When lowering vector shifts a check is performed to see if the value to shift by
[oota-llvm.git] / lib / Target / ARM / ARMISelLowering.cpp
1 //===-- ARMISelLowering.cpp - ARM DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that ARM uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "ARMISelLowering.h"
16 #include "ARMCallingConv.h"
17 #include "ARMConstantPoolValue.h"
18 #include "ARMMachineFunctionInfo.h"
19 #include "ARMPerfectShuffle.h"
20 #include "ARMSubtarget.h"
21 #include "ARMTargetMachine.h"
22 #include "ARMTargetObjectFile.h"
23 #include "MCTargetDesc/ARMAddressingModes.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/ADT/StringSwitch.h"
27 #include "llvm/CodeGen/CallingConvLower.h"
28 #include "llvm/CodeGen/IntrinsicLowering.h"
29 #include "llvm/CodeGen/MachineBasicBlock.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineJumpTableInfo.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/SelectionDAG.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/GlobalValue.h"
41 #include "llvm/IR/IRBuilder.h"
42 #include "llvm/IR/Instruction.h"
43 #include "llvm/IR/Instructions.h"
44 #include "llvm/IR/IntrinsicInst.h"
45 #include "llvm/IR/Intrinsics.h"
46 #include "llvm/IR/Type.h"
47 #include "llvm/MC/MCSectionMachO.h"
48 #include "llvm/Support/CommandLine.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Support/raw_ostream.h"
53 #include "llvm/Target/TargetOptions.h"
54 #include <utility>
55 using namespace llvm;
56
57 #define DEBUG_TYPE "arm-isel"
58
59 STATISTIC(NumTailCalls, "Number of tail calls");
60 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
61 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
62
63 static cl::opt<bool>
64 ARMInterworking("arm-interworking", cl::Hidden,
65   cl::desc("Enable / disable ARM interworking (for debugging only)"),
66   cl::init(true));
67
68 namespace {
69   class ARMCCState : public CCState {
70   public:
71     ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
72                SmallVectorImpl<CCValAssign> &locs, LLVMContext &C,
73                ParmContext PC)
74         : CCState(CC, isVarArg, MF, locs, C) {
75       assert(((PC == Call) || (PC == Prologue)) &&
76              "ARMCCState users must specify whether their context is call"
77              "or prologue generation.");
78       CallOrPrologue = PC;
79     }
80   };
81 }
82
83 // The APCS parameter registers.
84 static const MCPhysReg GPRArgRegs[] = {
85   ARM::R0, ARM::R1, ARM::R2, ARM::R3
86 };
87
88 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
89                                        MVT PromotedBitwiseVT) {
90   if (VT != PromotedLdStVT) {
91     setOperationAction(ISD::LOAD, VT, Promote);
92     AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
93
94     setOperationAction(ISD::STORE, VT, Promote);
95     AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
96   }
97
98   MVT ElemTy = VT.getVectorElementType();
99   if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
100     setOperationAction(ISD::SETCC, VT, Custom);
101   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
102   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
103   if (ElemTy == MVT::i32) {
104     setOperationAction(ISD::SINT_TO_FP, VT, Custom);
105     setOperationAction(ISD::UINT_TO_FP, VT, Custom);
106     setOperationAction(ISD::FP_TO_SINT, VT, Custom);
107     setOperationAction(ISD::FP_TO_UINT, VT, Custom);
108   } else {
109     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
110     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
111     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
112     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
113   }
114   setOperationAction(ISD::BUILD_VECTOR,      VT, Custom);
115   setOperationAction(ISD::VECTOR_SHUFFLE,    VT, Custom);
116   setOperationAction(ISD::CONCAT_VECTORS,    VT, Legal);
117   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
118   setOperationAction(ISD::SELECT,            VT, Expand);
119   setOperationAction(ISD::SELECT_CC,         VT, Expand);
120   setOperationAction(ISD::VSELECT,           VT, Expand);
121   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
122   if (VT.isInteger()) {
123     setOperationAction(ISD::SHL, VT, Custom);
124     setOperationAction(ISD::SRA, VT, Custom);
125     setOperationAction(ISD::SRL, VT, Custom);
126   }
127
128   // Promote all bit-wise operations.
129   if (VT.isInteger() && VT != PromotedBitwiseVT) {
130     setOperationAction(ISD::AND, VT, Promote);
131     AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
132     setOperationAction(ISD::OR,  VT, Promote);
133     AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
134     setOperationAction(ISD::XOR, VT, Promote);
135     AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
136   }
137
138   // Neon does not support vector divide/remainder operations.
139   setOperationAction(ISD::SDIV, VT, Expand);
140   setOperationAction(ISD::UDIV, VT, Expand);
141   setOperationAction(ISD::FDIV, VT, Expand);
142   setOperationAction(ISD::SREM, VT, Expand);
143   setOperationAction(ISD::UREM, VT, Expand);
144   setOperationAction(ISD::FREM, VT, Expand);
145
146   if (VT.isInteger()) {
147     setOperationAction(ISD::SABSDIFF, VT, Legal);
148     setOperationAction(ISD::UABSDIFF, VT, Legal);
149   }
150 }
151
152 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
153   addRegisterClass(VT, &ARM::DPRRegClass);
154   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
155 }
156
157 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
158   addRegisterClass(VT, &ARM::DPairRegClass);
159   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
160 }
161
162 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM,
163                                      const ARMSubtarget &STI)
164     : TargetLowering(TM), Subtarget(&STI) {
165   RegInfo = Subtarget->getRegisterInfo();
166   Itins = Subtarget->getInstrItineraryData();
167
168   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
169
170   if (Subtarget->isTargetMachO()) {
171     // Uses VFP for Thumb libfuncs if available.
172     if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
173         Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) {
174       // Single-precision floating-point arithmetic.
175       setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
176       setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
177       setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
178       setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
179
180       // Double-precision floating-point arithmetic.
181       setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
182       setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
183       setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
184       setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
185
186       // Single-precision comparisons.
187       setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
188       setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
189       setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
190       setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
191       setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
192       setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
193       setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
194       setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
195
196       setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
197       setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
198       setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
199       setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
200       setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
201       setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
202       setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
203       setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
204
205       // Double-precision comparisons.
206       setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
207       setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
208       setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
209       setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
210       setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
211       setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
212       setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
213       setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
214
215       setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
216       setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
217       setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
218       setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
219       setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
220       setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
221       setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
222       setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
223
224       // Floating-point to integer conversions.
225       // i64 conversions are done via library routines even when generating VFP
226       // instructions, so use the same ones.
227       setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
228       setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
229       setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
230       setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
231
232       // Conversions between floating types.
233       setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
234       setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
235
236       // Integer to floating-point conversions.
237       // i64 conversions are done via library routines even when generating VFP
238       // instructions, so use the same ones.
239       // FIXME: There appears to be some naming inconsistency in ARM libgcc:
240       // e.g., __floatunsidf vs. __floatunssidfvfp.
241       setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
242       setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
243       setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
244       setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
245     }
246   }
247
248   // These libcalls are not available in 32-bit.
249   setLibcallName(RTLIB::SHL_I128, nullptr);
250   setLibcallName(RTLIB::SRL_I128, nullptr);
251   setLibcallName(RTLIB::SRA_I128, nullptr);
252
253   if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO() &&
254       !Subtarget->isTargetWindows()) {
255     static const struct {
256       const RTLIB::Libcall Op;
257       const char * const Name;
258       const CallingConv::ID CC;
259       const ISD::CondCode Cond;
260     } LibraryCalls[] = {
261       // Double-precision floating-point arithmetic helper functions
262       // RTABI chapter 4.1.2, Table 2
263       { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
264       { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
265       { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
266       { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
267
268       // Double-precision floating-point comparison helper functions
269       // RTABI chapter 4.1.2, Table 3
270       { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
271       { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
272       { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
273       { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
274       { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
275       { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
276       { RTLIB::UO_F64,  "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
277       { RTLIB::O_F64,   "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
278
279       // Single-precision floating-point arithmetic helper functions
280       // RTABI chapter 4.1.2, Table 4
281       { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
282       { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
283       { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
284       { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
285
286       // Single-precision floating-point comparison helper functions
287       // RTABI chapter 4.1.2, Table 5
288       { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
289       { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
290       { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
291       { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
292       { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
293       { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
294       { RTLIB::UO_F32,  "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
295       { RTLIB::O_F32,   "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
296
297       // Floating-point to integer conversions.
298       // RTABI chapter 4.1.2, Table 6
299       { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
300       { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
301       { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
302       { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
303       { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
304       { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
305       { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
306       { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
307
308       // Conversions between floating types.
309       // RTABI chapter 4.1.2, Table 7
310       { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
311       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
312       { RTLIB::FPEXT_F32_F64,   "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
313
314       // Integer to floating-point conversions.
315       // RTABI chapter 4.1.2, Table 8
316       { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
317       { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
318       { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
319       { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
320       { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
321       { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
322       { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
323       { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
324
325       // Long long helper functions
326       // RTABI chapter 4.2, Table 9
327       { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
328       { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
329       { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
330       { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
331
332       // Integer division functions
333       // RTABI chapter 4.3.1
334       { RTLIB::SDIV_I8,  "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
335       { RTLIB::SDIV_I16, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
336       { RTLIB::SDIV_I32, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
337       { RTLIB::SDIV_I64, "__aeabi_ldivmod",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
338       { RTLIB::UDIV_I8,  "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
339       { RTLIB::UDIV_I16, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
340       { RTLIB::UDIV_I32, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
341       { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
342
343       // Memory operations
344       // RTABI chapter 4.3.4
345       { RTLIB::MEMCPY,  "__aeabi_memcpy",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
346       { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
347       { RTLIB::MEMSET,  "__aeabi_memset",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
348     };
349
350     for (const auto &LC : LibraryCalls) {
351       setLibcallName(LC.Op, LC.Name);
352       setLibcallCallingConv(LC.Op, LC.CC);
353       if (LC.Cond != ISD::SETCC_INVALID)
354         setCmpLibcallCC(LC.Op, LC.Cond);
355     }
356   }
357
358   if (Subtarget->isTargetWindows()) {
359     static const struct {
360       const RTLIB::Libcall Op;
361       const char * const Name;
362       const CallingConv::ID CC;
363     } LibraryCalls[] = {
364       { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
365       { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
366       { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
367       { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
368       { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
369       { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
370       { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
371       { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
372     };
373
374     for (const auto &LC : LibraryCalls) {
375       setLibcallName(LC.Op, LC.Name);
376       setLibcallCallingConv(LC.Op, LC.CC);
377     }
378   }
379
380   // Use divmod compiler-rt calls for iOS 5.0 and later.
381   if (Subtarget->getTargetTriple().isiOS() &&
382       !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
383     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
384     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
385   }
386
387   // The half <-> float conversion functions are always soft-float, but are
388   // needed for some targets which use a hard-float calling convention by
389   // default.
390   if (Subtarget->isAAPCS_ABI()) {
391     setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
392     setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
393     setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
394   } else {
395     setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
396     setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
397     setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
398   }
399
400   if (Subtarget->isThumb1Only())
401     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
402   else
403     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
404   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
405       !Subtarget->isThumb1Only()) {
406     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
407     addRegisterClass(MVT::f64, &ARM::DPRRegClass);
408   }
409
410   for (MVT VT : MVT::vector_valuetypes()) {
411     for (MVT InnerVT : MVT::vector_valuetypes()) {
412       setTruncStoreAction(VT, InnerVT, Expand);
413       setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
414       setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
415       setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
416     }
417
418     setOperationAction(ISD::MULHS, VT, Expand);
419     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
420     setOperationAction(ISD::MULHU, VT, Expand);
421     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
422
423     setOperationAction(ISD::BSWAP, VT, Expand);
424   }
425
426   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
427   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
428
429   setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
430   setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
431
432   if (Subtarget->hasNEON()) {
433     addDRTypeForNEON(MVT::v2f32);
434     addDRTypeForNEON(MVT::v8i8);
435     addDRTypeForNEON(MVT::v4i16);
436     addDRTypeForNEON(MVT::v2i32);
437     addDRTypeForNEON(MVT::v1i64);
438
439     addQRTypeForNEON(MVT::v4f32);
440     addQRTypeForNEON(MVT::v2f64);
441     addQRTypeForNEON(MVT::v16i8);
442     addQRTypeForNEON(MVT::v8i16);
443     addQRTypeForNEON(MVT::v4i32);
444     addQRTypeForNEON(MVT::v2i64);
445
446     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
447     // neither Neon nor VFP support any arithmetic operations on it.
448     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
449     // supported for v4f32.
450     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
451     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
452     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
453     // FIXME: Code duplication: FDIV and FREM are expanded always, see
454     // ARMTargetLowering::addTypeForNEON method for details.
455     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
456     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
457     // FIXME: Create unittest.
458     // In another words, find a way when "copysign" appears in DAG with vector
459     // operands.
460     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
461     // FIXME: Code duplication: SETCC has custom operation action, see
462     // ARMTargetLowering::addTypeForNEON method for details.
463     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
464     // FIXME: Create unittest for FNEG and for FABS.
465     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
466     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
467     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
468     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
469     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
470     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
471     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
472     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
473     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
474     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
475     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
476     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
477     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
478     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
479     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
480     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
481     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
482     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
483     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
484
485     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
486     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
487     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
488     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
489     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
490     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
491     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
492     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
493     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
494     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
495     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
496     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
497     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
498     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
499     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
500
501     // Mark v2f32 intrinsics.
502     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
503     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
504     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
505     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
506     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
507     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
508     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
509     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
510     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
511     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
512     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
513     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
514     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
515     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
516     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
517
518     // Neon does not support some operations on v1i64 and v2i64 types.
519     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
520     // Custom handling for some quad-vector types to detect VMULL.
521     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
522     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
523     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
524     // Custom handling for some vector types to avoid expensive expansions
525     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
526     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
527     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
528     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
529     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
530     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
531     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
532     // a destination type that is wider than the source, and nor does
533     // it have a FP_TO_[SU]INT instruction with a narrower destination than
534     // source.
535     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
536     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
537     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
538     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
539
540     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
541     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
542
543     // NEON does not have single instruction CTPOP for vectors with element
544     // types wider than 8-bits.  However, custom lowering can leverage the
545     // v8i8/v16i8 vcnt instruction.
546     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
547     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
548     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
549     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
550
551     // NEON does not have single instruction CTTZ for vectors.
552     setOperationAction(ISD::CTTZ, MVT::v8i8, Custom);
553     setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
554     setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
555     setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
556
557     setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
558     setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
559     setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
560     setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
561
562     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom);
563     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom);
564     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom);
565     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom);
566
567     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
568     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
569     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
570     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
571
572     // NEON only has FMA instructions as of VFP4.
573     if (!Subtarget->hasVFP4()) {
574       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
575       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
576     }
577
578     setTargetDAGCombine(ISD::INTRINSIC_VOID);
579     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
580     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
581     setTargetDAGCombine(ISD::SHL);
582     setTargetDAGCombine(ISD::SRL);
583     setTargetDAGCombine(ISD::SRA);
584     setTargetDAGCombine(ISD::SIGN_EXTEND);
585     setTargetDAGCombine(ISD::ZERO_EXTEND);
586     setTargetDAGCombine(ISD::ANY_EXTEND);
587     setTargetDAGCombine(ISD::SELECT_CC);
588     setTargetDAGCombine(ISD::BUILD_VECTOR);
589     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
590     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
591     setTargetDAGCombine(ISD::STORE);
592     setTargetDAGCombine(ISD::FP_TO_SINT);
593     setTargetDAGCombine(ISD::FP_TO_UINT);
594     setTargetDAGCombine(ISD::FDIV);
595     setTargetDAGCombine(ISD::LOAD);
596
597     // It is legal to extload from v4i8 to v4i16 or v4i32.
598     for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
599                    MVT::v2i32}) {
600       for (MVT VT : MVT::integer_vector_valuetypes()) {
601         setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
602         setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
603         setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
604       }
605     }
606   }
607
608   // ARM and Thumb2 support UMLAL/SMLAL.
609   if (!Subtarget->isThumb1Only())
610     setTargetDAGCombine(ISD::ADDC);
611
612   if (Subtarget->isFPOnlySP()) {
613     // When targetting a floating-point unit with only single-precision
614     // operations, f64 is legal for the few double-precision instructions which
615     // are present However, no double-precision operations other than moves,
616     // loads and stores are provided by the hardware.
617     setOperationAction(ISD::FADD,       MVT::f64, Expand);
618     setOperationAction(ISD::FSUB,       MVT::f64, Expand);
619     setOperationAction(ISD::FMUL,       MVT::f64, Expand);
620     setOperationAction(ISD::FMA,        MVT::f64, Expand);
621     setOperationAction(ISD::FDIV,       MVT::f64, Expand);
622     setOperationAction(ISD::FREM,       MVT::f64, Expand);
623     setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
624     setOperationAction(ISD::FGETSIGN,   MVT::f64, Expand);
625     setOperationAction(ISD::FNEG,       MVT::f64, Expand);
626     setOperationAction(ISD::FABS,       MVT::f64, Expand);
627     setOperationAction(ISD::FSQRT,      MVT::f64, Expand);
628     setOperationAction(ISD::FSIN,       MVT::f64, Expand);
629     setOperationAction(ISD::FCOS,       MVT::f64, Expand);
630     setOperationAction(ISD::FPOWI,      MVT::f64, Expand);
631     setOperationAction(ISD::FPOW,       MVT::f64, Expand);
632     setOperationAction(ISD::FLOG,       MVT::f64, Expand);
633     setOperationAction(ISD::FLOG2,      MVT::f64, Expand);
634     setOperationAction(ISD::FLOG10,     MVT::f64, Expand);
635     setOperationAction(ISD::FEXP,       MVT::f64, Expand);
636     setOperationAction(ISD::FEXP2,      MVT::f64, Expand);
637     setOperationAction(ISD::FCEIL,      MVT::f64, Expand);
638     setOperationAction(ISD::FTRUNC,     MVT::f64, Expand);
639     setOperationAction(ISD::FRINT,      MVT::f64, Expand);
640     setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
641     setOperationAction(ISD::FFLOOR,     MVT::f64, Expand);
642     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
643     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
644     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
645     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
646     setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
647     setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
648     setOperationAction(ISD::FP_ROUND,   MVT::f32, Custom);
649     setOperationAction(ISD::FP_EXTEND,  MVT::f64, Custom);
650   }
651
652   computeRegisterProperties(Subtarget->getRegisterInfo());
653
654   // ARM does not have floating-point extending loads.
655   for (MVT VT : MVT::fp_valuetypes()) {
656     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
657     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
658   }
659
660   // ... or truncating stores
661   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
662   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
663   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
664
665   // ARM does not have i1 sign extending load.
666   for (MVT VT : MVT::integer_valuetypes())
667     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
668
669   // ARM supports all 4 flavors of integer indexed load / store.
670   if (!Subtarget->isThumb1Only()) {
671     for (unsigned im = (unsigned)ISD::PRE_INC;
672          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
673       setIndexedLoadAction(im,  MVT::i1,  Legal);
674       setIndexedLoadAction(im,  MVT::i8,  Legal);
675       setIndexedLoadAction(im,  MVT::i16, Legal);
676       setIndexedLoadAction(im,  MVT::i32, Legal);
677       setIndexedStoreAction(im, MVT::i1,  Legal);
678       setIndexedStoreAction(im, MVT::i8,  Legal);
679       setIndexedStoreAction(im, MVT::i16, Legal);
680       setIndexedStoreAction(im, MVT::i32, Legal);
681     }
682   }
683
684   setOperationAction(ISD::SADDO, MVT::i32, Custom);
685   setOperationAction(ISD::UADDO, MVT::i32, Custom);
686   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
687   setOperationAction(ISD::USUBO, MVT::i32, Custom);
688
689   // i64 operation support.
690   setOperationAction(ISD::MUL,     MVT::i64, Expand);
691   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
692   if (Subtarget->isThumb1Only()) {
693     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
694     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
695   }
696   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
697       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
698     setOperationAction(ISD::MULHS, MVT::i32, Expand);
699
700   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
701   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
702   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
703   setOperationAction(ISD::SRL,       MVT::i64, Custom);
704   setOperationAction(ISD::SRA,       MVT::i64, Custom);
705
706   if (!Subtarget->isThumb1Only()) {
707     // FIXME: We should do this for Thumb1 as well.
708     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
709     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
710     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
711     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
712   }
713
714   // ARM does not have ROTL.
715   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
716   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
717   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
718   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
719     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
720
721   // These just redirect to CTTZ and CTLZ on ARM.
722   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
723   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
724
725   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
726
727   // Only ARMv6 has BSWAP.
728   if (!Subtarget->hasV6Ops())
729     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
730
731   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
732       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
733     // These are expanded into libcalls if the cpu doesn't have HW divider.
734     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
735     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
736   }
737
738   // FIXME: Also set divmod for SREM on EABI
739   setOperationAction(ISD::SREM,  MVT::i32, Expand);
740   setOperationAction(ISD::UREM,  MVT::i32, Expand);
741   // Register based DivRem for AEABI (RTABI 4.2)
742   if (Subtarget->isTargetAEABI()) {
743     setLibcallName(RTLIB::SDIVREM_I8,  "__aeabi_idivmod");
744     setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
745     setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
746     setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
747     setLibcallName(RTLIB::UDIVREM_I8,  "__aeabi_uidivmod");
748     setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
749     setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
750     setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
751
752     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
753     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
754     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
755     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
756     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
757     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
758     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
759     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
760
761     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
762     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
763   } else {
764     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
765     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
766   }
767
768   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
769   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
770   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
771   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
772   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
773
774   setOperationAction(ISD::TRAP, MVT::Other, Legal);
775
776   // Use the default implementation.
777   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
778   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
779   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
780   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
781   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
782   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
783
784   if (!Subtarget->isTargetMachO()) {
785     // Non-MachO platforms may return values in these registers via the
786     // personality function.
787     setExceptionPointerRegister(ARM::R0);
788     setExceptionSelectorRegister(ARM::R1);
789   }
790
791   if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
792     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
793   else
794     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
795
796   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
797   // the default expansion. If we are targeting a single threaded system,
798   // then set them all for expand so we can lower them later into their
799   // non-atomic form.
800   if (TM.Options.ThreadModel == ThreadModel::Single)
801     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
802   else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
803     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
804     // to ldrex/strex loops already.
805     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
806
807     // On v8, we have particularly efficient implementations of atomic fences
808     // if they can be combined with nearby atomic loads and stores.
809     if (!Subtarget->hasV8Ops()) {
810       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
811       setInsertFencesForAtomic(true);
812     }
813   } else {
814     // If there's anything we can use as a barrier, go through custom lowering
815     // for ATOMIC_FENCE.
816     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
817                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
818
819     // Set them all for expansion, which will force libcalls.
820     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
821     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
822     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
823     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
824     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
825     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
826     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
827     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
828     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
829     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
830     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
831     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
832     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
833     // Unordered/Monotonic case.
834     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
835     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
836   }
837
838   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
839
840   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
841   if (!Subtarget->hasV6Ops()) {
842     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
843     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
844   }
845   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
846
847   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
848       !Subtarget->isThumb1Only()) {
849     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
850     // iff target supports vfp2.
851     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
852     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
853   }
854
855   // We want to custom lower some of our intrinsics.
856   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
857   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
858   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
859   setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
860   if (Subtarget->isTargetDarwin())
861     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
862
863   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
864   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
865   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
866   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
867   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
868   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
869   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
870   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
871   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
872
873   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
874   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
875   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
876   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
877   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
878
879   // We don't support sin/cos/fmod/copysign/pow
880   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
881   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
882   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
883   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
884   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
885   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
886   setOperationAction(ISD::FREM,      MVT::f64, Expand);
887   setOperationAction(ISD::FREM,      MVT::f32, Expand);
888   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
889       !Subtarget->isThumb1Only()) {
890     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
891     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
892   }
893   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
894   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
895
896   if (!Subtarget->hasVFP4()) {
897     setOperationAction(ISD::FMA, MVT::f64, Expand);
898     setOperationAction(ISD::FMA, MVT::f32, Expand);
899   }
900
901   // Various VFP goodness
902   if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
903     // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
904     if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
905       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
906       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
907     }
908
909     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
910     if (!Subtarget->hasFP16()) {
911       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
912       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
913     }
914   }
915
916   // Combine sin / cos into one node or libcall if possible.
917   if (Subtarget->hasSinCos()) {
918     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
919     setLibcallName(RTLIB::SINCOS_F64, "sincos");
920     if (Subtarget->getTargetTriple().isiOS()) {
921       // For iOS, we don't want to the normal expansion of a libcall to
922       // sincos. We want to issue a libcall to __sincos_stret.
923       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
924       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
925     }
926   }
927
928   // FP-ARMv8 implements a lot of rounding-like FP operations.
929   if (Subtarget->hasFPARMv8()) {
930     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
931     setOperationAction(ISD::FCEIL, MVT::f32, Legal);
932     setOperationAction(ISD::FROUND, MVT::f32, Legal);
933     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
934     setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
935     setOperationAction(ISD::FRINT, MVT::f32, Legal);
936     if (!Subtarget->isFPOnlySP()) {
937       setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
938       setOperationAction(ISD::FCEIL, MVT::f64, Legal);
939       setOperationAction(ISD::FROUND, MVT::f64, Legal);
940       setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
941       setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
942       setOperationAction(ISD::FRINT, MVT::f64, Legal);
943     }
944   }
945   // We have target-specific dag combine patterns for the following nodes:
946   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
947   setTargetDAGCombine(ISD::ADD);
948   setTargetDAGCombine(ISD::SUB);
949   setTargetDAGCombine(ISD::MUL);
950   setTargetDAGCombine(ISD::AND);
951   setTargetDAGCombine(ISD::OR);
952   setTargetDAGCombine(ISD::XOR);
953
954   if (Subtarget->hasV6Ops())
955     setTargetDAGCombine(ISD::SRL);
956
957   setStackPointerRegisterToSaveRestore(ARM::SP);
958
959   if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
960       !Subtarget->hasVFP2())
961     setSchedulingPreference(Sched::RegPressure);
962   else
963     setSchedulingPreference(Sched::Hybrid);
964
965   //// temporary - rewrite interface to use type
966   MaxStoresPerMemset = 8;
967   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
968   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
969   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
970   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
971   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
972
973   // On ARM arguments smaller than 4 bytes are extended, so all arguments
974   // are at least 4 bytes aligned.
975   setMinStackArgumentAlignment(4);
976
977   // Prefer likely predicted branches to selects on out-of-order cores.
978   PredictableSelectIsExpensive = Subtarget->isLikeA9();
979
980   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
981 }
982
983 bool ARMTargetLowering::useSoftFloat() const {
984   return Subtarget->useSoftFloat();
985 }
986
987 // FIXME: It might make sense to define the representative register class as the
988 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
989 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
990 // SPR's representative would be DPR_VFP2. This should work well if register
991 // pressure tracking were modified such that a register use would increment the
992 // pressure of the register class's representative and all of it's super
993 // classes' representatives transitively. We have not implemented this because
994 // of the difficulty prior to coalescing of modeling operand register classes
995 // due to the common occurrence of cross class copies and subregister insertions
996 // and extractions.
997 std::pair<const TargetRegisterClass *, uint8_t>
998 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
999                                            MVT VT) const {
1000   const TargetRegisterClass *RRC = nullptr;
1001   uint8_t Cost = 1;
1002   switch (VT.SimpleTy) {
1003   default:
1004     return TargetLowering::findRepresentativeClass(TRI, VT);
1005   // Use DPR as representative register class for all floating point
1006   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1007   // the cost is 1 for both f32 and f64.
1008   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1009   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1010     RRC = &ARM::DPRRegClass;
1011     // When NEON is used for SP, only half of the register file is available
1012     // because operations that define both SP and DP results will be constrained
1013     // to the VFP2 class (D0-D15). We currently model this constraint prior to
1014     // coalescing by double-counting the SP regs. See the FIXME above.
1015     if (Subtarget->useNEONForSinglePrecisionFP())
1016       Cost = 2;
1017     break;
1018   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1019   case MVT::v4f32: case MVT::v2f64:
1020     RRC = &ARM::DPRRegClass;
1021     Cost = 2;
1022     break;
1023   case MVT::v4i64:
1024     RRC = &ARM::DPRRegClass;
1025     Cost = 4;
1026     break;
1027   case MVT::v8i64:
1028     RRC = &ARM::DPRRegClass;
1029     Cost = 8;
1030     break;
1031   }
1032   return std::make_pair(RRC, Cost);
1033 }
1034
1035 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1036   switch ((ARMISD::NodeType)Opcode) {
1037   case ARMISD::FIRST_NUMBER:  break;
1038   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1039   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1040   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1041   case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1042   case ARMISD::CALL:          return "ARMISD::CALL";
1043   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1044   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1045   case ARMISD::tCALL:         return "ARMISD::tCALL";
1046   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1047   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1048   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1049   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1050   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1051   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1052   case ARMISD::CMP:           return "ARMISD::CMP";
1053   case ARMISD::CMN:           return "ARMISD::CMN";
1054   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1055   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1056   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1057   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1058   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1059
1060   case ARMISD::CMOV:          return "ARMISD::CMOV";
1061
1062   case ARMISD::RBIT:          return "ARMISD::RBIT";
1063
1064   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1065   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1066   case ARMISD::RRX:           return "ARMISD::RRX";
1067
1068   case ARMISD::ADDC:          return "ARMISD::ADDC";
1069   case ARMISD::ADDE:          return "ARMISD::ADDE";
1070   case ARMISD::SUBC:          return "ARMISD::SUBC";
1071   case ARMISD::SUBE:          return "ARMISD::SUBE";
1072
1073   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1074   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1075
1076   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1077   case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1078   case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1079
1080   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1081
1082   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1083
1084   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1085
1086   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1087
1088   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1089
1090   case ARMISD::WIN__CHKSTK:   return "ARMISD:::WIN__CHKSTK";
1091
1092   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1093   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1094   case ARMISD::VCGE:          return "ARMISD::VCGE";
1095   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1096   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1097   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1098   case ARMISD::VCGT:          return "ARMISD::VCGT";
1099   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1100   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1101   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1102   case ARMISD::VTST:          return "ARMISD::VTST";
1103
1104   case ARMISD::VSHL:          return "ARMISD::VSHL";
1105   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1106   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1107   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1108   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1109   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1110   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1111   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1112   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1113   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1114   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1115   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1116   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1117   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1118   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1119   case ARMISD::VSLI:          return "ARMISD::VSLI";
1120   case ARMISD::VSRI:          return "ARMISD::VSRI";
1121   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1122   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1123   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1124   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1125   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1126   case ARMISD::VDUP:          return "ARMISD::VDUP";
1127   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1128   case ARMISD::VEXT:          return "ARMISD::VEXT";
1129   case ARMISD::VREV64:        return "ARMISD::VREV64";
1130   case ARMISD::VREV32:        return "ARMISD::VREV32";
1131   case ARMISD::VREV16:        return "ARMISD::VREV16";
1132   case ARMISD::VZIP:          return "ARMISD::VZIP";
1133   case ARMISD::VUZP:          return "ARMISD::VUZP";
1134   case ARMISD::VTRN:          return "ARMISD::VTRN";
1135   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1136   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1137   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1138   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1139   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1140   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1141   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1142   case ARMISD::FMAX:          return "ARMISD::FMAX";
1143   case ARMISD::FMIN:          return "ARMISD::FMIN";
1144   case ARMISD::VMAXNM:        return "ARMISD::VMAX";
1145   case ARMISD::VMINNM:        return "ARMISD::VMIN";
1146   case ARMISD::BFI:           return "ARMISD::BFI";
1147   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1148   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1149   case ARMISD::VBSL:          return "ARMISD::VBSL";
1150   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1151   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1152   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1153   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1154   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1155   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1156   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1157   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1158   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1159   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1160   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1161   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1162   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1163   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1164   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1165   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1166   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1167   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1168   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1169   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1170   }
1171   return nullptr;
1172 }
1173
1174 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1175                                           EVT VT) const {
1176   if (!VT.isVector())
1177     return getPointerTy(DL);
1178   return VT.changeVectorElementTypeToInteger();
1179 }
1180
1181 /// getRegClassFor - Return the register class that should be used for the
1182 /// specified value type.
1183 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1184   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1185   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1186   // load / store 4 to 8 consecutive D registers.
1187   if (Subtarget->hasNEON()) {
1188     if (VT == MVT::v4i64)
1189       return &ARM::QQPRRegClass;
1190     if (VT == MVT::v8i64)
1191       return &ARM::QQQQPRRegClass;
1192   }
1193   return TargetLowering::getRegClassFor(VT);
1194 }
1195
1196 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1197 // source/dest is aligned and the copy size is large enough. We therefore want
1198 // to align such objects passed to memory intrinsics.
1199 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1200                                                unsigned &PrefAlign) const {
1201   if (!isa<MemIntrinsic>(CI))
1202     return false;
1203   MinSize = 8;
1204   // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1205   // cycle faster than 4-byte aligned LDM.
1206   PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1207   return true;
1208 }
1209
1210 // Create a fast isel object.
1211 FastISel *
1212 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1213                                   const TargetLibraryInfo *libInfo) const {
1214   return ARM::createFastISel(funcInfo, libInfo);
1215 }
1216
1217 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1218   unsigned NumVals = N->getNumValues();
1219   if (!NumVals)
1220     return Sched::RegPressure;
1221
1222   for (unsigned i = 0; i != NumVals; ++i) {
1223     EVT VT = N->getValueType(i);
1224     if (VT == MVT::Glue || VT == MVT::Other)
1225       continue;
1226     if (VT.isFloatingPoint() || VT.isVector())
1227       return Sched::ILP;
1228   }
1229
1230   if (!N->isMachineOpcode())
1231     return Sched::RegPressure;
1232
1233   // Load are scheduled for latency even if there instruction itinerary
1234   // is not available.
1235   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1236   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1237
1238   if (MCID.getNumDefs() == 0)
1239     return Sched::RegPressure;
1240   if (!Itins->isEmpty() &&
1241       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1242     return Sched::ILP;
1243
1244   return Sched::RegPressure;
1245 }
1246
1247 //===----------------------------------------------------------------------===//
1248 // Lowering Code
1249 //===----------------------------------------------------------------------===//
1250
1251 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1252 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1253   switch (CC) {
1254   default: llvm_unreachable("Unknown condition code!");
1255   case ISD::SETNE:  return ARMCC::NE;
1256   case ISD::SETEQ:  return ARMCC::EQ;
1257   case ISD::SETGT:  return ARMCC::GT;
1258   case ISD::SETGE:  return ARMCC::GE;
1259   case ISD::SETLT:  return ARMCC::LT;
1260   case ISD::SETLE:  return ARMCC::LE;
1261   case ISD::SETUGT: return ARMCC::HI;
1262   case ISD::SETUGE: return ARMCC::HS;
1263   case ISD::SETULT: return ARMCC::LO;
1264   case ISD::SETULE: return ARMCC::LS;
1265   }
1266 }
1267
1268 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1269 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1270                         ARMCC::CondCodes &CondCode2) {
1271   CondCode2 = ARMCC::AL;
1272   switch (CC) {
1273   default: llvm_unreachable("Unknown FP condition!");
1274   case ISD::SETEQ:
1275   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1276   case ISD::SETGT:
1277   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1278   case ISD::SETGE:
1279   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1280   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1281   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1282   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1283   case ISD::SETO:   CondCode = ARMCC::VC; break;
1284   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1285   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1286   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1287   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1288   case ISD::SETLT:
1289   case ISD::SETULT: CondCode = ARMCC::LT; break;
1290   case ISD::SETLE:
1291   case ISD::SETULE: CondCode = ARMCC::LE; break;
1292   case ISD::SETNE:
1293   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1294   }
1295 }
1296
1297 //===----------------------------------------------------------------------===//
1298 //                      Calling Convention Implementation
1299 //===----------------------------------------------------------------------===//
1300
1301 #include "ARMGenCallingConv.inc"
1302
1303 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1304 /// account presence of floating point hardware and calling convention
1305 /// limitations, such as support for variadic functions.
1306 CallingConv::ID
1307 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1308                                            bool isVarArg) const {
1309   switch (CC) {
1310   default:
1311     llvm_unreachable("Unsupported calling convention");
1312   case CallingConv::ARM_AAPCS:
1313   case CallingConv::ARM_APCS:
1314   case CallingConv::GHC:
1315     return CC;
1316   case CallingConv::ARM_AAPCS_VFP:
1317     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1318   case CallingConv::C:
1319     if (!Subtarget->isAAPCS_ABI())
1320       return CallingConv::ARM_APCS;
1321     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1322              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1323              !isVarArg)
1324       return CallingConv::ARM_AAPCS_VFP;
1325     else
1326       return CallingConv::ARM_AAPCS;
1327   case CallingConv::Fast:
1328     if (!Subtarget->isAAPCS_ABI()) {
1329       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1330         return CallingConv::Fast;
1331       return CallingConv::ARM_APCS;
1332     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1333       return CallingConv::ARM_AAPCS_VFP;
1334     else
1335       return CallingConv::ARM_AAPCS;
1336   }
1337 }
1338
1339 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1340 /// CallingConvention.
1341 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1342                                                  bool Return,
1343                                                  bool isVarArg) const {
1344   switch (getEffectiveCallingConv(CC, isVarArg)) {
1345   default:
1346     llvm_unreachable("Unsupported calling convention");
1347   case CallingConv::ARM_APCS:
1348     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1349   case CallingConv::ARM_AAPCS:
1350     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1351   case CallingConv::ARM_AAPCS_VFP:
1352     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1353   case CallingConv::Fast:
1354     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1355   case CallingConv::GHC:
1356     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1357   }
1358 }
1359
1360 /// LowerCallResult - Lower the result values of a call into the
1361 /// appropriate copies out of appropriate physical registers.
1362 SDValue
1363 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1364                                    CallingConv::ID CallConv, bool isVarArg,
1365                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1366                                    SDLoc dl, SelectionDAG &DAG,
1367                                    SmallVectorImpl<SDValue> &InVals,
1368                                    bool isThisReturn, SDValue ThisVal) const {
1369
1370   // Assign locations to each value returned by this call.
1371   SmallVector<CCValAssign, 16> RVLocs;
1372   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1373                     *DAG.getContext(), Call);
1374   CCInfo.AnalyzeCallResult(Ins,
1375                            CCAssignFnForNode(CallConv, /* Return*/ true,
1376                                              isVarArg));
1377
1378   // Copy all of the result registers out of their specified physreg.
1379   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1380     CCValAssign VA = RVLocs[i];
1381
1382     // Pass 'this' value directly from the argument to return value, to avoid
1383     // reg unit interference
1384     if (i == 0 && isThisReturn) {
1385       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1386              "unexpected return calling convention register assignment");
1387       InVals.push_back(ThisVal);
1388       continue;
1389     }
1390
1391     SDValue Val;
1392     if (VA.needsCustom()) {
1393       // Handle f64 or half of a v2f64.
1394       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1395                                       InFlag);
1396       Chain = Lo.getValue(1);
1397       InFlag = Lo.getValue(2);
1398       VA = RVLocs[++i]; // skip ahead to next loc
1399       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1400                                       InFlag);
1401       Chain = Hi.getValue(1);
1402       InFlag = Hi.getValue(2);
1403       if (!Subtarget->isLittle())
1404         std::swap (Lo, Hi);
1405       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1406
1407       if (VA.getLocVT() == MVT::v2f64) {
1408         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1409         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1410                           DAG.getConstant(0, dl, MVT::i32));
1411
1412         VA = RVLocs[++i]; // skip ahead to next loc
1413         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1414         Chain = Lo.getValue(1);
1415         InFlag = Lo.getValue(2);
1416         VA = RVLocs[++i]; // skip ahead to next loc
1417         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1418         Chain = Hi.getValue(1);
1419         InFlag = Hi.getValue(2);
1420         if (!Subtarget->isLittle())
1421           std::swap (Lo, Hi);
1422         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1423         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1424                           DAG.getConstant(1, dl, MVT::i32));
1425       }
1426     } else {
1427       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1428                                InFlag);
1429       Chain = Val.getValue(1);
1430       InFlag = Val.getValue(2);
1431     }
1432
1433     switch (VA.getLocInfo()) {
1434     default: llvm_unreachable("Unknown loc info!");
1435     case CCValAssign::Full: break;
1436     case CCValAssign::BCvt:
1437       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1438       break;
1439     }
1440
1441     InVals.push_back(Val);
1442   }
1443
1444   return Chain;
1445 }
1446
1447 /// LowerMemOpCallTo - Store the argument to the stack.
1448 SDValue
1449 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1450                                     SDValue StackPtr, SDValue Arg,
1451                                     SDLoc dl, SelectionDAG &DAG,
1452                                     const CCValAssign &VA,
1453                                     ISD::ArgFlagsTy Flags) const {
1454   unsigned LocMemOffset = VA.getLocMemOffset();
1455   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1456   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1457                        StackPtr, PtrOff);
1458   return DAG.getStore(Chain, dl, Arg, PtrOff,
1459                       MachinePointerInfo::getStack(LocMemOffset),
1460                       false, false, 0);
1461 }
1462
1463 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1464                                          SDValue Chain, SDValue &Arg,
1465                                          RegsToPassVector &RegsToPass,
1466                                          CCValAssign &VA, CCValAssign &NextVA,
1467                                          SDValue &StackPtr,
1468                                          SmallVectorImpl<SDValue> &MemOpChains,
1469                                          ISD::ArgFlagsTy Flags) const {
1470
1471   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1472                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1473   unsigned id = Subtarget->isLittle() ? 0 : 1;
1474   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1475
1476   if (NextVA.isRegLoc())
1477     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1478   else {
1479     assert(NextVA.isMemLoc());
1480     if (!StackPtr.getNode())
1481       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
1482                                     getPointerTy(DAG.getDataLayout()));
1483
1484     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1485                                            dl, DAG, NextVA,
1486                                            Flags));
1487   }
1488 }
1489
1490 /// LowerCall - Lowering a call into a callseq_start <-
1491 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1492 /// nodes.
1493 SDValue
1494 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1495                              SmallVectorImpl<SDValue> &InVals) const {
1496   SelectionDAG &DAG                     = CLI.DAG;
1497   SDLoc &dl                             = CLI.DL;
1498   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1499   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1500   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1501   SDValue Chain                         = CLI.Chain;
1502   SDValue Callee                        = CLI.Callee;
1503   bool &isTailCall                      = CLI.IsTailCall;
1504   CallingConv::ID CallConv              = CLI.CallConv;
1505   bool doesNotRet                       = CLI.DoesNotReturn;
1506   bool isVarArg                         = CLI.IsVarArg;
1507
1508   MachineFunction &MF = DAG.getMachineFunction();
1509   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1510   bool isThisReturn   = false;
1511   bool isSibCall      = false;
1512   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
1513
1514   // Disable tail calls if they're not supported.
1515   if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
1516     isTailCall = false;
1517
1518   if (isTailCall) {
1519     // Check if it's really possible to do a tail call.
1520     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1521                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1522                                                    Outs, OutVals, Ins, DAG);
1523     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1524       report_fatal_error("failed to perform tail call elimination on a call "
1525                          "site marked musttail");
1526     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1527     // detected sibcalls.
1528     if (isTailCall) {
1529       ++NumTailCalls;
1530       isSibCall = true;
1531     }
1532   }
1533
1534   // Analyze operands of the call, assigning locations to each operand.
1535   SmallVector<CCValAssign, 16> ArgLocs;
1536   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1537                     *DAG.getContext(), Call);
1538   CCInfo.AnalyzeCallOperands(Outs,
1539                              CCAssignFnForNode(CallConv, /* Return*/ false,
1540                                                isVarArg));
1541
1542   // Get a count of how many bytes are to be pushed on the stack.
1543   unsigned NumBytes = CCInfo.getNextStackOffset();
1544
1545   // For tail calls, memory operands are available in our caller's stack.
1546   if (isSibCall)
1547     NumBytes = 0;
1548
1549   // Adjust the stack pointer for the new arguments...
1550   // These operations are automatically eliminated by the prolog/epilog pass
1551   if (!isSibCall)
1552     Chain = DAG.getCALLSEQ_START(Chain,
1553                                  DAG.getIntPtrConstant(NumBytes, dl, true), dl);
1554
1555   SDValue StackPtr =
1556       DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
1557
1558   RegsToPassVector RegsToPass;
1559   SmallVector<SDValue, 8> MemOpChains;
1560
1561   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1562   // of tail call optimization, arguments are handled later.
1563   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1564        i != e;
1565        ++i, ++realArgIdx) {
1566     CCValAssign &VA = ArgLocs[i];
1567     SDValue Arg = OutVals[realArgIdx];
1568     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1569     bool isByVal = Flags.isByVal();
1570
1571     // Promote the value if needed.
1572     switch (VA.getLocInfo()) {
1573     default: llvm_unreachable("Unknown loc info!");
1574     case CCValAssign::Full: break;
1575     case CCValAssign::SExt:
1576       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1577       break;
1578     case CCValAssign::ZExt:
1579       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1580       break;
1581     case CCValAssign::AExt:
1582       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1583       break;
1584     case CCValAssign::BCvt:
1585       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1586       break;
1587     }
1588
1589     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1590     if (VA.needsCustom()) {
1591       if (VA.getLocVT() == MVT::v2f64) {
1592         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1593                                   DAG.getConstant(0, dl, MVT::i32));
1594         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1595                                   DAG.getConstant(1, dl, MVT::i32));
1596
1597         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1598                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1599
1600         VA = ArgLocs[++i]; // skip ahead to next loc
1601         if (VA.isRegLoc()) {
1602           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1603                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1604         } else {
1605           assert(VA.isMemLoc());
1606
1607           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1608                                                  dl, DAG, VA, Flags));
1609         }
1610       } else {
1611         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1612                          StackPtr, MemOpChains, Flags);
1613       }
1614     } else if (VA.isRegLoc()) {
1615       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1616         assert(VA.getLocVT() == MVT::i32 &&
1617                "unexpected calling convention register assignment");
1618         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1619                "unexpected use of 'returned'");
1620         isThisReturn = true;
1621       }
1622       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1623     } else if (isByVal) {
1624       assert(VA.isMemLoc());
1625       unsigned offset = 0;
1626
1627       // True if this byval aggregate will be split between registers
1628       // and memory.
1629       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1630       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1631
1632       if (CurByValIdx < ByValArgsCount) {
1633
1634         unsigned RegBegin, RegEnd;
1635         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1636
1637         EVT PtrVT =
1638             DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
1639         unsigned int i, j;
1640         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1641           SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1642           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1643           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1644                                      MachinePointerInfo(),
1645                                      false, false, false,
1646                                      DAG.InferPtrAlignment(AddArg));
1647           MemOpChains.push_back(Load.getValue(1));
1648           RegsToPass.push_back(std::make_pair(j, Load));
1649         }
1650
1651         // If parameter size outsides register area, "offset" value
1652         // helps us to calculate stack slot for remained part properly.
1653         offset = RegEnd - RegBegin;
1654
1655         CCInfo.nextInRegsParam();
1656       }
1657
1658       if (Flags.getByValSize() > 4*offset) {
1659         auto PtrVT = getPointerTy(DAG.getDataLayout());
1660         unsigned LocMemOffset = VA.getLocMemOffset();
1661         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1662         SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
1663         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1664         SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
1665         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1666                                            MVT::i32);
1667         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1668                                             MVT::i32);
1669
1670         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1671         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1672         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1673                                           Ops));
1674       }
1675     } else if (!isSibCall) {
1676       assert(VA.isMemLoc());
1677
1678       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1679                                              dl, DAG, VA, Flags));
1680     }
1681   }
1682
1683   if (!MemOpChains.empty())
1684     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1685
1686   // Build a sequence of copy-to-reg nodes chained together with token chain
1687   // and flag operands which copy the outgoing args into the appropriate regs.
1688   SDValue InFlag;
1689   // Tail call byval lowering might overwrite argument registers so in case of
1690   // tail call optimization the copies to registers are lowered later.
1691   if (!isTailCall)
1692     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1693       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1694                                RegsToPass[i].second, InFlag);
1695       InFlag = Chain.getValue(1);
1696     }
1697
1698   // For tail calls lower the arguments to the 'real' stack slot.
1699   if (isTailCall) {
1700     // Force all the incoming stack arguments to be loaded from the stack
1701     // before any new outgoing arguments are stored to the stack, because the
1702     // outgoing stack slots may alias the incoming argument stack slots, and
1703     // the alias isn't otherwise explicit. This is slightly more conservative
1704     // than necessary, because it means that each store effectively depends
1705     // on every argument instead of just those arguments it would clobber.
1706
1707     // Do not flag preceding copytoreg stuff together with the following stuff.
1708     InFlag = SDValue();
1709     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1710       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1711                                RegsToPass[i].second, InFlag);
1712       InFlag = Chain.getValue(1);
1713     }
1714     InFlag = SDValue();
1715   }
1716
1717   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1718   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1719   // node so that legalize doesn't hack it.
1720   bool isDirect = false;
1721   bool isARMFunc = false;
1722   bool isLocalARMFunc = false;
1723   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1724   auto PtrVt = getPointerTy(DAG.getDataLayout());
1725
1726   if (Subtarget->genLongCalls()) {
1727     assert((Subtarget->isTargetWindows() ||
1728             getTargetMachine().getRelocationModel() == Reloc::Static) &&
1729            "long-calls with non-static relocation model!");
1730     // Handle a global address or an external symbol. If it's not one of
1731     // those, the target's already in a register, so we don't need to do
1732     // anything extra.
1733     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1734       const GlobalValue *GV = G->getGlobal();
1735       // Create a constant pool entry for the callee address
1736       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1737       ARMConstantPoolValue *CPV =
1738         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1739
1740       // Get the address of the callee into a register
1741       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1742       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1743       Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), CPAddr,
1744                            MachinePointerInfo::getConstantPool(), false, false,
1745                            false, 0);
1746     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1747       const char *Sym = S->getSymbol();
1748
1749       // Create a constant pool entry for the callee address
1750       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1751       ARMConstantPoolValue *CPV =
1752         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1753                                       ARMPCLabelIndex, 0);
1754       // Get the address of the callee into a register
1755       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1756       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1757       Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), CPAddr,
1758                            MachinePointerInfo::getConstantPool(), false, false,
1759                            false, 0);
1760     }
1761   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1762     const GlobalValue *GV = G->getGlobal();
1763     isDirect = true;
1764     bool isDef = GV->isStrongDefinitionForLinker();
1765     bool isStub = (!isDef && Subtarget->isTargetMachO()) &&
1766                    getTargetMachine().getRelocationModel() != Reloc::Static;
1767     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1768     // ARM call to a local ARM function is predicable.
1769     isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
1770     // tBX takes a register source operand.
1771     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1772       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1773       Callee = DAG.getNode(
1774           ARMISD::WrapperPIC, dl, PtrVt,
1775           DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
1776       Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), Callee,
1777                            MachinePointerInfo::getGOT(), false, false, true, 0);
1778     } else if (Subtarget->isTargetCOFF()) {
1779       assert(Subtarget->isTargetWindows() &&
1780              "Windows is the only supported COFF target");
1781       unsigned TargetFlags = GV->hasDLLImportStorageClass()
1782                                  ? ARMII::MO_DLLIMPORT
1783                                  : ARMII::MO_NO_FLAG;
1784       Callee =
1785           DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0, TargetFlags);
1786       if (GV->hasDLLImportStorageClass())
1787         Callee =
1788             DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
1789                         DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
1790                         MachinePointerInfo::getGOT(), false, false, false, 0);
1791     } else {
1792       // On ELF targets for PIC code, direct calls should go through the PLT
1793       unsigned OpFlags = 0;
1794       if (Subtarget->isTargetELF() &&
1795           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1796         OpFlags = ARMII::MO_PLT;
1797       Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, OpFlags);
1798     }
1799   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1800     isDirect = true;
1801     bool isStub = Subtarget->isTargetMachO() &&
1802                   getTargetMachine().getRelocationModel() != Reloc::Static;
1803     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1804     // tBX takes a register source operand.
1805     const char *Sym = S->getSymbol();
1806     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1807       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1808       ARMConstantPoolValue *CPV =
1809         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1810                                       ARMPCLabelIndex, 4);
1811       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1812       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1813       Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), CPAddr,
1814                            MachinePointerInfo::getConstantPool(), false, false,
1815                            false, 0);
1816       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
1817       Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
1818     } else {
1819       unsigned OpFlags = 0;
1820       // On ELF targets for PIC code, direct calls should go through the PLT
1821       if (Subtarget->isTargetELF() &&
1822                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1823         OpFlags = ARMII::MO_PLT;
1824       Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, OpFlags);
1825     }
1826   }
1827
1828   // FIXME: handle tail calls differently.
1829   unsigned CallOpc;
1830   bool HasMinSizeAttr = MF.getFunction()->hasFnAttribute(Attribute::MinSize);
1831   if (Subtarget->isThumb()) {
1832     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1833       CallOpc = ARMISD::CALL_NOLINK;
1834     else
1835       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1836   } else {
1837     if (!isDirect && !Subtarget->hasV5TOps())
1838       CallOpc = ARMISD::CALL_NOLINK;
1839     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1840                // Emit regular call when code size is the priority
1841                !HasMinSizeAttr)
1842       // "mov lr, pc; b _foo" to avoid confusing the RSP
1843       CallOpc = ARMISD::CALL_NOLINK;
1844     else
1845       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1846   }
1847
1848   std::vector<SDValue> Ops;
1849   Ops.push_back(Chain);
1850   Ops.push_back(Callee);
1851
1852   // Add argument registers to the end of the list so that they are known live
1853   // into the call.
1854   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1855     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1856                                   RegsToPass[i].second.getValueType()));
1857
1858   // Add a register mask operand representing the call-preserved registers.
1859   if (!isTailCall) {
1860     const uint32_t *Mask;
1861     const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
1862     if (isThisReturn) {
1863       // For 'this' returns, use the R0-preserving mask if applicable
1864       Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
1865       if (!Mask) {
1866         // Set isThisReturn to false if the calling convention is not one that
1867         // allows 'returned' to be modeled in this way, so LowerCallResult does
1868         // not try to pass 'this' straight through
1869         isThisReturn = false;
1870         Mask = ARI->getCallPreservedMask(MF, CallConv);
1871       }
1872     } else
1873       Mask = ARI->getCallPreservedMask(MF, CallConv);
1874
1875     assert(Mask && "Missing call preserved mask for calling convention");
1876     Ops.push_back(DAG.getRegisterMask(Mask));
1877   }
1878
1879   if (InFlag.getNode())
1880     Ops.push_back(InFlag);
1881
1882   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1883   if (isTailCall) {
1884     MF.getFrameInfo()->setHasTailCall();
1885     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1886   }
1887
1888   // Returns a chain and a flag for retval copy to use.
1889   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1890   InFlag = Chain.getValue(1);
1891
1892   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
1893                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
1894   if (!Ins.empty())
1895     InFlag = Chain.getValue(1);
1896
1897   // Handle result values, copying them out of physregs into vregs that we
1898   // return.
1899   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1900                          InVals, isThisReturn,
1901                          isThisReturn ? OutVals[0] : SDValue());
1902 }
1903
1904 /// HandleByVal - Every parameter *after* a byval parameter is passed
1905 /// on the stack.  Remember the next parameter register to allocate,
1906 /// and then confiscate the rest of the parameter registers to insure
1907 /// this.
1908 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
1909                                     unsigned Align) const {
1910   assert((State->getCallOrPrologue() == Prologue ||
1911           State->getCallOrPrologue() == Call) &&
1912          "unhandled ParmContext");
1913
1914   // Byval (as with any stack) slots are always at least 4 byte aligned.
1915   Align = std::max(Align, 4U);
1916
1917   unsigned Reg = State->AllocateReg(GPRArgRegs);
1918   if (!Reg)
1919     return;
1920
1921   unsigned AlignInRegs = Align / 4;
1922   unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
1923   for (unsigned i = 0; i < Waste; ++i)
1924     Reg = State->AllocateReg(GPRArgRegs);
1925
1926   if (!Reg)
1927     return;
1928
1929   unsigned Excess = 4 * (ARM::R4 - Reg);
1930
1931   // Special case when NSAA != SP and parameter size greater than size of
1932   // all remained GPR regs. In that case we can't split parameter, we must
1933   // send it to stack. We also must set NCRN to R4, so waste all
1934   // remained registers.
1935   const unsigned NSAAOffset = State->getNextStackOffset();
1936   if (NSAAOffset != 0 && Size > Excess) {
1937     while (State->AllocateReg(GPRArgRegs))
1938       ;
1939     return;
1940   }
1941
1942   // First register for byval parameter is the first register that wasn't
1943   // allocated before this method call, so it would be "reg".
1944   // If parameter is small enough to be saved in range [reg, r4), then
1945   // the end (first after last) register would be reg + param-size-in-regs,
1946   // else parameter would be splitted between registers and stack,
1947   // end register would be r4 in this case.
1948   unsigned ByValRegBegin = Reg;
1949   unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
1950   State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1951   // Note, first register is allocated in the beginning of function already,
1952   // allocate remained amount of registers we need.
1953   for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
1954     State->AllocateReg(GPRArgRegs);
1955   // A byval parameter that is split between registers and memory needs its
1956   // size truncated here.
1957   // In the case where the entire structure fits in registers, we set the
1958   // size in memory to zero.
1959   Size = std::max<int>(Size - Excess, 0);
1960 }
1961
1962 /// MatchingStackOffset - Return true if the given stack call argument is
1963 /// already available in the same position (relatively) of the caller's
1964 /// incoming argument stack.
1965 static
1966 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1967                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1968                          const TargetInstrInfo *TII) {
1969   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1970   int FI = INT_MAX;
1971   if (Arg.getOpcode() == ISD::CopyFromReg) {
1972     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1973     if (!TargetRegisterInfo::isVirtualRegister(VR))
1974       return false;
1975     MachineInstr *Def = MRI->getVRegDef(VR);
1976     if (!Def)
1977       return false;
1978     if (!Flags.isByVal()) {
1979       if (!TII->isLoadFromStackSlot(Def, FI))
1980         return false;
1981     } else {
1982       return false;
1983     }
1984   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1985     if (Flags.isByVal())
1986       // ByVal argument is passed in as a pointer but it's now being
1987       // dereferenced. e.g.
1988       // define @foo(%struct.X* %A) {
1989       //   tail call @bar(%struct.X* byval %A)
1990       // }
1991       return false;
1992     SDValue Ptr = Ld->getBasePtr();
1993     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1994     if (!FINode)
1995       return false;
1996     FI = FINode->getIndex();
1997   } else
1998     return false;
1999
2000   assert(FI != INT_MAX);
2001   if (!MFI->isFixedObjectIndex(FI))
2002     return false;
2003   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2004 }
2005
2006 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2007 /// for tail call optimization. Targets which want to do tail call
2008 /// optimization should implement this function.
2009 bool
2010 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2011                                                      CallingConv::ID CalleeCC,
2012                                                      bool isVarArg,
2013                                                      bool isCalleeStructRet,
2014                                                      bool isCallerStructRet,
2015                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2016                                     const SmallVectorImpl<SDValue> &OutVals,
2017                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2018                                                      SelectionDAG& DAG) const {
2019   const Function *CallerF = DAG.getMachineFunction().getFunction();
2020   CallingConv::ID CallerCC = CallerF->getCallingConv();
2021   bool CCMatch = CallerCC == CalleeCC;
2022
2023   // Look for obvious safe cases to perform tail call optimization that do not
2024   // require ABI changes. This is what gcc calls sibcall.
2025
2026   // Do not sibcall optimize vararg calls unless the call site is not passing
2027   // any arguments.
2028   if (isVarArg && !Outs.empty())
2029     return false;
2030
2031   // Exception-handling functions need a special set of instructions to indicate
2032   // a return to the hardware. Tail-calling another function would probably
2033   // break this.
2034   if (CallerF->hasFnAttribute("interrupt"))
2035     return false;
2036
2037   // Also avoid sibcall optimization if either caller or callee uses struct
2038   // return semantics.
2039   if (isCalleeStructRet || isCallerStructRet)
2040     return false;
2041
2042   // FIXME: Completely disable sibcall for Thumb1 since ThumbRegisterInfo::
2043   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
2044   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
2045   // support in the assembler and linker to be used. This would need to be
2046   // fixed to fully support tail calls in Thumb1.
2047   //
2048   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
2049   // LR.  This means if we need to reload LR, it takes an extra instructions,
2050   // which outweighs the value of the tail call; but here we don't know yet
2051   // whether LR is going to be used.  Probably the right approach is to
2052   // generate the tail call here and turn it back into CALL/RET in
2053   // emitEpilogue if LR is used.
2054
2055   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
2056   // but we need to make sure there are enough registers; the only valid
2057   // registers are the 4 used for parameters.  We don't currently do this
2058   // case.
2059   if (Subtarget->isThumb1Only())
2060     return false;
2061
2062   // Externally-defined functions with weak linkage should not be
2063   // tail-called on ARM when the OS does not support dynamic
2064   // pre-emption of symbols, as the AAELF spec requires normal calls
2065   // to undefined weak functions to be replaced with a NOP or jump to the
2066   // next instruction. The behaviour of branch instructions in this
2067   // situation (as used for tail calls) is implementation-defined, so we
2068   // cannot rely on the linker replacing the tail call with a return.
2069   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2070     const GlobalValue *GV = G->getGlobal();
2071     const Triple &TT = getTargetMachine().getTargetTriple();
2072     if (GV->hasExternalWeakLinkage() &&
2073         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2074       return false;
2075   }
2076
2077   // If the calling conventions do not match, then we'd better make sure the
2078   // results are returned in the same way as what the caller expects.
2079   if (!CCMatch) {
2080     SmallVector<CCValAssign, 16> RVLocs1;
2081     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2082                        *DAG.getContext(), Call);
2083     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2084
2085     SmallVector<CCValAssign, 16> RVLocs2;
2086     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2087                        *DAG.getContext(), Call);
2088     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2089
2090     if (RVLocs1.size() != RVLocs2.size())
2091       return false;
2092     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2093       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2094         return false;
2095       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2096         return false;
2097       if (RVLocs1[i].isRegLoc()) {
2098         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2099           return false;
2100       } else {
2101         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2102           return false;
2103       }
2104     }
2105   }
2106
2107   // If Caller's vararg or byval argument has been split between registers and
2108   // stack, do not perform tail call, since part of the argument is in caller's
2109   // local frame.
2110   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2111                                       getInfo<ARMFunctionInfo>();
2112   if (AFI_Caller->getArgRegsSaveSize())
2113     return false;
2114
2115   // If the callee takes no arguments then go on to check the results of the
2116   // call.
2117   if (!Outs.empty()) {
2118     // Check if stack adjustment is needed. For now, do not do this if any
2119     // argument is passed on the stack.
2120     SmallVector<CCValAssign, 16> ArgLocs;
2121     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2122                       *DAG.getContext(), Call);
2123     CCInfo.AnalyzeCallOperands(Outs,
2124                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2125     if (CCInfo.getNextStackOffset()) {
2126       MachineFunction &MF = DAG.getMachineFunction();
2127
2128       // Check if the arguments are already laid out in the right way as
2129       // the caller's fixed stack objects.
2130       MachineFrameInfo *MFI = MF.getFrameInfo();
2131       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2132       const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2133       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2134            i != e;
2135            ++i, ++realArgIdx) {
2136         CCValAssign &VA = ArgLocs[i];
2137         EVT RegVT = VA.getLocVT();
2138         SDValue Arg = OutVals[realArgIdx];
2139         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2140         if (VA.getLocInfo() == CCValAssign::Indirect)
2141           return false;
2142         if (VA.needsCustom()) {
2143           // f64 and vector types are split into multiple registers or
2144           // register/stack-slot combinations.  The types will not match
2145           // the registers; give up on memory f64 refs until we figure
2146           // out what to do about this.
2147           if (!VA.isRegLoc())
2148             return false;
2149           if (!ArgLocs[++i].isRegLoc())
2150             return false;
2151           if (RegVT == MVT::v2f64) {
2152             if (!ArgLocs[++i].isRegLoc())
2153               return false;
2154             if (!ArgLocs[++i].isRegLoc())
2155               return false;
2156           }
2157         } else if (!VA.isRegLoc()) {
2158           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2159                                    MFI, MRI, TII))
2160             return false;
2161         }
2162       }
2163     }
2164   }
2165
2166   return true;
2167 }
2168
2169 bool
2170 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2171                                   MachineFunction &MF, bool isVarArg,
2172                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2173                                   LLVMContext &Context) const {
2174   SmallVector<CCValAssign, 16> RVLocs;
2175   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2176   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2177                                                     isVarArg));
2178 }
2179
2180 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2181                                     SDLoc DL, SelectionDAG &DAG) {
2182   const MachineFunction &MF = DAG.getMachineFunction();
2183   const Function *F = MF.getFunction();
2184
2185   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2186
2187   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2188   // version of the "preferred return address". These offsets affect the return
2189   // instruction if this is a return from PL1 without hypervisor extensions.
2190   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2191   //    SWI:     0      "subs pc, lr, #0"
2192   //    ABORT:   +4     "subs pc, lr, #4"
2193   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2194   // UNDEF varies depending on where the exception came from ARM or Thumb
2195   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2196
2197   int64_t LROffset;
2198   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2199       IntKind == "ABORT")
2200     LROffset = 4;
2201   else if (IntKind == "SWI" || IntKind == "UNDEF")
2202     LROffset = 0;
2203   else
2204     report_fatal_error("Unsupported interrupt attribute. If present, value "
2205                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2206
2207   RetOps.insert(RetOps.begin() + 1,
2208                 DAG.getConstant(LROffset, DL, MVT::i32, false));
2209
2210   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2211 }
2212
2213 SDValue
2214 ARMTargetLowering::LowerReturn(SDValue Chain,
2215                                CallingConv::ID CallConv, bool isVarArg,
2216                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2217                                const SmallVectorImpl<SDValue> &OutVals,
2218                                SDLoc dl, SelectionDAG &DAG) const {
2219
2220   // CCValAssign - represent the assignment of the return value to a location.
2221   SmallVector<CCValAssign, 16> RVLocs;
2222
2223   // CCState - Info about the registers and stack slots.
2224   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2225                     *DAG.getContext(), Call);
2226
2227   // Analyze outgoing return values.
2228   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2229                                                isVarArg));
2230
2231   SDValue Flag;
2232   SmallVector<SDValue, 4> RetOps;
2233   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2234   bool isLittleEndian = Subtarget->isLittle();
2235
2236   MachineFunction &MF = DAG.getMachineFunction();
2237   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2238   AFI->setReturnRegsCount(RVLocs.size());
2239
2240   // Copy the result values into the output registers.
2241   for (unsigned i = 0, realRVLocIdx = 0;
2242        i != RVLocs.size();
2243        ++i, ++realRVLocIdx) {
2244     CCValAssign &VA = RVLocs[i];
2245     assert(VA.isRegLoc() && "Can only return in registers!");
2246
2247     SDValue Arg = OutVals[realRVLocIdx];
2248
2249     switch (VA.getLocInfo()) {
2250     default: llvm_unreachable("Unknown loc info!");
2251     case CCValAssign::Full: break;
2252     case CCValAssign::BCvt:
2253       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2254       break;
2255     }
2256
2257     if (VA.needsCustom()) {
2258       if (VA.getLocVT() == MVT::v2f64) {
2259         // Extract the first half and return it in two registers.
2260         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2261                                    DAG.getConstant(0, dl, MVT::i32));
2262         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2263                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2264
2265         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2266                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2267                                  Flag);
2268         Flag = Chain.getValue(1);
2269         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2270         VA = RVLocs[++i]; // skip ahead to next loc
2271         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2272                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2273                                  Flag);
2274         Flag = Chain.getValue(1);
2275         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2276         VA = RVLocs[++i]; // skip ahead to next loc
2277
2278         // Extract the 2nd half and fall through to handle it as an f64 value.
2279         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2280                           DAG.getConstant(1, dl, MVT::i32));
2281       }
2282       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2283       // available.
2284       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2285                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2286       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2287                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2288                                Flag);
2289       Flag = Chain.getValue(1);
2290       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2291       VA = RVLocs[++i]; // skip ahead to next loc
2292       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2293                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2294                                Flag);
2295     } else
2296       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2297
2298     // Guarantee that all emitted copies are
2299     // stuck together, avoiding something bad.
2300     Flag = Chain.getValue(1);
2301     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2302   }
2303
2304   // Update chain and glue.
2305   RetOps[0] = Chain;
2306   if (Flag.getNode())
2307     RetOps.push_back(Flag);
2308
2309   // CPUs which aren't M-class use a special sequence to return from
2310   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2311   // though we use "subs pc, lr, #N").
2312   //
2313   // M-class CPUs actually use a normal return sequence with a special
2314   // (hardware-provided) value in LR, so the normal code path works.
2315   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2316       !Subtarget->isMClass()) {
2317     if (Subtarget->isThumb1Only())
2318       report_fatal_error("interrupt attribute is not supported in Thumb1");
2319     return LowerInterruptReturn(RetOps, dl, DAG);
2320   }
2321
2322   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2323 }
2324
2325 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2326   if (N->getNumValues() != 1)
2327     return false;
2328   if (!N->hasNUsesOfValue(1, 0))
2329     return false;
2330
2331   SDValue TCChain = Chain;
2332   SDNode *Copy = *N->use_begin();
2333   if (Copy->getOpcode() == ISD::CopyToReg) {
2334     // If the copy has a glue operand, we conservatively assume it isn't safe to
2335     // perform a tail call.
2336     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2337       return false;
2338     TCChain = Copy->getOperand(0);
2339   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2340     SDNode *VMov = Copy;
2341     // f64 returned in a pair of GPRs.
2342     SmallPtrSet<SDNode*, 2> Copies;
2343     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2344          UI != UE; ++UI) {
2345       if (UI->getOpcode() != ISD::CopyToReg)
2346         return false;
2347       Copies.insert(*UI);
2348     }
2349     if (Copies.size() > 2)
2350       return false;
2351
2352     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2353          UI != UE; ++UI) {
2354       SDValue UseChain = UI->getOperand(0);
2355       if (Copies.count(UseChain.getNode()))
2356         // Second CopyToReg
2357         Copy = *UI;
2358       else {
2359         // We are at the top of this chain.
2360         // If the copy has a glue operand, we conservatively assume it
2361         // isn't safe to perform a tail call.
2362         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2363           return false;
2364         // First CopyToReg
2365         TCChain = UseChain;
2366       }
2367     }
2368   } else if (Copy->getOpcode() == ISD::BITCAST) {
2369     // f32 returned in a single GPR.
2370     if (!Copy->hasOneUse())
2371       return false;
2372     Copy = *Copy->use_begin();
2373     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2374       return false;
2375     // If the copy has a glue operand, we conservatively assume it isn't safe to
2376     // perform a tail call.
2377     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2378       return false;
2379     TCChain = Copy->getOperand(0);
2380   } else {
2381     return false;
2382   }
2383
2384   bool HasRet = false;
2385   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2386        UI != UE; ++UI) {
2387     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2388         UI->getOpcode() != ARMISD::INTRET_FLAG)
2389       return false;
2390     HasRet = true;
2391   }
2392
2393   if (!HasRet)
2394     return false;
2395
2396   Chain = TCChain;
2397   return true;
2398 }
2399
2400 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2401   if (!Subtarget->supportsTailCall())
2402     return false;
2403
2404   auto Attr =
2405       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2406   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2407     return false;
2408
2409   return !Subtarget->isThumb1Only();
2410 }
2411
2412 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2413 // and pass the lower and high parts through.
2414 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2415   SDLoc DL(Op);
2416   SDValue WriteValue = Op->getOperand(2);
2417
2418   // This function is only supposed to be called for i64 type argument.
2419   assert(WriteValue.getValueType() == MVT::i64
2420           && "LowerWRITE_REGISTER called for non-i64 type argument.");
2421
2422   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2423                            DAG.getConstant(0, DL, MVT::i32));
2424   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2425                            DAG.getConstant(1, DL, MVT::i32));
2426   SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2427   return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2428 }
2429
2430 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2431 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2432 // one of the above mentioned nodes. It has to be wrapped because otherwise
2433 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2434 // be used to form addressing mode. These wrapped nodes will be selected
2435 // into MOVi.
2436 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2437   EVT PtrVT = Op.getValueType();
2438   // FIXME there is no actual debug info here
2439   SDLoc dl(Op);
2440   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2441   SDValue Res;
2442   if (CP->isMachineConstantPoolEntry())
2443     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2444                                     CP->getAlignment());
2445   else
2446     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2447                                     CP->getAlignment());
2448   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2449 }
2450
2451 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2452   return MachineJumpTableInfo::EK_Inline;
2453 }
2454
2455 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2456                                              SelectionDAG &DAG) const {
2457   MachineFunction &MF = DAG.getMachineFunction();
2458   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2459   unsigned ARMPCLabelIndex = 0;
2460   SDLoc DL(Op);
2461   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2462   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2463   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2464   SDValue CPAddr;
2465   if (RelocM == Reloc::Static) {
2466     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2467   } else {
2468     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2469     ARMPCLabelIndex = AFI->createPICLabelUId();
2470     ARMConstantPoolValue *CPV =
2471       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2472                                       ARMCP::CPBlockAddress, PCAdj);
2473     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2474   }
2475   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2476   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2477                                MachinePointerInfo::getConstantPool(),
2478                                false, false, false, 0);
2479   if (RelocM == Reloc::Static)
2480     return Result;
2481   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2482   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2483 }
2484
2485 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2486 SDValue
2487 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2488                                                  SelectionDAG &DAG) const {
2489   SDLoc dl(GA);
2490   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2491   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2492   MachineFunction &MF = DAG.getMachineFunction();
2493   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2494   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2495   ARMConstantPoolValue *CPV =
2496     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2497                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2498   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2499   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2500   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2501                          MachinePointerInfo::getConstantPool(),
2502                          false, false, false, 0);
2503   SDValue Chain = Argument.getValue(1);
2504
2505   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2506   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2507
2508   // call __tls_get_addr.
2509   ArgListTy Args;
2510   ArgListEntry Entry;
2511   Entry.Node = Argument;
2512   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2513   Args.push_back(Entry);
2514
2515   // FIXME: is there useful debug info available here?
2516   TargetLowering::CallLoweringInfo CLI(DAG);
2517   CLI.setDebugLoc(dl).setChain(Chain)
2518     .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2519                DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2520                0);
2521
2522   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2523   return CallResult.first;
2524 }
2525
2526 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2527 // "local exec" model.
2528 SDValue
2529 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2530                                         SelectionDAG &DAG,
2531                                         TLSModel::Model model) const {
2532   const GlobalValue *GV = GA->getGlobal();
2533   SDLoc dl(GA);
2534   SDValue Offset;
2535   SDValue Chain = DAG.getEntryNode();
2536   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2537   // Get the Thread Pointer
2538   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2539
2540   if (model == TLSModel::InitialExec) {
2541     MachineFunction &MF = DAG.getMachineFunction();
2542     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2543     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2544     // Initial exec model.
2545     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2546     ARMConstantPoolValue *CPV =
2547       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2548                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2549                                       true);
2550     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2551     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2552     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2553                          MachinePointerInfo::getConstantPool(),
2554                          false, false, false, 0);
2555     Chain = Offset.getValue(1);
2556
2557     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2558     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2559
2560     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2561                          MachinePointerInfo::getConstantPool(),
2562                          false, false, false, 0);
2563   } else {
2564     // local exec model
2565     assert(model == TLSModel::LocalExec);
2566     ARMConstantPoolValue *CPV =
2567       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2568     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2569     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2570     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2571                          MachinePointerInfo::getConstantPool(),
2572                          false, false, false, 0);
2573   }
2574
2575   // The address of the thread local variable is the add of the thread
2576   // pointer with the offset of the variable.
2577   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2578 }
2579
2580 SDValue
2581 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2582   // TODO: implement the "local dynamic" model
2583   assert(Subtarget->isTargetELF() &&
2584          "TLS not implemented for non-ELF targets");
2585   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2586
2587   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2588
2589   switch (model) {
2590     case TLSModel::GeneralDynamic:
2591     case TLSModel::LocalDynamic:
2592       return LowerToTLSGeneralDynamicModel(GA, DAG);
2593     case TLSModel::InitialExec:
2594     case TLSModel::LocalExec:
2595       return LowerToTLSExecModels(GA, DAG, model);
2596   }
2597   llvm_unreachable("bogus TLS model");
2598 }
2599
2600 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2601                                                  SelectionDAG &DAG) const {
2602   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2603   SDLoc dl(Op);
2604   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2605   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2606     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2607     ARMConstantPoolValue *CPV =
2608       ARMConstantPoolConstant::Create(GV,
2609                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2610     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2611     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2612     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2613                                  CPAddr,
2614                                  MachinePointerInfo::getConstantPool(),
2615                                  false, false, false, 0);
2616     SDValue Chain = Result.getValue(1);
2617     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2618     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2619     if (!UseGOTOFF)
2620       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2621                            MachinePointerInfo::getGOT(),
2622                            false, false, false, 0);
2623     return Result;
2624   }
2625
2626   // If we have T2 ops, we can materialize the address directly via movt/movw
2627   // pair. This is always cheaper.
2628   if (Subtarget->useMovt(DAG.getMachineFunction())) {
2629     ++NumMovwMovt;
2630     // FIXME: Once remat is capable of dealing with instructions with register
2631     // operands, expand this into two nodes.
2632     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2633                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2634   } else {
2635     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2636     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2637     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2638                        MachinePointerInfo::getConstantPool(),
2639                        false, false, false, 0);
2640   }
2641 }
2642
2643 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2644                                                     SelectionDAG &DAG) const {
2645   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2646   SDLoc dl(Op);
2647   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2648   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2649
2650   if (Subtarget->useMovt(DAG.getMachineFunction()))
2651     ++NumMovwMovt;
2652
2653   // FIXME: Once remat is capable of dealing with instructions with register
2654   // operands, expand this into multiple nodes
2655   unsigned Wrapper =
2656       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2657
2658   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2659   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2660
2661   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2662     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2663                          MachinePointerInfo::getGOT(), false, false, false, 0);
2664   return Result;
2665 }
2666
2667 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2668                                                      SelectionDAG &DAG) const {
2669   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2670   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2671          "Windows on ARM expects to use movw/movt");
2672
2673   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2674   const ARMII::TOF TargetFlags =
2675     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2676   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2677   SDValue Result;
2678   SDLoc DL(Op);
2679
2680   ++NumMovwMovt;
2681
2682   // FIXME: Once remat is capable of dealing with instructions with register
2683   // operands, expand this into two nodes.
2684   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2685                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2686                                                   TargetFlags));
2687   if (GV->hasDLLImportStorageClass())
2688     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2689                          MachinePointerInfo::getGOT(), false, false, false, 0);
2690   return Result;
2691 }
2692
2693 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2694                                                     SelectionDAG &DAG) const {
2695   assert(Subtarget->isTargetELF() &&
2696          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2697   MachineFunction &MF = DAG.getMachineFunction();
2698   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2699   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2700   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2701   SDLoc dl(Op);
2702   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2703   ARMConstantPoolValue *CPV =
2704     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2705                                   ARMPCLabelIndex, PCAdj);
2706   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2707   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2708   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2709                                MachinePointerInfo::getConstantPool(),
2710                                false, false, false, 0);
2711   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2712   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2713 }
2714
2715 SDValue
2716 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2717   SDLoc dl(Op);
2718   SDValue Val = DAG.getConstant(0, dl, MVT::i32);
2719   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2720                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2721                      Op.getOperand(1), Val);
2722 }
2723
2724 SDValue
2725 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2726   SDLoc dl(Op);
2727   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2728                      Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
2729 }
2730
2731 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
2732                                                       SelectionDAG &DAG) const {
2733   SDLoc dl(Op);
2734   return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
2735                      Op.getOperand(0));
2736 }
2737
2738 SDValue
2739 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2740                                           const ARMSubtarget *Subtarget) const {
2741   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2742   SDLoc dl(Op);
2743   switch (IntNo) {
2744   default: return SDValue();    // Don't custom lower most intrinsics.
2745   case Intrinsic::arm_rbit: {
2746     assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2747            "RBIT intrinsic must have i32 type!");
2748     return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1));
2749   }
2750   case Intrinsic::arm_thread_pointer: {
2751     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2752     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2753   }
2754   case Intrinsic::eh_sjlj_lsda: {
2755     MachineFunction &MF = DAG.getMachineFunction();
2756     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2757     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2758     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2759     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2760     SDValue CPAddr;
2761     unsigned PCAdj = (RelocM != Reloc::PIC_)
2762       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2763     ARMConstantPoolValue *CPV =
2764       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2765                                       ARMCP::CPLSDA, PCAdj);
2766     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2767     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2768     SDValue Result =
2769       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2770                   MachinePointerInfo::getConstantPool(),
2771                   false, false, false, 0);
2772
2773     if (RelocM == Reloc::PIC_) {
2774       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2775       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2776     }
2777     return Result;
2778   }
2779   case Intrinsic::arm_neon_vmulls:
2780   case Intrinsic::arm_neon_vmullu: {
2781     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2782       ? ARMISD::VMULLs : ARMISD::VMULLu;
2783     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2784                        Op.getOperand(1), Op.getOperand(2));
2785   }
2786   }
2787 }
2788
2789 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2790                                  const ARMSubtarget *Subtarget) {
2791   // FIXME: handle "fence singlethread" more efficiently.
2792   SDLoc dl(Op);
2793   if (!Subtarget->hasDataBarrier()) {
2794     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2795     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2796     // here.
2797     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2798            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2799     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2800                        DAG.getConstant(0, dl, MVT::i32));
2801   }
2802
2803   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2804   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2805   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
2806   if (Subtarget->isMClass()) {
2807     // Only a full system barrier exists in the M-class architectures.
2808     Domain = ARM_MB::SY;
2809   } else if (Subtarget->isSwift() && Ord == Release) {
2810     // Swift happens to implement ISHST barriers in a way that's compatible with
2811     // Release semantics but weaker than ISH so we'd be fools not to use
2812     // it. Beware: other processors probably don't!
2813     Domain = ARM_MB::ISHST;
2814   }
2815
2816   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2817                      DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
2818                      DAG.getConstant(Domain, dl, MVT::i32));
2819 }
2820
2821 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2822                              const ARMSubtarget *Subtarget) {
2823   // ARM pre v5TE and Thumb1 does not have preload instructions.
2824   if (!(Subtarget->isThumb2() ||
2825         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2826     // Just preserve the chain.
2827     return Op.getOperand(0);
2828
2829   SDLoc dl(Op);
2830   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2831   if (!isRead &&
2832       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2833     // ARMv7 with MP extension has PLDW.
2834     return Op.getOperand(0);
2835
2836   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2837   if (Subtarget->isThumb()) {
2838     // Invert the bits.
2839     isRead = ~isRead & 1;
2840     isData = ~isData & 1;
2841   }
2842
2843   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2844                      Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
2845                      DAG.getConstant(isData, dl, MVT::i32));
2846 }
2847
2848 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2849   MachineFunction &MF = DAG.getMachineFunction();
2850   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2851
2852   // vastart just stores the address of the VarArgsFrameIndex slot into the
2853   // memory location argument.
2854   SDLoc dl(Op);
2855   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2856   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2857   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2858   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2859                       MachinePointerInfo(SV), false, false, 0);
2860 }
2861
2862 SDValue
2863 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2864                                         SDValue &Root, SelectionDAG &DAG,
2865                                         SDLoc dl) const {
2866   MachineFunction &MF = DAG.getMachineFunction();
2867   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2868
2869   const TargetRegisterClass *RC;
2870   if (AFI->isThumb1OnlyFunction())
2871     RC = &ARM::tGPRRegClass;
2872   else
2873     RC = &ARM::GPRRegClass;
2874
2875   // Transform the arguments stored in physical registers into virtual ones.
2876   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2877   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2878
2879   SDValue ArgValue2;
2880   if (NextVA.isMemLoc()) {
2881     MachineFrameInfo *MFI = MF.getFrameInfo();
2882     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2883
2884     // Create load node to retrieve arguments from the stack.
2885     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2886     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2887                             MachinePointerInfo::getFixedStack(FI),
2888                             false, false, false, 0);
2889   } else {
2890     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2891     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2892   }
2893   if (!Subtarget->isLittle())
2894     std::swap (ArgValue, ArgValue2);
2895   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2896 }
2897
2898 // The remaining GPRs hold either the beginning of variable-argument
2899 // data, or the beginning of an aggregate passed by value (usually
2900 // byval).  Either way, we allocate stack slots adjacent to the data
2901 // provided by our caller, and store the unallocated registers there.
2902 // If this is a variadic function, the va_list pointer will begin with
2903 // these values; otherwise, this reassembles a (byval) structure that
2904 // was split between registers and memory.
2905 // Return: The frame index registers were stored into.
2906 int
2907 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2908                                   SDLoc dl, SDValue &Chain,
2909                                   const Value *OrigArg,
2910                                   unsigned InRegsParamRecordIdx,
2911                                   int ArgOffset,
2912                                   unsigned ArgSize) const {
2913   // Currently, two use-cases possible:
2914   // Case #1. Non-var-args function, and we meet first byval parameter.
2915   //          Setup first unallocated register as first byval register;
2916   //          eat all remained registers
2917   //          (these two actions are performed by HandleByVal method).
2918   //          Then, here, we initialize stack frame with
2919   //          "store-reg" instructions.
2920   // Case #2. Var-args function, that doesn't contain byval parameters.
2921   //          The same: eat all remained unallocated registers,
2922   //          initialize stack frame.
2923
2924   MachineFunction &MF = DAG.getMachineFunction();
2925   MachineFrameInfo *MFI = MF.getFrameInfo();
2926   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2927   unsigned RBegin, REnd;
2928   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2929     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2930   } else {
2931     unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
2932     RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
2933     REnd = ARM::R4;
2934   }
2935
2936   if (REnd != RBegin)
2937     ArgOffset = -4 * (ARM::R4 - RBegin);
2938
2939   auto PtrVT = getPointerTy(DAG.getDataLayout());
2940   int FrameIndex = MFI->CreateFixedObject(ArgSize, ArgOffset, false);
2941   SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
2942
2943   SmallVector<SDValue, 4> MemOps;
2944   const TargetRegisterClass *RC =
2945       AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
2946
2947   for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
2948     unsigned VReg = MF.addLiveIn(Reg, RC);
2949     SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2950     SDValue Store =
2951         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2952                      MachinePointerInfo(OrigArg, 4 * i), false, false, 0);
2953     MemOps.push_back(Store);
2954     FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
2955   }
2956
2957   if (!MemOps.empty())
2958     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2959   return FrameIndex;
2960 }
2961
2962 // Setup stack frame, the va_list pointer will start from.
2963 void
2964 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2965                                         SDLoc dl, SDValue &Chain,
2966                                         unsigned ArgOffset,
2967                                         unsigned TotalArgRegsSaveSize,
2968                                         bool ForceMutable) const {
2969   MachineFunction &MF = DAG.getMachineFunction();
2970   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2971
2972   // Try to store any remaining integer argument regs
2973   // to their spots on the stack so that they may be loaded by deferencing
2974   // the result of va_next.
2975   // If there is no regs to be stored, just point address after last
2976   // argument passed via stack.
2977   int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
2978                                   CCInfo.getInRegsParamsCount(),
2979                                   CCInfo.getNextStackOffset(), 4);
2980   AFI->setVarArgsFrameIndex(FrameIndex);
2981 }
2982
2983 SDValue
2984 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2985                                         CallingConv::ID CallConv, bool isVarArg,
2986                                         const SmallVectorImpl<ISD::InputArg>
2987                                           &Ins,
2988                                         SDLoc dl, SelectionDAG &DAG,
2989                                         SmallVectorImpl<SDValue> &InVals)
2990                                           const {
2991   MachineFunction &MF = DAG.getMachineFunction();
2992   MachineFrameInfo *MFI = MF.getFrameInfo();
2993
2994   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2995
2996   // Assign locations to all of the incoming arguments.
2997   SmallVector<CCValAssign, 16> ArgLocs;
2998   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2999                     *DAG.getContext(), Prologue);
3000   CCInfo.AnalyzeFormalArguments(Ins,
3001                                 CCAssignFnForNode(CallConv, /* Return*/ false,
3002                                                   isVarArg));
3003
3004   SmallVector<SDValue, 16> ArgValues;
3005   SDValue ArgValue;
3006   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3007   unsigned CurArgIdx = 0;
3008
3009   // Initially ArgRegsSaveSize is zero.
3010   // Then we increase this value each time we meet byval parameter.
3011   // We also increase this value in case of varargs function.
3012   AFI->setArgRegsSaveSize(0);
3013
3014   // Calculate the amount of stack space that we need to allocate to store
3015   // byval and variadic arguments that are passed in registers.
3016   // We need to know this before we allocate the first byval or variadic
3017   // argument, as they will be allocated a stack slot below the CFA (Canonical
3018   // Frame Address, the stack pointer at entry to the function).
3019   unsigned ArgRegBegin = ARM::R4;
3020   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3021     if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3022       break;
3023
3024     CCValAssign &VA = ArgLocs[i];
3025     unsigned Index = VA.getValNo();
3026     ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3027     if (!Flags.isByVal())
3028       continue;
3029
3030     assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3031     unsigned RBegin, REnd;
3032     CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3033     ArgRegBegin = std::min(ArgRegBegin, RBegin);
3034
3035     CCInfo.nextInRegsParam();
3036   }
3037   CCInfo.rewindByValRegsInfo();
3038
3039   int lastInsIndex = -1;
3040   if (isVarArg && MFI->hasVAStart()) {
3041     unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3042     if (RegIdx != array_lengthof(GPRArgRegs))
3043       ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3044   }
3045
3046   unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3047   AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3048   auto PtrVT = getPointerTy(DAG.getDataLayout());
3049
3050   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3051     CCValAssign &VA = ArgLocs[i];
3052     if (Ins[VA.getValNo()].isOrigArg()) {
3053       std::advance(CurOrigArg,
3054                    Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3055       CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3056     }
3057     // Arguments stored in registers.
3058     if (VA.isRegLoc()) {
3059       EVT RegVT = VA.getLocVT();
3060
3061       if (VA.needsCustom()) {
3062         // f64 and vector types are split up into multiple registers or
3063         // combinations of registers and stack slots.
3064         if (VA.getLocVT() == MVT::v2f64) {
3065           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3066                                                    Chain, DAG, dl);
3067           VA = ArgLocs[++i]; // skip ahead to next loc
3068           SDValue ArgValue2;
3069           if (VA.isMemLoc()) {
3070             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3071             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3072             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3073                                     MachinePointerInfo::getFixedStack(FI),
3074                                     false, false, false, 0);
3075           } else {
3076             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3077                                              Chain, DAG, dl);
3078           }
3079           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3080           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3081                                  ArgValue, ArgValue1,
3082                                  DAG.getIntPtrConstant(0, dl));
3083           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3084                                  ArgValue, ArgValue2,
3085                                  DAG.getIntPtrConstant(1, dl));
3086         } else
3087           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3088
3089       } else {
3090         const TargetRegisterClass *RC;
3091
3092         if (RegVT == MVT::f32)
3093           RC = &ARM::SPRRegClass;
3094         else if (RegVT == MVT::f64)
3095           RC = &ARM::DPRRegClass;
3096         else if (RegVT == MVT::v2f64)
3097           RC = &ARM::QPRRegClass;
3098         else if (RegVT == MVT::i32)
3099           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3100                                            : &ARM::GPRRegClass;
3101         else
3102           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3103
3104         // Transform the arguments in physical registers into virtual ones.
3105         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3106         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3107       }
3108
3109       // If this is an 8 or 16-bit value, it is really passed promoted
3110       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3111       // truncate to the right size.
3112       switch (VA.getLocInfo()) {
3113       default: llvm_unreachable("Unknown loc info!");
3114       case CCValAssign::Full: break;
3115       case CCValAssign::BCvt:
3116         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3117         break;
3118       case CCValAssign::SExt:
3119         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3120                                DAG.getValueType(VA.getValVT()));
3121         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3122         break;
3123       case CCValAssign::ZExt:
3124         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3125                                DAG.getValueType(VA.getValVT()));
3126         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3127         break;
3128       }
3129
3130       InVals.push_back(ArgValue);
3131
3132     } else { // VA.isRegLoc()
3133
3134       // sanity check
3135       assert(VA.isMemLoc());
3136       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3137
3138       int index = VA.getValNo();
3139
3140       // Some Ins[] entries become multiple ArgLoc[] entries.
3141       // Process them only once.
3142       if (index != lastInsIndex)
3143         {
3144           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3145           // FIXME: For now, all byval parameter objects are marked mutable.
3146           // This can be changed with more analysis.
3147           // In case of tail call optimization mark all arguments mutable.
3148           // Since they could be overwritten by lowering of arguments in case of
3149           // a tail call.
3150           if (Flags.isByVal()) {
3151             assert(Ins[index].isOrigArg() &&
3152                    "Byval arguments cannot be implicit");
3153             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3154
3155             int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, CurOrigArg,
3156                                             CurByValIndex, VA.getLocMemOffset(),
3157                                             Flags.getByValSize());
3158             InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
3159             CCInfo.nextInRegsParam();
3160           } else {
3161             unsigned FIOffset = VA.getLocMemOffset();
3162             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3163                                             FIOffset, true);
3164
3165             // Create load nodes to retrieve arguments from the stack.
3166             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3167             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3168                                          MachinePointerInfo::getFixedStack(FI),
3169                                          false, false, false, 0));
3170           }
3171           lastInsIndex = index;
3172         }
3173     }
3174   }
3175
3176   // varargs
3177   if (isVarArg && MFI->hasVAStart())
3178     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3179                          CCInfo.getNextStackOffset(),
3180                          TotalArgRegsSaveSize);
3181
3182   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3183
3184   return Chain;
3185 }
3186
3187 /// isFloatingPointZero - Return true if this is +0.0.
3188 static bool isFloatingPointZero(SDValue Op) {
3189   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3190     return CFP->getValueAPF().isPosZero();
3191   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3192     // Maybe this has already been legalized into the constant pool?
3193     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3194       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3195       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3196         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3197           return CFP->getValueAPF().isPosZero();
3198     }
3199   } else if (Op->getOpcode() == ISD::BITCAST &&
3200              Op->getValueType(0) == MVT::f64) {
3201     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3202     // created by LowerConstantFP().
3203     SDValue BitcastOp = Op->getOperand(0);
3204     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM) {
3205       SDValue MoveOp = BitcastOp->getOperand(0);
3206       if (MoveOp->getOpcode() == ISD::TargetConstant &&
3207           cast<ConstantSDNode>(MoveOp)->getZExtValue() == 0) {
3208         return true;
3209       }
3210     }
3211   }
3212   return false;
3213 }
3214
3215 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3216 /// the given operands.
3217 SDValue
3218 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3219                              SDValue &ARMcc, SelectionDAG &DAG,
3220                              SDLoc dl) const {
3221   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3222     unsigned C = RHSC->getZExtValue();
3223     if (!isLegalICmpImmediate(C)) {
3224       // Constant does not fit, try adjusting it by one?
3225       switch (CC) {
3226       default: break;
3227       case ISD::SETLT:
3228       case ISD::SETGE:
3229         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3230           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3231           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3232         }
3233         break;
3234       case ISD::SETULT:
3235       case ISD::SETUGE:
3236         if (C != 0 && isLegalICmpImmediate(C-1)) {
3237           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3238           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3239         }
3240         break;
3241       case ISD::SETLE:
3242       case ISD::SETGT:
3243         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3244           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3245           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3246         }
3247         break;
3248       case ISD::SETULE:
3249       case ISD::SETUGT:
3250         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3251           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3252           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3253         }
3254         break;
3255       }
3256     }
3257   }
3258
3259   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3260   ARMISD::NodeType CompareType;
3261   switch (CondCode) {
3262   default:
3263     CompareType = ARMISD::CMP;
3264     break;
3265   case ARMCC::EQ:
3266   case ARMCC::NE:
3267     // Uses only Z Flag
3268     CompareType = ARMISD::CMPZ;
3269     break;
3270   }
3271   ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3272   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3273 }
3274
3275 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3276 SDValue
3277 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3278                              SDLoc dl) const {
3279   assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3280   SDValue Cmp;
3281   if (!isFloatingPointZero(RHS))
3282     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3283   else
3284     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3285   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3286 }
3287
3288 /// duplicateCmp - Glue values can have only one use, so this function
3289 /// duplicates a comparison node.
3290 SDValue
3291 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3292   unsigned Opc = Cmp.getOpcode();
3293   SDLoc DL(Cmp);
3294   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3295     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3296
3297   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3298   Cmp = Cmp.getOperand(0);
3299   Opc = Cmp.getOpcode();
3300   if (Opc == ARMISD::CMPFP)
3301     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3302   else {
3303     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3304     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3305   }
3306   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3307 }
3308
3309 std::pair<SDValue, SDValue>
3310 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3311                                  SDValue &ARMcc) const {
3312   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3313
3314   SDValue Value, OverflowCmp;
3315   SDValue LHS = Op.getOperand(0);
3316   SDValue RHS = Op.getOperand(1);
3317   SDLoc dl(Op);
3318
3319   // FIXME: We are currently always generating CMPs because we don't support
3320   // generating CMN through the backend. This is not as good as the natural
3321   // CMP case because it causes a register dependency and cannot be folded
3322   // later.
3323
3324   switch (Op.getOpcode()) {
3325   default:
3326     llvm_unreachable("Unknown overflow instruction!");
3327   case ISD::SADDO:
3328     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3329     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3330     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3331     break;
3332   case ISD::UADDO:
3333     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3334     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3335     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3336     break;
3337   case ISD::SSUBO:
3338     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3339     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3340     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3341     break;
3342   case ISD::USUBO:
3343     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3344     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3345     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3346     break;
3347   } // switch (...)
3348
3349   return std::make_pair(Value, OverflowCmp);
3350 }
3351
3352
3353 SDValue
3354 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3355   // Let legalize expand this if it isn't a legal type yet.
3356   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3357     return SDValue();
3358
3359   SDValue Value, OverflowCmp;
3360   SDValue ARMcc;
3361   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3362   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3363   SDLoc dl(Op);
3364   // We use 0 and 1 as false and true values.
3365   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3366   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3367   EVT VT = Op.getValueType();
3368
3369   SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
3370                                  ARMcc, CCR, OverflowCmp);
3371
3372   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3373   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
3374 }
3375
3376
3377 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3378   SDValue Cond = Op.getOperand(0);
3379   SDValue SelectTrue = Op.getOperand(1);
3380   SDValue SelectFalse = Op.getOperand(2);
3381   SDLoc dl(Op);
3382   unsigned Opc = Cond.getOpcode();
3383
3384   if (Cond.getResNo() == 1 &&
3385       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3386        Opc == ISD::USUBO)) {
3387     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3388       return SDValue();
3389
3390     SDValue Value, OverflowCmp;
3391     SDValue ARMcc;
3392     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3393     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3394     EVT VT = Op.getValueType();
3395
3396     return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
3397                    OverflowCmp, DAG);
3398   }
3399
3400   // Convert:
3401   //
3402   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3403   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3404   //
3405   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3406     const ConstantSDNode *CMOVTrue =
3407       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3408     const ConstantSDNode *CMOVFalse =
3409       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3410
3411     if (CMOVTrue && CMOVFalse) {
3412       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3413       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3414
3415       SDValue True;
3416       SDValue False;
3417       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3418         True = SelectTrue;
3419         False = SelectFalse;
3420       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3421         True = SelectFalse;
3422         False = SelectTrue;
3423       }
3424
3425       if (True.getNode() && False.getNode()) {
3426         EVT VT = Op.getValueType();
3427         SDValue ARMcc = Cond.getOperand(2);
3428         SDValue CCR = Cond.getOperand(3);
3429         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3430         assert(True.getValueType() == VT);
3431         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3432       }
3433     }
3434   }
3435
3436   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3437   // undefined bits before doing a full-word comparison with zero.
3438   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3439                      DAG.getConstant(1, dl, Cond.getValueType()));
3440
3441   return DAG.getSelectCC(dl, Cond,
3442                          DAG.getConstant(0, dl, Cond.getValueType()),
3443                          SelectTrue, SelectFalse, ISD::SETNE);
3444 }
3445
3446 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3447                                  bool &swpCmpOps, bool &swpVselOps) {
3448   // Start by selecting the GE condition code for opcodes that return true for
3449   // 'equality'
3450   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3451       CC == ISD::SETULE)
3452     CondCode = ARMCC::GE;
3453
3454   // and GT for opcodes that return false for 'equality'.
3455   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3456            CC == ISD::SETULT)
3457     CondCode = ARMCC::GT;
3458
3459   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3460   // to swap the compare operands.
3461   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3462       CC == ISD::SETULT)
3463     swpCmpOps = true;
3464
3465   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3466   // If we have an unordered opcode, we need to swap the operands to the VSEL
3467   // instruction (effectively negating the condition).
3468   //
3469   // This also has the effect of swapping which one of 'less' or 'greater'
3470   // returns true, so we also swap the compare operands. It also switches
3471   // whether we return true for 'equality', so we compensate by picking the
3472   // opposite condition code to our original choice.
3473   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3474       CC == ISD::SETUGT) {
3475     swpCmpOps = !swpCmpOps;
3476     swpVselOps = !swpVselOps;
3477     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3478   }
3479
3480   // 'ordered' is 'anything but unordered', so use the VS condition code and
3481   // swap the VSEL operands.
3482   if (CC == ISD::SETO) {
3483     CondCode = ARMCC::VS;
3484     swpVselOps = true;
3485   }
3486
3487   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3488   // code and swap the VSEL operands.
3489   if (CC == ISD::SETUNE) {
3490     CondCode = ARMCC::EQ;
3491     swpVselOps = true;
3492   }
3493 }
3494
3495 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3496                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3497                                    SDValue Cmp, SelectionDAG &DAG) const {
3498   if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3499     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3500                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3501     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3502                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3503
3504     SDValue TrueLow = TrueVal.getValue(0);
3505     SDValue TrueHigh = TrueVal.getValue(1);
3506     SDValue FalseLow = FalseVal.getValue(0);
3507     SDValue FalseHigh = FalseVal.getValue(1);
3508
3509     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3510                               ARMcc, CCR, Cmp);
3511     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3512                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
3513
3514     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3515   } else {
3516     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3517                        Cmp);
3518   }
3519 }
3520
3521 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3522   EVT VT = Op.getValueType();
3523   SDValue LHS = Op.getOperand(0);
3524   SDValue RHS = Op.getOperand(1);
3525   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3526   SDValue TrueVal = Op.getOperand(2);
3527   SDValue FalseVal = Op.getOperand(3);
3528   SDLoc dl(Op);
3529
3530   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3531     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3532                                                     dl);
3533
3534     // If softenSetCCOperands only returned one value, we should compare it to
3535     // zero.
3536     if (!RHS.getNode()) {
3537       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3538       CC = ISD::SETNE;
3539     }
3540   }
3541
3542   if (LHS.getValueType() == MVT::i32) {
3543     // Try to generate VSEL on ARMv8.
3544     // The VSEL instruction can't use all the usual ARM condition
3545     // codes: it only has two bits to select the condition code, so it's
3546     // constrained to use only GE, GT, VS and EQ.
3547     //
3548     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3549     // swap the operands of the previous compare instruction (effectively
3550     // inverting the compare condition, swapping 'less' and 'greater') and
3551     // sometimes need to swap the operands to the VSEL (which inverts the
3552     // condition in the sense of firing whenever the previous condition didn't)
3553     if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3554                                     TrueVal.getValueType() == MVT::f64)) {
3555       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3556       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3557           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3558         CC = ISD::getSetCCInverse(CC, true);
3559         std::swap(TrueVal, FalseVal);
3560       }
3561     }
3562
3563     SDValue ARMcc;
3564     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3565     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3566     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3567   }
3568
3569   ARMCC::CondCodes CondCode, CondCode2;
3570   FPCCToARMCC(CC, CondCode, CondCode2);
3571
3572   // Try to generate VMAXNM/VMINNM on ARMv8.
3573   if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3574                                   TrueVal.getValueType() == MVT::f64)) {
3575     // We can use VMAXNM/VMINNM for a compare followed by a select with the
3576     // same operands, as follows:
3577     //   c = fcmp [?gt, ?ge, ?lt, ?le] a, b
3578     //   select c, a, b
3579     // In NoNaNsFPMath the CC will have been changed from, e.g., 'ogt' to 'gt'.
3580     bool swapSides = false;
3581     if (!getTargetMachine().Options.NoNaNsFPMath) {
3582       // transformability may depend on which way around we compare
3583       switch (CC) {
3584       default:
3585         break;
3586       case ISD::SETOGT:
3587       case ISD::SETOGE:
3588       case ISD::SETOLT:
3589       case ISD::SETOLE:
3590         // the non-NaN should be RHS
3591         swapSides = DAG.isKnownNeverNaN(LHS) && !DAG.isKnownNeverNaN(RHS);
3592         break;
3593       case ISD::SETUGT:
3594       case ISD::SETUGE:
3595       case ISD::SETULT:
3596       case ISD::SETULE:
3597         // the non-NaN should be LHS
3598         swapSides = DAG.isKnownNeverNaN(RHS) && !DAG.isKnownNeverNaN(LHS);
3599         break;
3600       }
3601     }
3602     swapSides = swapSides || (LHS == FalseVal && RHS == TrueVal);
3603     if (swapSides) {
3604       CC = ISD::getSetCCSwappedOperands(CC);
3605       std::swap(LHS, RHS);
3606     }
3607     if (LHS == TrueVal && RHS == FalseVal) {
3608       bool canTransform = true;
3609       // FIXME: FastMathFlags::noSignedZeros() doesn't appear reachable from here
3610       if (!getTargetMachine().Options.UnsafeFPMath &&
3611           !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
3612         const ConstantFPSDNode *Zero;
3613         switch (CC) {
3614         default:
3615           break;
3616         case ISD::SETOGT:
3617         case ISD::SETUGT:
3618         case ISD::SETGT:
3619           // RHS must not be -0
3620           canTransform = (Zero = dyn_cast<ConstantFPSDNode>(RHS)) &&
3621                          !Zero->isNegative();
3622           break;
3623         case ISD::SETOGE:
3624         case ISD::SETUGE:
3625         case ISD::SETGE:
3626           // LHS must not be -0
3627           canTransform = (Zero = dyn_cast<ConstantFPSDNode>(LHS)) &&
3628                          !Zero->isNegative();
3629           break;
3630         case ISD::SETOLT:
3631         case ISD::SETULT:
3632         case ISD::SETLT:
3633           // RHS must not be +0
3634           canTransform = (Zero = dyn_cast<ConstantFPSDNode>(RHS)) &&
3635                           Zero->isNegative();
3636           break;
3637         case ISD::SETOLE:
3638         case ISD::SETULE:
3639         case ISD::SETLE:
3640           // LHS must not be +0
3641           canTransform = (Zero = dyn_cast<ConstantFPSDNode>(LHS)) &&
3642                           Zero->isNegative();
3643           break;
3644         }
3645       }
3646       if (canTransform) {
3647         // Note: If one of the elements in a pair is a number and the other
3648         // element is NaN, the corresponding result element is the number.
3649         // This is consistent with the IEEE 754-2008 standard.
3650         // Therefore, a > b ? a : b <=> vmax(a,b), if b is constant and a is NaN
3651         switch (CC) {
3652         default:
3653           break;
3654         case ISD::SETOGT:
3655         case ISD::SETOGE:
3656           if (!DAG.isKnownNeverNaN(RHS))
3657             break;
3658           return DAG.getNode(ARMISD::VMAXNM, dl, VT, LHS, RHS);
3659         case ISD::SETUGT:
3660         case ISD::SETUGE:
3661           if (!DAG.isKnownNeverNaN(LHS))
3662             break;
3663         case ISD::SETGT:
3664         case ISD::SETGE:
3665           return DAG.getNode(ARMISD::VMAXNM, dl, VT, LHS, RHS);
3666         case ISD::SETOLT:
3667         case ISD::SETOLE:
3668           if (!DAG.isKnownNeverNaN(RHS))
3669             break;
3670           return DAG.getNode(ARMISD::VMINNM, dl, VT, LHS, RHS);
3671         case ISD::SETULT:
3672         case ISD::SETULE:
3673           if (!DAG.isKnownNeverNaN(LHS))
3674             break;
3675         case ISD::SETLT:
3676         case ISD::SETLE:
3677           return DAG.getNode(ARMISD::VMINNM, dl, VT, LHS, RHS);
3678         }
3679       }
3680     }
3681
3682     bool swpCmpOps = false;
3683     bool swpVselOps = false;
3684     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3685
3686     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3687         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3688       if (swpCmpOps)
3689         std::swap(LHS, RHS);
3690       if (swpVselOps)
3691         std::swap(TrueVal, FalseVal);
3692     }
3693   }
3694
3695   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3696   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3697   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3698   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3699   if (CondCode2 != ARMCC::AL) {
3700     SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
3701     // FIXME: Needs another CMP because flag can have but one use.
3702     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3703     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3704   }
3705   return Result;
3706 }
3707
3708 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3709 /// to morph to an integer compare sequence.
3710 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3711                            const ARMSubtarget *Subtarget) {
3712   SDNode *N = Op.getNode();
3713   if (!N->hasOneUse())
3714     // Otherwise it requires moving the value from fp to integer registers.
3715     return false;
3716   if (!N->getNumValues())
3717     return false;
3718   EVT VT = Op.getValueType();
3719   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3720     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3721     // vmrs are very slow, e.g. cortex-a8.
3722     return false;
3723
3724   if (isFloatingPointZero(Op)) {
3725     SeenZero = true;
3726     return true;
3727   }
3728   return ISD::isNormalLoad(N);
3729 }
3730
3731 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3732   if (isFloatingPointZero(Op))
3733     return DAG.getConstant(0, SDLoc(Op), MVT::i32);
3734
3735   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3736     return DAG.getLoad(MVT::i32, SDLoc(Op),
3737                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3738                        Ld->isVolatile(), Ld->isNonTemporal(),
3739                        Ld->isInvariant(), Ld->getAlignment());
3740
3741   llvm_unreachable("Unknown VFP cmp argument!");
3742 }
3743
3744 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3745                            SDValue &RetVal1, SDValue &RetVal2) {
3746   SDLoc dl(Op);
3747
3748   if (isFloatingPointZero(Op)) {
3749     RetVal1 = DAG.getConstant(0, dl, MVT::i32);
3750     RetVal2 = DAG.getConstant(0, dl, MVT::i32);
3751     return;
3752   }
3753
3754   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3755     SDValue Ptr = Ld->getBasePtr();
3756     RetVal1 = DAG.getLoad(MVT::i32, dl,
3757                           Ld->getChain(), Ptr,
3758                           Ld->getPointerInfo(),
3759                           Ld->isVolatile(), Ld->isNonTemporal(),
3760                           Ld->isInvariant(), Ld->getAlignment());
3761
3762     EVT PtrType = Ptr.getValueType();
3763     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3764     SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
3765                                  PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
3766     RetVal2 = DAG.getLoad(MVT::i32, dl,
3767                           Ld->getChain(), NewPtr,
3768                           Ld->getPointerInfo().getWithOffset(4),
3769                           Ld->isVolatile(), Ld->isNonTemporal(),
3770                           Ld->isInvariant(), NewAlign);
3771     return;
3772   }
3773
3774   llvm_unreachable("Unknown VFP cmp argument!");
3775 }
3776
3777 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3778 /// f32 and even f64 comparisons to integer ones.
3779 SDValue
3780 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3781   SDValue Chain = Op.getOperand(0);
3782   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3783   SDValue LHS = Op.getOperand(2);
3784   SDValue RHS = Op.getOperand(3);
3785   SDValue Dest = Op.getOperand(4);
3786   SDLoc dl(Op);
3787
3788   bool LHSSeenZero = false;
3789   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3790   bool RHSSeenZero = false;
3791   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3792   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3793     // If unsafe fp math optimization is enabled and there are no other uses of
3794     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3795     // to an integer comparison.
3796     if (CC == ISD::SETOEQ)
3797       CC = ISD::SETEQ;
3798     else if (CC == ISD::SETUNE)
3799       CC = ISD::SETNE;
3800
3801     SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
3802     SDValue ARMcc;
3803     if (LHS.getValueType() == MVT::f32) {
3804       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3805                         bitcastf32Toi32(LHS, DAG), Mask);
3806       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3807                         bitcastf32Toi32(RHS, DAG), Mask);
3808       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3809       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3810       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3811                          Chain, Dest, ARMcc, CCR, Cmp);
3812     }
3813
3814     SDValue LHS1, LHS2;
3815     SDValue RHS1, RHS2;
3816     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3817     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3818     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3819     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3820     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3821     ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3822     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3823     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3824     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3825   }
3826
3827   return SDValue();
3828 }
3829
3830 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3831   SDValue Chain = Op.getOperand(0);
3832   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3833   SDValue LHS = Op.getOperand(2);
3834   SDValue RHS = Op.getOperand(3);
3835   SDValue Dest = Op.getOperand(4);
3836   SDLoc dl(Op);
3837
3838   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3839     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3840                                                     dl);
3841
3842     // If softenSetCCOperands only returned one value, we should compare it to
3843     // zero.
3844     if (!RHS.getNode()) {
3845       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3846       CC = ISD::SETNE;
3847     }
3848   }
3849
3850   if (LHS.getValueType() == MVT::i32) {
3851     SDValue ARMcc;
3852     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3853     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3854     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3855                        Chain, Dest, ARMcc, CCR, Cmp);
3856   }
3857
3858   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3859
3860   if (getTargetMachine().Options.UnsafeFPMath &&
3861       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3862        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3863     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3864     if (Result.getNode())
3865       return Result;
3866   }
3867
3868   ARMCC::CondCodes CondCode, CondCode2;
3869   FPCCToARMCC(CC, CondCode, CondCode2);
3870
3871   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3872   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3873   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3874   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3875   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3876   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3877   if (CondCode2 != ARMCC::AL) {
3878     ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
3879     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3880     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3881   }
3882   return Res;
3883 }
3884
3885 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3886   SDValue Chain = Op.getOperand(0);
3887   SDValue Table = Op.getOperand(1);
3888   SDValue Index = Op.getOperand(2);
3889   SDLoc dl(Op);
3890
3891   EVT PTy = getPointerTy(DAG.getDataLayout());
3892   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3893   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3894   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
3895   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
3896   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3897   if (Subtarget->isThumb2()) {
3898     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3899     // which does another jump to the destination. This also makes it easier
3900     // to translate it to TBB / TBH later.
3901     // FIXME: This might not work if the function is extremely large.
3902     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3903                        Addr, Op.getOperand(2), JTI);
3904   }
3905   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3906     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3907                        MachinePointerInfo::getJumpTable(),
3908                        false, false, false, 0);
3909     Chain = Addr.getValue(1);
3910     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3911     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3912   } else {
3913     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3914                        MachinePointerInfo::getJumpTable(),
3915                        false, false, false, 0);
3916     Chain = Addr.getValue(1);
3917     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3918   }
3919 }
3920
3921 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3922   EVT VT = Op.getValueType();
3923   SDLoc dl(Op);
3924
3925   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3926     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3927       return Op;
3928     return DAG.UnrollVectorOp(Op.getNode());
3929   }
3930
3931   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3932          "Invalid type for custom lowering!");
3933   if (VT != MVT::v4i16)
3934     return DAG.UnrollVectorOp(Op.getNode());
3935
3936   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3937   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3938 }
3939
3940 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3941   EVT VT = Op.getValueType();
3942   if (VT.isVector())
3943     return LowerVectorFP_TO_INT(Op, DAG);
3944   if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3945     RTLIB::Libcall LC;
3946     if (Op.getOpcode() == ISD::FP_TO_SINT)
3947       LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
3948                               Op.getValueType());
3949     else
3950       LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
3951                               Op.getValueType());
3952     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3953                        /*isSigned*/ false, SDLoc(Op)).first;
3954   }
3955
3956   return Op;
3957 }
3958
3959 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3960   EVT VT = Op.getValueType();
3961   SDLoc dl(Op);
3962
3963   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3964     if (VT.getVectorElementType() == MVT::f32)
3965       return Op;
3966     return DAG.UnrollVectorOp(Op.getNode());
3967   }
3968
3969   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3970          "Invalid type for custom lowering!");
3971   if (VT != MVT::v4f32)
3972     return DAG.UnrollVectorOp(Op.getNode());
3973
3974   unsigned CastOpc;
3975   unsigned Opc;
3976   switch (Op.getOpcode()) {
3977   default: llvm_unreachable("Invalid opcode!");
3978   case ISD::SINT_TO_FP:
3979     CastOpc = ISD::SIGN_EXTEND;
3980     Opc = ISD::SINT_TO_FP;
3981     break;
3982   case ISD::UINT_TO_FP:
3983     CastOpc = ISD::ZERO_EXTEND;
3984     Opc = ISD::UINT_TO_FP;
3985     break;
3986   }
3987
3988   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3989   return DAG.getNode(Opc, dl, VT, Op);
3990 }
3991
3992 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
3993   EVT VT = Op.getValueType();
3994   if (VT.isVector())
3995     return LowerVectorINT_TO_FP(Op, DAG);
3996   if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
3997     RTLIB::Libcall LC;
3998     if (Op.getOpcode() == ISD::SINT_TO_FP)
3999       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
4000                               Op.getValueType());
4001     else
4002       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
4003                               Op.getValueType());
4004     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
4005                        /*isSigned*/ false, SDLoc(Op)).first;
4006   }
4007
4008   return Op;
4009 }
4010
4011 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
4012   // Implement fcopysign with a fabs and a conditional fneg.
4013   SDValue Tmp0 = Op.getOperand(0);
4014   SDValue Tmp1 = Op.getOperand(1);
4015   SDLoc dl(Op);
4016   EVT VT = Op.getValueType();
4017   EVT SrcVT = Tmp1.getValueType();
4018   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
4019     Tmp0.getOpcode() == ARMISD::VMOVDRR;
4020   bool UseNEON = !InGPR && Subtarget->hasNEON();
4021
4022   if (UseNEON) {
4023     // Use VBSL to copy the sign bit.
4024     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
4025     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
4026                                DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
4027     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
4028     if (VT == MVT::f64)
4029       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4030                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
4031                          DAG.getConstant(32, dl, MVT::i32));
4032     else /*if (VT == MVT::f32)*/
4033       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
4034     if (SrcVT == MVT::f32) {
4035       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4036       if (VT == MVT::f64)
4037         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4038                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4039                            DAG.getConstant(32, dl, MVT::i32));
4040     } else if (VT == MVT::f32)
4041       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4042                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4043                          DAG.getConstant(32, dl, MVT::i32));
4044     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4045     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4046
4047     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4048                                             dl, MVT::i32);
4049     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4050     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4051                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4052
4053     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4054                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4055                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4056     if (VT == MVT::f32) {
4057       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4058       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4059                         DAG.getConstant(0, dl, MVT::i32));
4060     } else {
4061       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4062     }
4063
4064     return Res;
4065   }
4066
4067   // Bitcast operand 1 to i32.
4068   if (SrcVT == MVT::f64)
4069     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4070                        Tmp1).getValue(1);
4071   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4072
4073   // Or in the signbit with integer operations.
4074   SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
4075   SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4076   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4077   if (VT == MVT::f32) {
4078     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4079                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4080     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4081                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4082   }
4083
4084   // f64: Or the high part with signbit and then combine two parts.
4085   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4086                      Tmp0);
4087   SDValue Lo = Tmp0.getValue(0);
4088   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4089   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4090   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4091 }
4092
4093 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4094   MachineFunction &MF = DAG.getMachineFunction();
4095   MachineFrameInfo *MFI = MF.getFrameInfo();
4096   MFI->setReturnAddressIsTaken(true);
4097
4098   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4099     return SDValue();
4100
4101   EVT VT = Op.getValueType();
4102   SDLoc dl(Op);
4103   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4104   if (Depth) {
4105     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4106     SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
4107     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4108                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4109                        MachinePointerInfo(), false, false, false, 0);
4110   }
4111
4112   // Return LR, which contains the return address. Mark it an implicit live-in.
4113   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4114   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4115 }
4116
4117 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4118   const ARMBaseRegisterInfo &ARI =
4119     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4120   MachineFunction &MF = DAG.getMachineFunction();
4121   MachineFrameInfo *MFI = MF.getFrameInfo();
4122   MFI->setFrameAddressIsTaken(true);
4123
4124   EVT VT = Op.getValueType();
4125   SDLoc dl(Op);  // FIXME probably not meaningful
4126   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4127   unsigned FrameReg = ARI.getFrameRegister(MF);
4128   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4129   while (Depth--)
4130     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4131                             MachinePointerInfo(),
4132                             false, false, false, 0);
4133   return FrameAddr;
4134 }
4135
4136 // FIXME? Maybe this could be a TableGen attribute on some registers and
4137 // this table could be generated automatically from RegInfo.
4138 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
4139                                               SelectionDAG &DAG) const {
4140   unsigned Reg = StringSwitch<unsigned>(RegName)
4141                        .Case("sp", ARM::SP)
4142                        .Default(0);
4143   if (Reg)
4144     return Reg;
4145   report_fatal_error(Twine("Invalid register name \""
4146                               + StringRef(RegName)  + "\"."));
4147 }
4148
4149 // Result is 64 bit value so split into two 32 bit values and return as a
4150 // pair of values.
4151 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
4152                                 SelectionDAG &DAG) {
4153   SDLoc DL(N);
4154
4155   // This function is only supposed to be called for i64 type destination.
4156   assert(N->getValueType(0) == MVT::i64
4157           && "ExpandREAD_REGISTER called for non-i64 type result.");
4158
4159   SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
4160                              DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
4161                              N->getOperand(0),
4162                              N->getOperand(1));
4163
4164   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
4165                     Read.getValue(1)));
4166   Results.push_back(Read.getOperand(0));
4167 }
4168
4169 /// ExpandBITCAST - If the target supports VFP, this function is called to
4170 /// expand a bit convert where either the source or destination type is i64 to
4171 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
4172 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4173 /// vectors), since the legalizer won't know what to do with that.
4174 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4175   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4176   SDLoc dl(N);
4177   SDValue Op = N->getOperand(0);
4178
4179   // This function is only supposed to be called for i64 types, either as the
4180   // source or destination of the bit convert.
4181   EVT SrcVT = Op.getValueType();
4182   EVT DstVT = N->getValueType(0);
4183   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4184          "ExpandBITCAST called for non-i64 type");
4185
4186   // Turn i64->f64 into VMOVDRR.
4187   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4188     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4189                              DAG.getConstant(0, dl, MVT::i32));
4190     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4191                              DAG.getConstant(1, dl, MVT::i32));
4192     return DAG.getNode(ISD::BITCAST, dl, DstVT,
4193                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4194   }
4195
4196   // Turn f64->i64 into VMOVRRD.
4197   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4198     SDValue Cvt;
4199     if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
4200         SrcVT.getVectorNumElements() > 1)
4201       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4202                         DAG.getVTList(MVT::i32, MVT::i32),
4203                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4204     else
4205       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4206                         DAG.getVTList(MVT::i32, MVT::i32), Op);
4207     // Merge the pieces into a single i64 value.
4208     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4209   }
4210
4211   return SDValue();
4212 }
4213
4214 /// getZeroVector - Returns a vector of specified type with all zero elements.
4215 /// Zero vectors are used to represent vector negation and in those cases
4216 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
4217 /// not support i64 elements, so sometimes the zero vectors will need to be
4218 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
4219 /// zero vector.
4220 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4221   assert(VT.isVector() && "Expected a vector type");
4222   // The canonical modified immediate encoding of a zero vector is....0!
4223   SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
4224   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4225   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4226   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4227 }
4228
4229 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4230 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4231 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4232                                                 SelectionDAG &DAG) const {
4233   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4234   EVT VT = Op.getValueType();
4235   unsigned VTBits = VT.getSizeInBits();
4236   SDLoc dl(Op);
4237   SDValue ShOpLo = Op.getOperand(0);
4238   SDValue ShOpHi = Op.getOperand(1);
4239   SDValue ShAmt  = Op.getOperand(2);
4240   SDValue ARMcc;
4241   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4242
4243   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4244
4245   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4246                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4247   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4248   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4249                                    DAG.getConstant(VTBits, dl, MVT::i32));
4250   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4251   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4252   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4253
4254   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4255   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4256                           ISD::SETGE, ARMcc, DAG, dl);
4257   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4258   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4259                            CCR, Cmp);
4260
4261   SDValue Ops[2] = { Lo, Hi };
4262   return DAG.getMergeValues(Ops, dl);
4263 }
4264
4265 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4266 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4267 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4268                                                SelectionDAG &DAG) const {
4269   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4270   EVT VT = Op.getValueType();
4271   unsigned VTBits = VT.getSizeInBits();
4272   SDLoc dl(Op);
4273   SDValue ShOpLo = Op.getOperand(0);
4274   SDValue ShOpHi = Op.getOperand(1);
4275   SDValue ShAmt  = Op.getOperand(2);
4276   SDValue ARMcc;
4277
4278   assert(Op.getOpcode() == ISD::SHL_PARTS);
4279   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4280                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4281   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4282   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4283                                    DAG.getConstant(VTBits, dl, MVT::i32));
4284   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4285   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4286
4287   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4288   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4289   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4290                           ISD::SETGE, ARMcc, DAG, dl);
4291   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4292   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4293                            CCR, Cmp);
4294
4295   SDValue Ops[2] = { Lo, Hi };
4296   return DAG.getMergeValues(Ops, dl);
4297 }
4298
4299 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4300                                             SelectionDAG &DAG) const {
4301   // The rounding mode is in bits 23:22 of the FPSCR.
4302   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4303   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4304   // so that the shift + and get folded into a bitfield extract.
4305   SDLoc dl(Op);
4306   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4307                               DAG.getConstant(Intrinsic::arm_get_fpscr, dl,
4308                                               MVT::i32));
4309   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4310                                   DAG.getConstant(1U << 22, dl, MVT::i32));
4311   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4312                               DAG.getConstant(22, dl, MVT::i32));
4313   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4314                      DAG.getConstant(3, dl, MVT::i32));
4315 }
4316
4317 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4318                          const ARMSubtarget *ST) {
4319   SDLoc dl(N);
4320   EVT VT = N->getValueType(0);
4321   if (VT.isVector()) {
4322     assert(ST->hasNEON());
4323
4324     // Compute the least significant set bit: LSB = X & -X
4325     SDValue X = N->getOperand(0);
4326     SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
4327     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
4328
4329     EVT ElemTy = VT.getVectorElementType();
4330
4331     if (ElemTy == MVT::i8) {
4332       // Compute with: cttz(x) = ctpop(lsb - 1)
4333       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4334                                 DAG.getTargetConstant(1, dl, ElemTy));
4335       SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4336       return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
4337     }
4338
4339     if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
4340         (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
4341       // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
4342       unsigned NumBits = ElemTy.getSizeInBits();
4343       SDValue WidthMinus1 =
4344           DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4345                       DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
4346       SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
4347       return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
4348     }
4349
4350     // Compute with: cttz(x) = ctpop(lsb - 1)
4351
4352     // Since we can only compute the number of bits in a byte with vcnt.8, we
4353     // have to gather the result with pairwise addition (vpaddl) for i16, i32,
4354     // and i64.
4355
4356     // Compute LSB - 1.
4357     SDValue Bits;
4358     if (ElemTy == MVT::i64) {
4359       // Load constant 0xffff'ffff'ffff'ffff to register.
4360       SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4361                                DAG.getTargetConstant(0x1eff, dl, MVT::i32));
4362       Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
4363     } else {
4364       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4365                                 DAG.getTargetConstant(1, dl, ElemTy));
4366       Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4367     }
4368
4369     // Count #bits with vcnt.8.
4370     EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4371     SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits);
4372     SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8);
4373
4374     // Gather the #bits with vpaddl (pairwise add.)
4375     EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4376     SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit,
4377         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4378         Cnt8);
4379     if (ElemTy == MVT::i16)
4380       return Cnt16;
4381
4382     EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32;
4383     SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit,
4384         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4385         Cnt16);
4386     if (ElemTy == MVT::i32)
4387       return Cnt32;
4388
4389     assert(ElemTy == MVT::i64);
4390     SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4391         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4392         Cnt32);
4393     return Cnt64;
4394   }
4395
4396   if (!ST->hasV6T2Ops())
4397     return SDValue();
4398
4399   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4400   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4401 }
4402
4403 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4404 /// for each 16-bit element from operand, repeated.  The basic idea is to
4405 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4406 ///
4407 /// Trace for v4i16:
4408 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
4409 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4410 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4411 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4412 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
4413 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
4414 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4415 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
4416 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4417   EVT VT = N->getValueType(0);
4418   SDLoc DL(N);
4419
4420   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4421   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4422   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4423   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4424   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4425   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4426 }
4427
4428 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4429 /// bit-count for each 16-bit element from the operand.  We need slightly
4430 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4431 /// 64/128-bit registers.
4432 ///
4433 /// Trace for v4i16:
4434 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
4435 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4436 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
4437 /// v4i16:Extracted = [k0    k1    k2    k3    ]
4438 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4439   EVT VT = N->getValueType(0);
4440   SDLoc DL(N);
4441
4442   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4443   if (VT.is64BitVector()) {
4444     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4445     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4446                        DAG.getIntPtrConstant(0, DL));
4447   } else {
4448     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4449                                     BitCounts, DAG.getIntPtrConstant(0, DL));
4450     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4451   }
4452 }
4453
4454 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4455 /// bit-count for each 32-bit element from the operand.  The idea here is
4456 /// to split the vector into 16-bit elements, leverage the 16-bit count
4457 /// routine, and then combine the results.
4458 ///
4459 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4460 /// input    = [v0    v1    ] (vi: 32-bit elements)
4461 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4462 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4463 /// vrev: N0 = [k1 k0 k3 k2 ]
4464 ///            [k0 k1 k2 k3 ]
4465 ///       N1 =+[k1 k0 k3 k2 ]
4466 ///            [k0 k2 k1 k3 ]
4467 ///       N2 =+[k1 k3 k0 k2 ]
4468 ///            [k0    k2    k1    k3    ]
4469 /// Extended =+[k1    k3    k0    k2    ]
4470 ///            [k0    k2    ]
4471 /// Extracted=+[k1    k3    ]
4472 ///
4473 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4474   EVT VT = N->getValueType(0);
4475   SDLoc DL(N);
4476
4477   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4478
4479   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4480   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4481   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4482   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4483   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4484
4485   if (VT.is64BitVector()) {
4486     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4487     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4488                        DAG.getIntPtrConstant(0, DL));
4489   } else {
4490     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4491                                     DAG.getIntPtrConstant(0, DL));
4492     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4493   }
4494 }
4495
4496 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4497                           const ARMSubtarget *ST) {
4498   EVT VT = N->getValueType(0);
4499
4500   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4501   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4502           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4503          "Unexpected type for custom ctpop lowering");
4504
4505   if (VT.getVectorElementType() == MVT::i32)
4506     return lowerCTPOP32BitElements(N, DAG);
4507   else
4508     return lowerCTPOP16BitElements(N, DAG);
4509 }
4510
4511 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4512                           const ARMSubtarget *ST) {
4513   EVT VT = N->getValueType(0);
4514   SDLoc dl(N);
4515
4516   if (!VT.isVector())
4517     return SDValue();
4518
4519   // Lower vector shifts on NEON to use VSHL.
4520   assert(ST->hasNEON() && "unexpected vector shift");
4521
4522   // Left shifts translate directly to the vshiftu intrinsic.
4523   if (N->getOpcode() == ISD::SHL)
4524     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4525                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
4526                                        MVT::i32),
4527                        N->getOperand(0), N->getOperand(1));
4528
4529   assert((N->getOpcode() == ISD::SRA ||
4530           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4531
4532   // NEON uses the same intrinsics for both left and right shifts.  For
4533   // right shifts, the shift amounts are negative, so negate the vector of
4534   // shift amounts.
4535   EVT ShiftVT = N->getOperand(1).getValueType();
4536   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4537                                      getZeroVector(ShiftVT, DAG, dl),
4538                                      N->getOperand(1));
4539   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4540                              Intrinsic::arm_neon_vshifts :
4541                              Intrinsic::arm_neon_vshiftu);
4542   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4543                      DAG.getConstant(vshiftInt, dl, MVT::i32),
4544                      N->getOperand(0), NegatedCount);
4545 }
4546
4547 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4548                                 const ARMSubtarget *ST) {
4549   EVT VT = N->getValueType(0);
4550   SDLoc dl(N);
4551
4552   // We can get here for a node like i32 = ISD::SHL i32, i64
4553   if (VT != MVT::i64)
4554     return SDValue();
4555
4556   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4557          "Unknown shift to lower!");
4558
4559   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4560   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4561       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4562     return SDValue();
4563
4564   // If we are in thumb mode, we don't have RRX.
4565   if (ST->isThumb1Only()) return SDValue();
4566
4567   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4568   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4569                            DAG.getConstant(0, dl, MVT::i32));
4570   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4571                            DAG.getConstant(1, dl, MVT::i32));
4572
4573   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4574   // captures the result into a carry flag.
4575   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4576   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4577
4578   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4579   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4580
4581   // Merge the pieces into a single i64 value.
4582  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4583 }
4584
4585 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4586   SDValue TmpOp0, TmpOp1;
4587   bool Invert = false;
4588   bool Swap = false;
4589   unsigned Opc = 0;
4590
4591   SDValue Op0 = Op.getOperand(0);
4592   SDValue Op1 = Op.getOperand(1);
4593   SDValue CC = Op.getOperand(2);
4594   EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
4595   EVT VT = Op.getValueType();
4596   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4597   SDLoc dl(Op);
4598
4599   if (Op1.getValueType().isFloatingPoint()) {
4600     switch (SetCCOpcode) {
4601     default: llvm_unreachable("Illegal FP comparison");
4602     case ISD::SETUNE:
4603     case ISD::SETNE:  Invert = true; // Fallthrough
4604     case ISD::SETOEQ:
4605     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4606     case ISD::SETOLT:
4607     case ISD::SETLT: Swap = true; // Fallthrough
4608     case ISD::SETOGT:
4609     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4610     case ISD::SETOLE:
4611     case ISD::SETLE:  Swap = true; // Fallthrough
4612     case ISD::SETOGE:
4613     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4614     case ISD::SETUGE: Swap = true; // Fallthrough
4615     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4616     case ISD::SETUGT: Swap = true; // Fallthrough
4617     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4618     case ISD::SETUEQ: Invert = true; // Fallthrough
4619     case ISD::SETONE:
4620       // Expand this to (OLT | OGT).
4621       TmpOp0 = Op0;
4622       TmpOp1 = Op1;
4623       Opc = ISD::OR;
4624       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4625       Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
4626       break;
4627     case ISD::SETUO: Invert = true; // Fallthrough
4628     case ISD::SETO:
4629       // Expand this to (OLT | OGE).
4630       TmpOp0 = Op0;
4631       TmpOp1 = Op1;
4632       Opc = ISD::OR;
4633       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4634       Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
4635       break;
4636     }
4637   } else {
4638     // Integer comparisons.
4639     switch (SetCCOpcode) {
4640     default: llvm_unreachable("Illegal integer comparison");
4641     case ISD::SETNE:  Invert = true;
4642     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4643     case ISD::SETLT:  Swap = true;
4644     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4645     case ISD::SETLE:  Swap = true;
4646     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4647     case ISD::SETULT: Swap = true;
4648     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4649     case ISD::SETULE: Swap = true;
4650     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4651     }
4652
4653     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4654     if (Opc == ARMISD::VCEQ) {
4655
4656       SDValue AndOp;
4657       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4658         AndOp = Op0;
4659       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4660         AndOp = Op1;
4661
4662       // Ignore bitconvert.
4663       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4664         AndOp = AndOp.getOperand(0);
4665
4666       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4667         Opc = ARMISD::VTST;
4668         Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
4669         Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
4670         Invert = !Invert;
4671       }
4672     }
4673   }
4674
4675   if (Swap)
4676     std::swap(Op0, Op1);
4677
4678   // If one of the operands is a constant vector zero, attempt to fold the
4679   // comparison to a specialized compare-against-zero form.
4680   SDValue SingleOp;
4681   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4682     SingleOp = Op0;
4683   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4684     if (Opc == ARMISD::VCGE)
4685       Opc = ARMISD::VCLEZ;
4686     else if (Opc == ARMISD::VCGT)
4687       Opc = ARMISD::VCLTZ;
4688     SingleOp = Op1;
4689   }
4690
4691   SDValue Result;
4692   if (SingleOp.getNode()) {
4693     switch (Opc) {
4694     case ARMISD::VCEQ:
4695       Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
4696     case ARMISD::VCGE:
4697       Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
4698     case ARMISD::VCLEZ:
4699       Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
4700     case ARMISD::VCGT:
4701       Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
4702     case ARMISD::VCLTZ:
4703       Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
4704     default:
4705       Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4706     }
4707   } else {
4708      Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4709   }
4710
4711   Result = DAG.getSExtOrTrunc(Result, dl, VT);
4712
4713   if (Invert)
4714     Result = DAG.getNOT(dl, Result, VT);
4715
4716   return Result;
4717 }
4718
4719 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4720 /// valid vector constant for a NEON instruction with a "modified immediate"
4721 /// operand (e.g., VMOV).  If so, return the encoded value.
4722 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4723                                  unsigned SplatBitSize, SelectionDAG &DAG,
4724                                  SDLoc dl, EVT &VT, bool is128Bits,
4725                                  NEONModImmType type) {
4726   unsigned OpCmode, Imm;
4727
4728   // SplatBitSize is set to the smallest size that splats the vector, so a
4729   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4730   // immediate instructions others than VMOV do not support the 8-bit encoding
4731   // of a zero vector, and the default encoding of zero is supposed to be the
4732   // 32-bit version.
4733   if (SplatBits == 0)
4734     SplatBitSize = 32;
4735
4736   switch (SplatBitSize) {
4737   case 8:
4738     if (type != VMOVModImm)
4739       return SDValue();
4740     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4741     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4742     OpCmode = 0xe;
4743     Imm = SplatBits;
4744     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4745     break;
4746
4747   case 16:
4748     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4749     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4750     if ((SplatBits & ~0xff) == 0) {
4751       // Value = 0x00nn: Op=x, Cmode=100x.
4752       OpCmode = 0x8;
4753       Imm = SplatBits;
4754       break;
4755     }
4756     if ((SplatBits & ~0xff00) == 0) {
4757       // Value = 0xnn00: Op=x, Cmode=101x.
4758       OpCmode = 0xa;
4759       Imm = SplatBits >> 8;
4760       break;
4761     }
4762     return SDValue();
4763
4764   case 32:
4765     // NEON's 32-bit VMOV supports splat values where:
4766     // * only one byte is nonzero, or
4767     // * the least significant byte is 0xff and the second byte is nonzero, or
4768     // * the least significant 2 bytes are 0xff and the third is nonzero.
4769     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4770     if ((SplatBits & ~0xff) == 0) {
4771       // Value = 0x000000nn: Op=x, Cmode=000x.
4772       OpCmode = 0;
4773       Imm = SplatBits;
4774       break;
4775     }
4776     if ((SplatBits & ~0xff00) == 0) {
4777       // Value = 0x0000nn00: Op=x, Cmode=001x.
4778       OpCmode = 0x2;
4779       Imm = SplatBits >> 8;
4780       break;
4781     }
4782     if ((SplatBits & ~0xff0000) == 0) {
4783       // Value = 0x00nn0000: Op=x, Cmode=010x.
4784       OpCmode = 0x4;
4785       Imm = SplatBits >> 16;
4786       break;
4787     }
4788     if ((SplatBits & ~0xff000000) == 0) {
4789       // Value = 0xnn000000: Op=x, Cmode=011x.
4790       OpCmode = 0x6;
4791       Imm = SplatBits >> 24;
4792       break;
4793     }
4794
4795     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4796     if (type == OtherModImm) return SDValue();
4797
4798     if ((SplatBits & ~0xffff) == 0 &&
4799         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4800       // Value = 0x0000nnff: Op=x, Cmode=1100.
4801       OpCmode = 0xc;
4802       Imm = SplatBits >> 8;
4803       break;
4804     }
4805
4806     if ((SplatBits & ~0xffffff) == 0 &&
4807         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4808       // Value = 0x00nnffff: Op=x, Cmode=1101.
4809       OpCmode = 0xd;
4810       Imm = SplatBits >> 16;
4811       break;
4812     }
4813
4814     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4815     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4816     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4817     // and fall through here to test for a valid 64-bit splat.  But, then the
4818     // caller would also need to check and handle the change in size.
4819     return SDValue();
4820
4821   case 64: {
4822     if (type != VMOVModImm)
4823       return SDValue();
4824     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4825     uint64_t BitMask = 0xff;
4826     uint64_t Val = 0;
4827     unsigned ImmMask = 1;
4828     Imm = 0;
4829     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4830       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4831         Val |= BitMask;
4832         Imm |= ImmMask;
4833       } else if ((SplatBits & BitMask) != 0) {
4834         return SDValue();
4835       }
4836       BitMask <<= 8;
4837       ImmMask <<= 1;
4838     }
4839
4840     if (DAG.getDataLayout().isBigEndian())
4841       // swap higher and lower 32 bit word
4842       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4843
4844     // Op=1, Cmode=1110.
4845     OpCmode = 0x1e;
4846     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4847     break;
4848   }
4849
4850   default:
4851     llvm_unreachable("unexpected size for isNEONModifiedImm");
4852   }
4853
4854   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4855   return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
4856 }
4857
4858 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4859                                            const ARMSubtarget *ST) const {
4860   if (!ST->hasVFP3())
4861     return SDValue();
4862
4863   bool IsDouble = Op.getValueType() == MVT::f64;
4864   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4865
4866   // Use the default (constant pool) lowering for double constants when we have
4867   // an SP-only FPU
4868   if (IsDouble && Subtarget->isFPOnlySP())
4869     return SDValue();
4870
4871   // Try splatting with a VMOV.f32...
4872   APFloat FPVal = CFP->getValueAPF();
4873   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4874
4875   if (ImmVal != -1) {
4876     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4877       // We have code in place to select a valid ConstantFP already, no need to
4878       // do any mangling.
4879       return Op;
4880     }
4881
4882     // It's a float and we are trying to use NEON operations where
4883     // possible. Lower it to a splat followed by an extract.
4884     SDLoc DL(Op);
4885     SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
4886     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4887                                       NewVal);
4888     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4889                        DAG.getConstant(0, DL, MVT::i32));
4890   }
4891
4892   // The rest of our options are NEON only, make sure that's allowed before
4893   // proceeding..
4894   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4895     return SDValue();
4896
4897   EVT VMovVT;
4898   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4899
4900   // It wouldn't really be worth bothering for doubles except for one very
4901   // important value, which does happen to match: 0.0. So make sure we don't do
4902   // anything stupid.
4903   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4904     return SDValue();
4905
4906   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4907   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
4908                                      VMovVT, false, VMOVModImm);
4909   if (NewVal != SDValue()) {
4910     SDLoc DL(Op);
4911     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4912                                       NewVal);
4913     if (IsDouble)
4914       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4915
4916     // It's a float: cast and extract a vector element.
4917     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4918                                        VecConstant);
4919     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4920                        DAG.getConstant(0, DL, MVT::i32));
4921   }
4922
4923   // Finally, try a VMVN.i32
4924   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
4925                              false, VMVNModImm);
4926   if (NewVal != SDValue()) {
4927     SDLoc DL(Op);
4928     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4929
4930     if (IsDouble)
4931       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4932
4933     // It's a float: cast and extract a vector element.
4934     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4935                                        VecConstant);
4936     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4937                        DAG.getConstant(0, DL, MVT::i32));
4938   }
4939
4940   return SDValue();
4941 }
4942
4943 // check if an VEXT instruction can handle the shuffle mask when the
4944 // vector sources of the shuffle are the same.
4945 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4946   unsigned NumElts = VT.getVectorNumElements();
4947
4948   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4949   if (M[0] < 0)
4950     return false;
4951
4952   Imm = M[0];
4953
4954   // If this is a VEXT shuffle, the immediate value is the index of the first
4955   // element.  The other shuffle indices must be the successive elements after
4956   // the first one.
4957   unsigned ExpectedElt = Imm;
4958   for (unsigned i = 1; i < NumElts; ++i) {
4959     // Increment the expected index.  If it wraps around, just follow it
4960     // back to index zero and keep going.
4961     ++ExpectedElt;
4962     if (ExpectedElt == NumElts)
4963       ExpectedElt = 0;
4964
4965     if (M[i] < 0) continue; // ignore UNDEF indices
4966     if (ExpectedElt != static_cast<unsigned>(M[i]))
4967       return false;
4968   }
4969
4970   return true;
4971 }
4972
4973
4974 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4975                        bool &ReverseVEXT, unsigned &Imm) {
4976   unsigned NumElts = VT.getVectorNumElements();
4977   ReverseVEXT = false;
4978
4979   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4980   if (M[0] < 0)
4981     return false;
4982
4983   Imm = M[0];
4984
4985   // If this is a VEXT shuffle, the immediate value is the index of the first
4986   // element.  The other shuffle indices must be the successive elements after
4987   // the first one.
4988   unsigned ExpectedElt = Imm;
4989   for (unsigned i = 1; i < NumElts; ++i) {
4990     // Increment the expected index.  If it wraps around, it may still be
4991     // a VEXT but the source vectors must be swapped.
4992     ExpectedElt += 1;
4993     if (ExpectedElt == NumElts * 2) {
4994       ExpectedElt = 0;
4995       ReverseVEXT = true;
4996     }
4997
4998     if (M[i] < 0) continue; // ignore UNDEF indices
4999     if (ExpectedElt != static_cast<unsigned>(M[i]))
5000       return false;
5001   }
5002
5003   // Adjust the index value if the source operands will be swapped.
5004   if (ReverseVEXT)
5005     Imm -= NumElts;
5006
5007   return true;
5008 }
5009
5010 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
5011 /// instruction with the specified blocksize.  (The order of the elements
5012 /// within each block of the vector is reversed.)
5013 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5014   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
5015          "Only possible block sizes for VREV are: 16, 32, 64");
5016
5017   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5018   if (EltSz == 64)
5019     return false;
5020
5021   unsigned NumElts = VT.getVectorNumElements();
5022   unsigned BlockElts = M[0] + 1;
5023   // If the first shuffle index is UNDEF, be optimistic.
5024   if (M[0] < 0)
5025     BlockElts = BlockSize / EltSz;
5026
5027   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5028     return false;
5029
5030   for (unsigned i = 0; i < NumElts; ++i) {
5031     if (M[i] < 0) continue; // ignore UNDEF indices
5032     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
5033       return false;
5034   }
5035
5036   return true;
5037 }
5038
5039 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
5040   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
5041   // range, then 0 is placed into the resulting vector. So pretty much any mask
5042   // of 8 elements can work here.
5043   return VT == MVT::v8i8 && M.size() == 8;
5044 }
5045
5046 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5047   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5048   if (EltSz == 64)
5049     return false;
5050
5051   unsigned NumElts = VT.getVectorNumElements();
5052   WhichResult = (M[0] == 0 ? 0 : 1);
5053   for (unsigned i = 0; i < NumElts; i += 2) {
5054     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
5055         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
5056       return false;
5057   }
5058   return true;
5059 }
5060
5061 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
5062 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5063 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5064 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5065   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5066   if (EltSz == 64)
5067     return false;
5068
5069   unsigned NumElts = VT.getVectorNumElements();
5070   WhichResult = (M[0] == 0 ? 0 : 1);
5071   for (unsigned i = 0; i < NumElts; i += 2) {
5072     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
5073         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
5074       return false;
5075   }
5076   return true;
5077 }
5078
5079 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5080   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5081   if (EltSz == 64)
5082     return false;
5083
5084   unsigned NumElts = VT.getVectorNumElements();
5085   WhichResult = (M[0] == 0 ? 0 : 1);
5086   for (unsigned i = 0; i != NumElts; ++i) {
5087     if (M[i] < 0) continue; // ignore UNDEF indices
5088     if ((unsigned) M[i] != 2 * i + WhichResult)
5089       return false;
5090   }
5091
5092   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5093   if (VT.is64BitVector() && EltSz == 32)
5094     return false;
5095
5096   return true;
5097 }
5098
5099 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
5100 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5101 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5102 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5103   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5104   if (EltSz == 64)
5105     return false;
5106
5107   unsigned Half = VT.getVectorNumElements() / 2;
5108   WhichResult = (M[0] == 0 ? 0 : 1);
5109   for (unsigned j = 0; j != 2; ++j) {
5110     unsigned Idx = WhichResult;
5111     for (unsigned i = 0; i != Half; ++i) {
5112       int MIdx = M[i + j * Half];
5113       if (MIdx >= 0 && (unsigned) MIdx != Idx)
5114         return false;
5115       Idx += 2;
5116     }
5117   }
5118
5119   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5120   if (VT.is64BitVector() && EltSz == 32)
5121     return false;
5122
5123   return true;
5124 }
5125
5126 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5127   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5128   if (EltSz == 64)
5129     return false;
5130
5131   unsigned NumElts = VT.getVectorNumElements();
5132   WhichResult = (M[0] == 0 ? 0 : 1);
5133   unsigned Idx = WhichResult * NumElts / 2;
5134   for (unsigned i = 0; i != NumElts; i += 2) {
5135     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
5136         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
5137       return false;
5138     Idx += 1;
5139   }
5140
5141   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5142   if (VT.is64BitVector() && EltSz == 32)
5143     return false;
5144
5145   return true;
5146 }
5147
5148 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5149 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5150 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5151 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5152   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5153   if (EltSz == 64)
5154     return false;
5155
5156   unsigned NumElts = VT.getVectorNumElements();
5157   WhichResult = (M[0] == 0 ? 0 : 1);
5158   unsigned Idx = WhichResult * NumElts / 2;
5159   for (unsigned i = 0; i != NumElts; i += 2) {
5160     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
5161         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
5162       return false;
5163     Idx += 1;
5164   }
5165
5166   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5167   if (VT.is64BitVector() && EltSz == 32)
5168     return false;
5169
5170   return true;
5171 }
5172
5173 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
5174 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
5175 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
5176                                            unsigned &WhichResult,
5177                                            bool &isV_UNDEF) {
5178   isV_UNDEF = false;
5179   if (isVTRNMask(ShuffleMask, VT, WhichResult))
5180     return ARMISD::VTRN;
5181   if (isVUZPMask(ShuffleMask, VT, WhichResult))
5182     return ARMISD::VUZP;
5183   if (isVZIPMask(ShuffleMask, VT, WhichResult))
5184     return ARMISD::VZIP;
5185
5186   isV_UNDEF = true;
5187   if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5188     return ARMISD::VTRN;
5189   if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5190     return ARMISD::VUZP;
5191   if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5192     return ARMISD::VZIP;
5193
5194   return 0;
5195 }
5196
5197 /// \return true if this is a reverse operation on an vector.
5198 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5199   unsigned NumElts = VT.getVectorNumElements();
5200   // Make sure the mask has the right size.
5201   if (NumElts != M.size())
5202       return false;
5203
5204   // Look for <15, ..., 3, -1, 1, 0>.
5205   for (unsigned i = 0; i != NumElts; ++i)
5206     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5207       return false;
5208
5209   return true;
5210 }
5211
5212 // If N is an integer constant that can be moved into a register in one
5213 // instruction, return an SDValue of such a constant (will become a MOV
5214 // instruction).  Otherwise return null.
5215 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5216                                      const ARMSubtarget *ST, SDLoc dl) {
5217   uint64_t Val;
5218   if (!isa<ConstantSDNode>(N))
5219     return SDValue();
5220   Val = cast<ConstantSDNode>(N)->getZExtValue();
5221
5222   if (ST->isThumb1Only()) {
5223     if (Val <= 255 || ~Val <= 255)
5224       return DAG.getConstant(Val, dl, MVT::i32);
5225   } else {
5226     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5227       return DAG.getConstant(Val, dl, MVT::i32);
5228   }
5229   return SDValue();
5230 }
5231
5232 // If this is a case we can't handle, return null and let the default
5233 // expansion code take care of it.
5234 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5235                                              const ARMSubtarget *ST) const {
5236   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5237   SDLoc dl(Op);
5238   EVT VT = Op.getValueType();
5239
5240   APInt SplatBits, SplatUndef;
5241   unsigned SplatBitSize;
5242   bool HasAnyUndefs;
5243   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5244     if (SplatBitSize <= 64) {
5245       // Check if an immediate VMOV works.
5246       EVT VmovVT;
5247       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5248                                       SplatUndef.getZExtValue(), SplatBitSize,
5249                                       DAG, dl, VmovVT, VT.is128BitVector(),
5250                                       VMOVModImm);
5251       if (Val.getNode()) {
5252         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5253         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5254       }
5255
5256       // Try an immediate VMVN.
5257       uint64_t NegatedImm = (~SplatBits).getZExtValue();
5258       Val = isNEONModifiedImm(NegatedImm,
5259                                       SplatUndef.getZExtValue(), SplatBitSize,
5260                                       DAG, dl, VmovVT, VT.is128BitVector(),
5261                                       VMVNModImm);
5262       if (Val.getNode()) {
5263         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5264         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5265       }
5266
5267       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5268       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5269         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5270         if (ImmVal != -1) {
5271           SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
5272           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5273         }
5274       }
5275     }
5276   }
5277
5278   // Scan through the operands to see if only one value is used.
5279   //
5280   // As an optimisation, even if more than one value is used it may be more
5281   // profitable to splat with one value then change some lanes.
5282   //
5283   // Heuristically we decide to do this if the vector has a "dominant" value,
5284   // defined as splatted to more than half of the lanes.
5285   unsigned NumElts = VT.getVectorNumElements();
5286   bool isOnlyLowElement = true;
5287   bool usesOnlyOneValue = true;
5288   bool hasDominantValue = false;
5289   bool isConstant = true;
5290
5291   // Map of the number of times a particular SDValue appears in the
5292   // element list.
5293   DenseMap<SDValue, unsigned> ValueCounts;
5294   SDValue Value;
5295   for (unsigned i = 0; i < NumElts; ++i) {
5296     SDValue V = Op.getOperand(i);
5297     if (V.getOpcode() == ISD::UNDEF)
5298       continue;
5299     if (i > 0)
5300       isOnlyLowElement = false;
5301     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5302       isConstant = false;
5303
5304     ValueCounts.insert(std::make_pair(V, 0));
5305     unsigned &Count = ValueCounts[V];
5306
5307     // Is this value dominant? (takes up more than half of the lanes)
5308     if (++Count > (NumElts / 2)) {
5309       hasDominantValue = true;
5310       Value = V;
5311     }
5312   }
5313   if (ValueCounts.size() != 1)
5314     usesOnlyOneValue = false;
5315   if (!Value.getNode() && ValueCounts.size() > 0)
5316     Value = ValueCounts.begin()->first;
5317
5318   if (ValueCounts.size() == 0)
5319     return DAG.getUNDEF(VT);
5320
5321   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5322   // Keep going if we are hitting this case.
5323   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5324     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5325
5326   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5327
5328   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
5329   // i32 and try again.
5330   if (hasDominantValue && EltSize <= 32) {
5331     if (!isConstant) {
5332       SDValue N;
5333
5334       // If we are VDUPing a value that comes directly from a vector, that will
5335       // cause an unnecessary move to and from a GPR, where instead we could
5336       // just use VDUPLANE. We can only do this if the lane being extracted
5337       // is at a constant index, as the VDUP from lane instructions only have
5338       // constant-index forms.
5339       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5340           isa<ConstantSDNode>(Value->getOperand(1))) {
5341         // We need to create a new undef vector to use for the VDUPLANE if the
5342         // size of the vector from which we get the value is different than the
5343         // size of the vector that we need to create. We will insert the element
5344         // such that the register coalescer will remove unnecessary copies.
5345         if (VT != Value->getOperand(0).getValueType()) {
5346           ConstantSDNode *constIndex;
5347           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5348           assert(constIndex && "The index is not a constant!");
5349           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5350                              VT.getVectorNumElements();
5351           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5352                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5353                         Value, DAG.getConstant(index, dl, MVT::i32)),
5354                            DAG.getConstant(index, dl, MVT::i32));
5355         } else
5356           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5357                         Value->getOperand(0), Value->getOperand(1));
5358       } else
5359         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5360
5361       if (!usesOnlyOneValue) {
5362         // The dominant value was splatted as 'N', but we now have to insert
5363         // all differing elements.
5364         for (unsigned I = 0; I < NumElts; ++I) {
5365           if (Op.getOperand(I) == Value)
5366             continue;
5367           SmallVector<SDValue, 3> Ops;
5368           Ops.push_back(N);
5369           Ops.push_back(Op.getOperand(I));
5370           Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
5371           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5372         }
5373       }
5374       return N;
5375     }
5376     if (VT.getVectorElementType().isFloatingPoint()) {
5377       SmallVector<SDValue, 8> Ops;
5378       for (unsigned i = 0; i < NumElts; ++i)
5379         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5380                                   Op.getOperand(i)));
5381       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5382       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5383       Val = LowerBUILD_VECTOR(Val, DAG, ST);
5384       if (Val.getNode())
5385         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5386     }
5387     if (usesOnlyOneValue) {
5388       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5389       if (isConstant && Val.getNode())
5390         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5391     }
5392   }
5393
5394   // If all elements are constants and the case above didn't get hit, fall back
5395   // to the default expansion, which will generate a load from the constant
5396   // pool.
5397   if (isConstant)
5398     return SDValue();
5399
5400   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5401   if (NumElts >= 4) {
5402     SDValue shuffle = ReconstructShuffle(Op, DAG);
5403     if (shuffle != SDValue())
5404       return shuffle;
5405   }
5406
5407   // Vectors with 32- or 64-bit elements can be built by directly assigning
5408   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
5409   // will be legalized.
5410   if (EltSize >= 32) {
5411     // Do the expansion with floating-point types, since that is what the VFP
5412     // registers are defined to use, and since i64 is not legal.
5413     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5414     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5415     SmallVector<SDValue, 8> Ops;
5416     for (unsigned i = 0; i < NumElts; ++i)
5417       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5418     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5419     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5420   }
5421
5422   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5423   // know the default expansion would otherwise fall back on something even
5424   // worse. For a vector with one or two non-undef values, that's
5425   // scalar_to_vector for the elements followed by a shuffle (provided the
5426   // shuffle is valid for the target) and materialization element by element
5427   // on the stack followed by a load for everything else.
5428   if (!isConstant && !usesOnlyOneValue) {
5429     SDValue Vec = DAG.getUNDEF(VT);
5430     for (unsigned i = 0 ; i < NumElts; ++i) {
5431       SDValue V = Op.getOperand(i);
5432       if (V.getOpcode() == ISD::UNDEF)
5433         continue;
5434       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
5435       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5436     }
5437     return Vec;
5438   }
5439
5440   return SDValue();
5441 }
5442
5443 // Gather data to see if the operation can be modelled as a
5444 // shuffle in combination with VEXTs.
5445 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5446                                               SelectionDAG &DAG) const {
5447   SDLoc dl(Op);
5448   EVT VT = Op.getValueType();
5449   unsigned NumElts = VT.getVectorNumElements();
5450
5451   SmallVector<SDValue, 2> SourceVecs;
5452   SmallVector<unsigned, 2> MinElts;
5453   SmallVector<unsigned, 2> MaxElts;
5454
5455   for (unsigned i = 0; i < NumElts; ++i) {
5456     SDValue V = Op.getOperand(i);
5457     if (V.getOpcode() == ISD::UNDEF)
5458       continue;
5459     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5460       // A shuffle can only come from building a vector from various
5461       // elements of other vectors.
5462       return SDValue();
5463     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5464                VT.getVectorElementType()) {
5465       // This code doesn't know how to handle shuffles where the vector
5466       // element types do not match (this happens because type legalization
5467       // promotes the return type of EXTRACT_VECTOR_ELT).
5468       // FIXME: It might be appropriate to extend this code to handle
5469       // mismatched types.
5470       return SDValue();
5471     }
5472
5473     // Record this extraction against the appropriate vector if possible...
5474     SDValue SourceVec = V.getOperand(0);
5475     // If the element number isn't a constant, we can't effectively
5476     // analyze what's going on.
5477     if (!isa<ConstantSDNode>(V.getOperand(1)))
5478       return SDValue();
5479     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5480     bool FoundSource = false;
5481     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5482       if (SourceVecs[j] == SourceVec) {
5483         if (MinElts[j] > EltNo)
5484           MinElts[j] = EltNo;
5485         if (MaxElts[j] < EltNo)
5486           MaxElts[j] = EltNo;
5487         FoundSource = true;
5488         break;
5489       }
5490     }
5491
5492     // Or record a new source if not...
5493     if (!FoundSource) {
5494       SourceVecs.push_back(SourceVec);
5495       MinElts.push_back(EltNo);
5496       MaxElts.push_back(EltNo);
5497     }
5498   }
5499
5500   // Currently only do something sane when at most two source vectors
5501   // involved.
5502   if (SourceVecs.size() > 2)
5503     return SDValue();
5504
5505   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5506   int VEXTOffsets[2] = {0, 0};
5507
5508   // This loop extracts the usage patterns of the source vectors
5509   // and prepares appropriate SDValues for a shuffle if possible.
5510   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5511     if (SourceVecs[i].getValueType() == VT) {
5512       // No VEXT necessary
5513       ShuffleSrcs[i] = SourceVecs[i];
5514       VEXTOffsets[i] = 0;
5515       continue;
5516     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5517       // It probably isn't worth padding out a smaller vector just to
5518       // break it down again in a shuffle.
5519       return SDValue();
5520     }
5521
5522     // Since only 64-bit and 128-bit vectors are legal on ARM and
5523     // we've eliminated the other cases...
5524     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5525            "unexpected vector sizes in ReconstructShuffle");
5526
5527     if (MaxElts[i] - MinElts[i] >= NumElts) {
5528       // Span too large for a VEXT to cope
5529       return SDValue();
5530     }
5531
5532     if (MinElts[i] >= NumElts) {
5533       // The extraction can just take the second half
5534       VEXTOffsets[i] = NumElts;
5535       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5536                                    SourceVecs[i],
5537                                    DAG.getIntPtrConstant(NumElts, dl));
5538     } else if (MaxElts[i] < NumElts) {
5539       // The extraction can just take the first half
5540       VEXTOffsets[i] = 0;
5541       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5542                                    SourceVecs[i],
5543                                    DAG.getIntPtrConstant(0, dl));
5544     } else {
5545       // An actual VEXT is needed
5546       VEXTOffsets[i] = MinElts[i];
5547       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5548                                      SourceVecs[i],
5549                                      DAG.getIntPtrConstant(0, dl));
5550       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5551                                      SourceVecs[i],
5552                                      DAG.getIntPtrConstant(NumElts, dl));
5553       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5554                                    DAG.getConstant(VEXTOffsets[i], dl,
5555                                                    MVT::i32));
5556     }
5557   }
5558
5559   SmallVector<int, 8> Mask;
5560
5561   for (unsigned i = 0; i < NumElts; ++i) {
5562     SDValue Entry = Op.getOperand(i);
5563     if (Entry.getOpcode() == ISD::UNDEF) {
5564       Mask.push_back(-1);
5565       continue;
5566     }
5567
5568     SDValue ExtractVec = Entry.getOperand(0);
5569     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5570                                           .getOperand(1))->getSExtValue();
5571     if (ExtractVec == SourceVecs[0]) {
5572       Mask.push_back(ExtractElt - VEXTOffsets[0]);
5573     } else {
5574       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5575     }
5576   }
5577
5578   // Final check before we try to produce nonsense...
5579   if (isShuffleMaskLegal(Mask, VT))
5580     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5581                                 &Mask[0]);
5582
5583   return SDValue();
5584 }
5585
5586 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5587 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5588 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5589 /// are assumed to be legal.
5590 bool
5591 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5592                                       EVT VT) const {
5593   if (VT.getVectorNumElements() == 4 &&
5594       (VT.is128BitVector() || VT.is64BitVector())) {
5595     unsigned PFIndexes[4];
5596     for (unsigned i = 0; i != 4; ++i) {
5597       if (M[i] < 0)
5598         PFIndexes[i] = 8;
5599       else
5600         PFIndexes[i] = M[i];
5601     }
5602
5603     // Compute the index in the perfect shuffle table.
5604     unsigned PFTableIndex =
5605       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5606     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5607     unsigned Cost = (PFEntry >> 30);
5608
5609     if (Cost <= 4)
5610       return true;
5611   }
5612
5613   bool ReverseVEXT, isV_UNDEF;
5614   unsigned Imm, WhichResult;
5615
5616   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5617   return (EltSize >= 32 ||
5618           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5619           isVREVMask(M, VT, 64) ||
5620           isVREVMask(M, VT, 32) ||
5621           isVREVMask(M, VT, 16) ||
5622           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5623           isVTBLMask(M, VT) ||
5624           isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) ||
5625           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5626 }
5627
5628 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5629 /// the specified operations to build the shuffle.
5630 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5631                                       SDValue RHS, SelectionDAG &DAG,
5632                                       SDLoc dl) {
5633   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5634   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5635   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5636
5637   enum {
5638     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5639     OP_VREV,
5640     OP_VDUP0,
5641     OP_VDUP1,
5642     OP_VDUP2,
5643     OP_VDUP3,
5644     OP_VEXT1,
5645     OP_VEXT2,
5646     OP_VEXT3,
5647     OP_VUZPL, // VUZP, left result
5648     OP_VUZPR, // VUZP, right result
5649     OP_VZIPL, // VZIP, left result
5650     OP_VZIPR, // VZIP, right result
5651     OP_VTRNL, // VTRN, left result
5652     OP_VTRNR  // VTRN, right result
5653   };
5654
5655   if (OpNum == OP_COPY) {
5656     if (LHSID == (1*9+2)*9+3) return LHS;
5657     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5658     return RHS;
5659   }
5660
5661   SDValue OpLHS, OpRHS;
5662   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5663   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5664   EVT VT = OpLHS.getValueType();
5665
5666   switch (OpNum) {
5667   default: llvm_unreachable("Unknown shuffle opcode!");
5668   case OP_VREV:
5669     // VREV divides the vector in half and swaps within the half.
5670     if (VT.getVectorElementType() == MVT::i32 ||
5671         VT.getVectorElementType() == MVT::f32)
5672       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5673     // vrev <4 x i16> -> VREV32
5674     if (VT.getVectorElementType() == MVT::i16)
5675       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5676     // vrev <4 x i8> -> VREV16
5677     assert(VT.getVectorElementType() == MVT::i8);
5678     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5679   case OP_VDUP0:
5680   case OP_VDUP1:
5681   case OP_VDUP2:
5682   case OP_VDUP3:
5683     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5684                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
5685   case OP_VEXT1:
5686   case OP_VEXT2:
5687   case OP_VEXT3:
5688     return DAG.getNode(ARMISD::VEXT, dl, VT,
5689                        OpLHS, OpRHS,
5690                        DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
5691   case OP_VUZPL:
5692   case OP_VUZPR:
5693     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5694                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5695   case OP_VZIPL:
5696   case OP_VZIPR:
5697     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5698                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5699   case OP_VTRNL:
5700   case OP_VTRNR:
5701     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5702                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5703   }
5704 }
5705
5706 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5707                                        ArrayRef<int> ShuffleMask,
5708                                        SelectionDAG &DAG) {
5709   // Check to see if we can use the VTBL instruction.
5710   SDValue V1 = Op.getOperand(0);
5711   SDValue V2 = Op.getOperand(1);
5712   SDLoc DL(Op);
5713
5714   SmallVector<SDValue, 8> VTBLMask;
5715   for (ArrayRef<int>::iterator
5716          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5717     VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
5718
5719   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5720     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5721                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5722
5723   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5724                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5725 }
5726
5727 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5728                                                       SelectionDAG &DAG) {
5729   SDLoc DL(Op);
5730   SDValue OpLHS = Op.getOperand(0);
5731   EVT VT = OpLHS.getValueType();
5732
5733   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5734          "Expect an v8i16/v16i8 type");
5735   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5736   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5737   // extract the first 8 bytes into the top double word and the last 8 bytes
5738   // into the bottom double word. The v8i16 case is similar.
5739   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5740   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5741                      DAG.getConstant(ExtractNum, DL, MVT::i32));
5742 }
5743
5744 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5745   SDValue V1 = Op.getOperand(0);
5746   SDValue V2 = Op.getOperand(1);
5747   SDLoc dl(Op);
5748   EVT VT = Op.getValueType();
5749   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5750
5751   // Convert shuffles that are directly supported on NEON to target-specific
5752   // DAG nodes, instead of keeping them as shuffles and matching them again
5753   // during code selection.  This is more efficient and avoids the possibility
5754   // of inconsistencies between legalization and selection.
5755   // FIXME: floating-point vectors should be canonicalized to integer vectors
5756   // of the same time so that they get CSEd properly.
5757   ArrayRef<int> ShuffleMask = SVN->getMask();
5758
5759   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5760   if (EltSize <= 32) {
5761     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5762       int Lane = SVN->getSplatIndex();
5763       // If this is undef splat, generate it via "just" vdup, if possible.
5764       if (Lane == -1) Lane = 0;
5765
5766       // Test if V1 is a SCALAR_TO_VECTOR.
5767       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5768         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5769       }
5770       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5771       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5772       // reaches it).
5773       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5774           !isa<ConstantSDNode>(V1.getOperand(0))) {
5775         bool IsScalarToVector = true;
5776         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5777           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5778             IsScalarToVector = false;
5779             break;
5780           }
5781         if (IsScalarToVector)
5782           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5783       }
5784       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5785                          DAG.getConstant(Lane, dl, MVT::i32));
5786     }
5787
5788     bool ReverseVEXT;
5789     unsigned Imm;
5790     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5791       if (ReverseVEXT)
5792         std::swap(V1, V2);
5793       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5794                          DAG.getConstant(Imm, dl, MVT::i32));
5795     }
5796
5797     if (isVREVMask(ShuffleMask, VT, 64))
5798       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5799     if (isVREVMask(ShuffleMask, VT, 32))
5800       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5801     if (isVREVMask(ShuffleMask, VT, 16))
5802       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5803
5804     if (V2->getOpcode() == ISD::UNDEF &&
5805         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5806       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5807                          DAG.getConstant(Imm, dl, MVT::i32));
5808     }
5809
5810     // Check for Neon shuffles that modify both input vectors in place.
5811     // If both results are used, i.e., if there are two shuffles with the same
5812     // source operands and with masks corresponding to both results of one of
5813     // these operations, DAG memoization will ensure that a single node is
5814     // used for both shuffles.
5815     unsigned WhichResult;
5816     bool isV_UNDEF;
5817     if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
5818             ShuffleMask, VT, WhichResult, isV_UNDEF)) {
5819       if (isV_UNDEF)
5820         V2 = V1;
5821       return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
5822           .getValue(WhichResult);
5823     }
5824
5825     // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
5826     // shuffles that produce a result larger than their operands with:
5827     //   shuffle(concat(v1, undef), concat(v2, undef))
5828     // ->
5829     //   shuffle(concat(v1, v2), undef)
5830     // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
5831     //
5832     // This is useful in the general case, but there are special cases where
5833     // native shuffles produce larger results: the two-result ops.
5834     //
5835     // Look through the concat when lowering them:
5836     //   shuffle(concat(v1, v2), undef)
5837     // ->
5838     //   concat(VZIP(v1, v2):0, :1)
5839     //
5840     if (V1->getOpcode() == ISD::CONCAT_VECTORS &&
5841         V2->getOpcode() == ISD::UNDEF) {
5842       SDValue SubV1 = V1->getOperand(0);
5843       SDValue SubV2 = V1->getOperand(1);
5844       EVT SubVT = SubV1.getValueType();
5845
5846       // We expect these to have been canonicalized to -1.
5847       assert(std::all_of(ShuffleMask.begin(), ShuffleMask.end(), [&](int i) {
5848         return i < (int)VT.getVectorNumElements();
5849       }) && "Unexpected shuffle index into UNDEF operand!");
5850
5851       if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
5852               ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
5853         if (isV_UNDEF)
5854           SubV2 = SubV1;
5855         assert((WhichResult == 0) &&
5856                "In-place shuffle of concat can only have one result!");
5857         SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
5858                                   SubV1, SubV2);
5859         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
5860                            Res.getValue(1));
5861       }
5862     }
5863   }
5864
5865   // If the shuffle is not directly supported and it has 4 elements, use
5866   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5867   unsigned NumElts = VT.getVectorNumElements();
5868   if (NumElts == 4) {
5869     unsigned PFIndexes[4];
5870     for (unsigned i = 0; i != 4; ++i) {
5871       if (ShuffleMask[i] < 0)
5872         PFIndexes[i] = 8;
5873       else
5874         PFIndexes[i] = ShuffleMask[i];
5875     }
5876
5877     // Compute the index in the perfect shuffle table.
5878     unsigned PFTableIndex =
5879       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5880     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5881     unsigned Cost = (PFEntry >> 30);
5882
5883     if (Cost <= 4)
5884       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5885   }
5886
5887   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5888   if (EltSize >= 32) {
5889     // Do the expansion with floating-point types, since that is what the VFP
5890     // registers are defined to use, and since i64 is not legal.
5891     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5892     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5893     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5894     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5895     SmallVector<SDValue, 8> Ops;
5896     for (unsigned i = 0; i < NumElts; ++i) {
5897       if (ShuffleMask[i] < 0)
5898         Ops.push_back(DAG.getUNDEF(EltVT));
5899       else
5900         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5901                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
5902                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5903                                                   dl, MVT::i32)));
5904     }
5905     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5906     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5907   }
5908
5909   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5910     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5911
5912   if (VT == MVT::v8i8) {
5913     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5914     if (NewOp.getNode())
5915       return NewOp;
5916   }
5917
5918   return SDValue();
5919 }
5920
5921 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5922   // INSERT_VECTOR_ELT is legal only for immediate indexes.
5923   SDValue Lane = Op.getOperand(2);
5924   if (!isa<ConstantSDNode>(Lane))
5925     return SDValue();
5926
5927   return Op;
5928 }
5929
5930 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5931   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5932   SDValue Lane = Op.getOperand(1);
5933   if (!isa<ConstantSDNode>(Lane))
5934     return SDValue();
5935
5936   SDValue Vec = Op.getOperand(0);
5937   if (Op.getValueType() == MVT::i32 &&
5938       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5939     SDLoc dl(Op);
5940     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5941   }
5942
5943   return Op;
5944 }
5945
5946 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5947   // The only time a CONCAT_VECTORS operation can have legal types is when
5948   // two 64-bit vectors are concatenated to a 128-bit vector.
5949   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5950          "unexpected CONCAT_VECTORS");
5951   SDLoc dl(Op);
5952   SDValue Val = DAG.getUNDEF(MVT::v2f64);
5953   SDValue Op0 = Op.getOperand(0);
5954   SDValue Op1 = Op.getOperand(1);
5955   if (Op0.getOpcode() != ISD::UNDEF)
5956     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5957                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5958                       DAG.getIntPtrConstant(0, dl));
5959   if (Op1.getOpcode() != ISD::UNDEF)
5960     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5961                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5962                       DAG.getIntPtrConstant(1, dl));
5963   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5964 }
5965
5966 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5967 /// element has been zero/sign-extended, depending on the isSigned parameter,
5968 /// from an integer type half its size.
5969 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5970                                    bool isSigned) {
5971   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5972   EVT VT = N->getValueType(0);
5973   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5974     SDNode *BVN = N->getOperand(0).getNode();
5975     if (BVN->getValueType(0) != MVT::v4i32 ||
5976         BVN->getOpcode() != ISD::BUILD_VECTOR)
5977       return false;
5978     unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
5979     unsigned HiElt = 1 - LoElt;
5980     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5981     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5982     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5983     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5984     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5985       return false;
5986     if (isSigned) {
5987       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5988           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5989         return true;
5990     } else {
5991       if (Hi0->isNullValue() && Hi1->isNullValue())
5992         return true;
5993     }
5994     return false;
5995   }
5996
5997   if (N->getOpcode() != ISD::BUILD_VECTOR)
5998     return false;
5999
6000   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
6001     SDNode *Elt = N->getOperand(i).getNode();
6002     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
6003       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6004       unsigned HalfSize = EltSize / 2;
6005       if (isSigned) {
6006         if (!isIntN(HalfSize, C->getSExtValue()))
6007           return false;
6008       } else {
6009         if (!isUIntN(HalfSize, C->getZExtValue()))
6010           return false;
6011       }
6012       continue;
6013     }
6014     return false;
6015   }
6016
6017   return true;
6018 }
6019
6020 /// isSignExtended - Check if a node is a vector value that is sign-extended
6021 /// or a constant BUILD_VECTOR with sign-extended elements.
6022 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
6023   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
6024     return true;
6025   if (isExtendedBUILD_VECTOR(N, DAG, true))
6026     return true;
6027   return false;
6028 }
6029
6030 /// isZeroExtended - Check if a node is a vector value that is zero-extended
6031 /// or a constant BUILD_VECTOR with zero-extended elements.
6032 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
6033   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
6034     return true;
6035   if (isExtendedBUILD_VECTOR(N, DAG, false))
6036     return true;
6037   return false;
6038 }
6039
6040 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
6041   if (OrigVT.getSizeInBits() >= 64)
6042     return OrigVT;
6043
6044   assert(OrigVT.isSimple() && "Expecting a simple value type");
6045
6046   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
6047   switch (OrigSimpleTy) {
6048   default: llvm_unreachable("Unexpected Vector Type");
6049   case MVT::v2i8:
6050   case MVT::v2i16:
6051      return MVT::v2i32;
6052   case MVT::v4i8:
6053     return  MVT::v4i16;
6054   }
6055 }
6056
6057 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
6058 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
6059 /// We insert the required extension here to get the vector to fill a D register.
6060 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
6061                                             const EVT &OrigTy,
6062                                             const EVT &ExtTy,
6063                                             unsigned ExtOpcode) {
6064   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
6065   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
6066   // 64-bits we need to insert a new extension so that it will be 64-bits.
6067   assert(ExtTy.is128BitVector() && "Unexpected extension size");
6068   if (OrigTy.getSizeInBits() >= 64)
6069     return N;
6070
6071   // Must extend size to at least 64 bits to be used as an operand for VMULL.
6072   EVT NewVT = getExtensionTo64Bits(OrigTy);
6073
6074   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
6075 }
6076
6077 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
6078 /// does not do any sign/zero extension. If the original vector is less
6079 /// than 64 bits, an appropriate extension will be added after the load to
6080 /// reach a total size of 64 bits. We have to add the extension separately
6081 /// because ARM does not have a sign/zero extending load for vectors.
6082 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
6083   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
6084
6085   // The load already has the right type.
6086   if (ExtendedTy == LD->getMemoryVT())
6087     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
6088                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
6089                 LD->isNonTemporal(), LD->isInvariant(),
6090                 LD->getAlignment());
6091
6092   // We need to create a zextload/sextload. We cannot just create a load
6093   // followed by a zext/zext node because LowerMUL is also run during normal
6094   // operation legalization where we can't create illegal types.
6095   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
6096                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
6097                         LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
6098                         LD->isNonTemporal(), LD->getAlignment());
6099 }
6100
6101 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
6102 /// extending load, or BUILD_VECTOR with extended elements, return the
6103 /// unextended value. The unextended vector should be 64 bits so that it can
6104 /// be used as an operand to a VMULL instruction. If the original vector size
6105 /// before extension is less than 64 bits we add a an extension to resize
6106 /// the vector to 64 bits.
6107 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
6108   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
6109     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
6110                                         N->getOperand(0)->getValueType(0),
6111                                         N->getValueType(0),
6112                                         N->getOpcode());
6113
6114   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
6115     return SkipLoadExtensionForVMULL(LD, DAG);
6116
6117   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
6118   // have been legalized as a BITCAST from v4i32.
6119   if (N->getOpcode() == ISD::BITCAST) {
6120     SDNode *BVN = N->getOperand(0).getNode();
6121     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
6122            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
6123     unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6124     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
6125                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
6126   }
6127   // Construct a new BUILD_VECTOR with elements truncated to half the size.
6128   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
6129   EVT VT = N->getValueType(0);
6130   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
6131   unsigned NumElts = VT.getVectorNumElements();
6132   MVT TruncVT = MVT::getIntegerVT(EltSize);
6133   SmallVector<SDValue, 8> Ops;
6134   SDLoc dl(N);
6135   for (unsigned i = 0; i != NumElts; ++i) {
6136     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
6137     const APInt &CInt = C->getAPIntValue();
6138     // Element types smaller than 32 bits are not legal, so use i32 elements.
6139     // The values are implicitly truncated so sext vs. zext doesn't matter.
6140     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
6141   }
6142   return DAG.getNode(ISD::BUILD_VECTOR, dl,
6143                      MVT::getVectorVT(TruncVT, NumElts), Ops);
6144 }
6145
6146 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
6147   unsigned Opcode = N->getOpcode();
6148   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6149     SDNode *N0 = N->getOperand(0).getNode();
6150     SDNode *N1 = N->getOperand(1).getNode();
6151     return N0->hasOneUse() && N1->hasOneUse() &&
6152       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
6153   }
6154   return false;
6155 }
6156
6157 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
6158   unsigned Opcode = N->getOpcode();
6159   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6160     SDNode *N0 = N->getOperand(0).getNode();
6161     SDNode *N1 = N->getOperand(1).getNode();
6162     return N0->hasOneUse() && N1->hasOneUse() &&
6163       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
6164   }
6165   return false;
6166 }
6167
6168 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
6169   // Multiplications are only custom-lowered for 128-bit vectors so that
6170   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
6171   EVT VT = Op.getValueType();
6172   assert(VT.is128BitVector() && VT.isInteger() &&
6173          "unexpected type for custom-lowering ISD::MUL");
6174   SDNode *N0 = Op.getOperand(0).getNode();
6175   SDNode *N1 = Op.getOperand(1).getNode();
6176   unsigned NewOpc = 0;
6177   bool isMLA = false;
6178   bool isN0SExt = isSignExtended(N0, DAG);
6179   bool isN1SExt = isSignExtended(N1, DAG);
6180   if (isN0SExt && isN1SExt)
6181     NewOpc = ARMISD::VMULLs;
6182   else {
6183     bool isN0ZExt = isZeroExtended(N0, DAG);
6184     bool isN1ZExt = isZeroExtended(N1, DAG);
6185     if (isN0ZExt && isN1ZExt)
6186       NewOpc = ARMISD::VMULLu;
6187     else if (isN1SExt || isN1ZExt) {
6188       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
6189       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
6190       if (isN1SExt && isAddSubSExt(N0, DAG)) {
6191         NewOpc = ARMISD::VMULLs;
6192         isMLA = true;
6193       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
6194         NewOpc = ARMISD::VMULLu;
6195         isMLA = true;
6196       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
6197         std::swap(N0, N1);
6198         NewOpc = ARMISD::VMULLu;
6199         isMLA = true;
6200       }
6201     }
6202
6203     if (!NewOpc) {
6204       if (VT == MVT::v2i64)
6205         // Fall through to expand this.  It is not legal.
6206         return SDValue();
6207       else
6208         // Other vector multiplications are legal.
6209         return Op;
6210     }
6211   }
6212
6213   // Legalize to a VMULL instruction.
6214   SDLoc DL(Op);
6215   SDValue Op0;
6216   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
6217   if (!isMLA) {
6218     Op0 = SkipExtensionForVMULL(N0, DAG);
6219     assert(Op0.getValueType().is64BitVector() &&
6220            Op1.getValueType().is64BitVector() &&
6221            "unexpected types for extended operands to VMULL");
6222     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
6223   }
6224
6225   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
6226   // isel lowering to take advantage of no-stall back to back vmul + vmla.
6227   //   vmull q0, d4, d6
6228   //   vmlal q0, d5, d6
6229   // is faster than
6230   //   vaddl q0, d4, d5
6231   //   vmovl q1, d6
6232   //   vmul  q0, q0, q1
6233   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
6234   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
6235   EVT Op1VT = Op1.getValueType();
6236   return DAG.getNode(N0->getOpcode(), DL, VT,
6237                      DAG.getNode(NewOpc, DL, VT,
6238                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
6239                      DAG.getNode(NewOpc, DL, VT,
6240                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
6241 }
6242
6243 static SDValue
6244 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
6245   // Convert to float
6246   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
6247   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
6248   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
6249   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
6250   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
6251   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
6252   // Get reciprocal estimate.
6253   // float4 recip = vrecpeq_f32(yf);
6254   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6255                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6256                    Y);
6257   // Because char has a smaller range than uchar, we can actually get away
6258   // without any newton steps.  This requires that we use a weird bias
6259   // of 0xb000, however (again, this has been exhaustively tested).
6260   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
6261   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
6262   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
6263   Y = DAG.getConstant(0xb000, dl, MVT::i32);
6264   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
6265   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6266   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6267   // Convert back to short.
6268   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6269   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6270   return X;
6271 }
6272
6273 static SDValue
6274 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
6275   SDValue N2;
6276   // Convert to float.
6277   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6278   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6279   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6280   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6281   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6282   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6283
6284   // Use reciprocal estimate and one refinement step.
6285   // float4 recip = vrecpeq_f32(yf);
6286   // recip *= vrecpsq_f32(yf, recip);
6287   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6288                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6289                    N1);
6290   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6291                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6292                    N1, N2);
6293   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6294   // Because short has a smaller range than ushort, we can actually get away
6295   // with only a single newton step.  This requires that we use a weird bias
6296   // of 89, however (again, this has been exhaustively tested).
6297   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6298   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6299   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6300   N1 = DAG.getConstant(0x89, dl, MVT::i32);
6301   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6302   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6303   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6304   // Convert back to integer and return.
6305   // return vmovn_s32(vcvt_s32_f32(result));
6306   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6307   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6308   return N0;
6309 }
6310
6311 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6312   EVT VT = Op.getValueType();
6313   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6314          "unexpected type for custom-lowering ISD::SDIV");
6315
6316   SDLoc dl(Op);
6317   SDValue N0 = Op.getOperand(0);
6318   SDValue N1 = Op.getOperand(1);
6319   SDValue N2, N3;
6320
6321   if (VT == MVT::v8i8) {
6322     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6323     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6324
6325     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6326                      DAG.getIntPtrConstant(4, dl));
6327     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6328                      DAG.getIntPtrConstant(4, dl));
6329     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6330                      DAG.getIntPtrConstant(0, dl));
6331     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6332                      DAG.getIntPtrConstant(0, dl));
6333
6334     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6335     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6336
6337     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6338     N0 = LowerCONCAT_VECTORS(N0, DAG);
6339
6340     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6341     return N0;
6342   }
6343   return LowerSDIV_v4i16(N0, N1, dl, DAG);
6344 }
6345
6346 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6347   EVT VT = Op.getValueType();
6348   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6349          "unexpected type for custom-lowering ISD::UDIV");
6350
6351   SDLoc dl(Op);
6352   SDValue N0 = Op.getOperand(0);
6353   SDValue N1 = Op.getOperand(1);
6354   SDValue N2, N3;
6355
6356   if (VT == MVT::v8i8) {
6357     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6358     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6359
6360     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6361                      DAG.getIntPtrConstant(4, dl));
6362     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6363                      DAG.getIntPtrConstant(4, dl));
6364     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6365                      DAG.getIntPtrConstant(0, dl));
6366     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6367                      DAG.getIntPtrConstant(0, dl));
6368
6369     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6370     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6371
6372     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6373     N0 = LowerCONCAT_VECTORS(N0, DAG);
6374
6375     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6376                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
6377                                      MVT::i32),
6378                      N0);
6379     return N0;
6380   }
6381
6382   // v4i16 sdiv ... Convert to float.
6383   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6384   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6385   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6386   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6387   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6388   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6389
6390   // Use reciprocal estimate and two refinement steps.
6391   // float4 recip = vrecpeq_f32(yf);
6392   // recip *= vrecpsq_f32(yf, recip);
6393   // recip *= vrecpsq_f32(yf, recip);
6394   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6395                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6396                    BN1);
6397   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6398                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6399                    BN1, N2);
6400   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6401   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6402                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6403                    BN1, N2);
6404   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6405   // Simply multiplying by the reciprocal estimate can leave us a few ulps
6406   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6407   // and that it will never cause us to return an answer too large).
6408   // float4 result = as_float4(as_int4(xf*recip) + 2);
6409   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6410   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6411   N1 = DAG.getConstant(2, dl, MVT::i32);
6412   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6413   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6414   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6415   // Convert back to integer and return.
6416   // return vmovn_u32(vcvt_s32_f32(result));
6417   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6418   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6419   return N0;
6420 }
6421
6422 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6423   EVT VT = Op.getNode()->getValueType(0);
6424   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6425
6426   unsigned Opc;
6427   bool ExtraOp = false;
6428   switch (Op.getOpcode()) {
6429   default: llvm_unreachable("Invalid code");
6430   case ISD::ADDC: Opc = ARMISD::ADDC; break;
6431   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6432   case ISD::SUBC: Opc = ARMISD::SUBC; break;
6433   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6434   }
6435
6436   if (!ExtraOp)
6437     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6438                        Op.getOperand(1));
6439   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6440                      Op.getOperand(1), Op.getOperand(2));
6441 }
6442
6443 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6444   assert(Subtarget->isTargetDarwin());
6445
6446   // For iOS, we want to call an alternative entry point: __sincos_stret,
6447   // return values are passed via sret.
6448   SDLoc dl(Op);
6449   SDValue Arg = Op.getOperand(0);
6450   EVT ArgVT = Arg.getValueType();
6451   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6452   auto PtrVT = getPointerTy(DAG.getDataLayout());
6453
6454   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6455
6456   // Pair of floats / doubles used to pass the result.
6457   StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
6458
6459   // Create stack object for sret.
6460   auto &DL = DAG.getDataLayout();
6461   const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
6462   const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
6463   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6464   SDValue SRet = DAG.getFrameIndex(FrameIdx, getPointerTy(DL));
6465
6466   ArgListTy Args;
6467   ArgListEntry Entry;
6468
6469   Entry.Node = SRet;
6470   Entry.Ty = RetTy->getPointerTo();
6471   Entry.isSExt = false;
6472   Entry.isZExt = false;
6473   Entry.isSRet = true;
6474   Args.push_back(Entry);
6475
6476   Entry.Node = Arg;
6477   Entry.Ty = ArgTy;
6478   Entry.isSExt = false;
6479   Entry.isZExt = false;
6480   Args.push_back(Entry);
6481
6482   const char *LibcallName  = (ArgVT == MVT::f64)
6483   ? "__sincos_stret" : "__sincosf_stret";
6484   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
6485
6486   TargetLowering::CallLoweringInfo CLI(DAG);
6487   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6488     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6489                std::move(Args), 0)
6490     .setDiscardResult();
6491
6492   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6493
6494   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6495                                 MachinePointerInfo(), false, false, false, 0);
6496
6497   // Address of cos field.
6498   SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
6499                             DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
6500   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6501                                 MachinePointerInfo(), false, false, false, 0);
6502
6503   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6504   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6505                      LoadSin.getValue(0), LoadCos.getValue(0));
6506 }
6507
6508 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6509   // Monotonic load/store is legal for all targets
6510   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6511     return Op;
6512
6513   // Acquire/Release load/store is not legal for targets without a
6514   // dmb or equivalent available.
6515   return SDValue();
6516 }
6517
6518 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6519                                     SmallVectorImpl<SDValue> &Results,
6520                                     SelectionDAG &DAG,
6521                                     const ARMSubtarget *Subtarget) {
6522   SDLoc DL(N);
6523   SDValue Cycles32, OutChain;
6524
6525   if (Subtarget->hasPerfMon()) {
6526     // Under Power Management extensions, the cycle-count is:
6527     //    mrc p15, #0, <Rt>, c9, c13, #0
6528     SDValue Ops[] = { N->getOperand(0), // Chain
6529                       DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
6530                       DAG.getConstant(15, DL, MVT::i32),
6531                       DAG.getConstant(0, DL, MVT::i32),
6532                       DAG.getConstant(9, DL, MVT::i32),
6533                       DAG.getConstant(13, DL, MVT::i32),
6534                       DAG.getConstant(0, DL, MVT::i32)
6535     };
6536
6537     Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6538                            DAG.getVTList(MVT::i32, MVT::Other), Ops);
6539     OutChain = Cycles32.getValue(1);
6540   } else {
6541     // Intrinsic is defined to return 0 on unsupported platforms. Technically
6542     // there are older ARM CPUs that have implementation-specific ways of
6543     // obtaining this information (FIXME!).
6544     Cycles32 = DAG.getConstant(0, DL, MVT::i32);
6545     OutChain = DAG.getEntryNode();
6546   }
6547
6548
6549   SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6550                                  Cycles32, DAG.getConstant(0, DL, MVT::i32));
6551   Results.push_back(Cycles64);
6552   Results.push_back(OutChain);
6553 }
6554
6555 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6556   switch (Op.getOpcode()) {
6557   default: llvm_unreachable("Don't know how to custom lower this!");
6558   case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
6559   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6560   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6561   case ISD::GlobalAddress:
6562     switch (Subtarget->getTargetTriple().getObjectFormat()) {
6563     default: llvm_unreachable("unknown object format");
6564     case Triple::COFF:
6565       return LowerGlobalAddressWindows(Op, DAG);
6566     case Triple::ELF:
6567       return LowerGlobalAddressELF(Op, DAG);
6568     case Triple::MachO:
6569       return LowerGlobalAddressDarwin(Op, DAG);
6570     }
6571   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6572   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6573   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6574   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6575   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6576   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6577   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6578   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6579   case ISD::SINT_TO_FP:
6580   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6581   case ISD::FP_TO_SINT:
6582   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6583   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6584   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6585   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6586   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6587   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6588   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6589   case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
6590   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6591                                                                Subtarget);
6592   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6593   case ISD::SHL:
6594   case ISD::SRL:
6595   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6596   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6597   case ISD::SRL_PARTS:
6598   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6599   case ISD::CTTZ:
6600   case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6601   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6602   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6603   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6604   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6605   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6606   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6607   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6608   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6609   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6610   case ISD::MUL:           return LowerMUL(Op, DAG);
6611   case ISD::SDIV:          return LowerSDIV(Op, DAG);
6612   case ISD::UDIV:          return LowerUDIV(Op, DAG);
6613   case ISD::ADDC:
6614   case ISD::ADDE:
6615   case ISD::SUBC:
6616   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6617   case ISD::SADDO:
6618   case ISD::UADDO:
6619   case ISD::SSUBO:
6620   case ISD::USUBO:
6621     return LowerXALUO(Op, DAG);
6622   case ISD::ATOMIC_LOAD:
6623   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6624   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6625   case ISD::SDIVREM:
6626   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6627   case ISD::DYNAMIC_STACKALLOC:
6628     if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6629       return LowerDYNAMIC_STACKALLOC(Op, DAG);
6630     llvm_unreachable("Don't know how to custom lower this!");
6631   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6632   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6633   }
6634 }
6635
6636 /// ReplaceNodeResults - Replace the results of node with an illegal result
6637 /// type with new values built out of custom code.
6638 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6639                                            SmallVectorImpl<SDValue>&Results,
6640                                            SelectionDAG &DAG) const {
6641   SDValue Res;
6642   switch (N->getOpcode()) {
6643   default:
6644     llvm_unreachable("Don't know how to custom expand this!");
6645   case ISD::READ_REGISTER:
6646     ExpandREAD_REGISTER(N, Results, DAG);
6647     break;
6648   case ISD::BITCAST:
6649     Res = ExpandBITCAST(N, DAG);
6650     break;
6651   case ISD::SRL:
6652   case ISD::SRA:
6653     Res = Expand64BitShift(N, DAG, Subtarget);
6654     break;
6655   case ISD::READCYCLECOUNTER:
6656     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6657     return;
6658   }
6659   if (Res.getNode())
6660     Results.push_back(Res);
6661 }
6662
6663 //===----------------------------------------------------------------------===//
6664 //                           ARM Scheduler Hooks
6665 //===----------------------------------------------------------------------===//
6666
6667 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6668 /// registers the function context.
6669 void ARMTargetLowering::
6670 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6671                        MachineBasicBlock *DispatchBB, int FI) const {
6672   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6673   DebugLoc dl = MI->getDebugLoc();
6674   MachineFunction *MF = MBB->getParent();
6675   MachineRegisterInfo *MRI = &MF->getRegInfo();
6676   MachineConstantPool *MCP = MF->getConstantPool();
6677   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6678   const Function *F = MF->getFunction();
6679
6680   bool isThumb = Subtarget->isThumb();
6681   bool isThumb2 = Subtarget->isThumb2();
6682
6683   unsigned PCLabelId = AFI->createPICLabelUId();
6684   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6685   ARMConstantPoolValue *CPV =
6686     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6687   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6688
6689   const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
6690                                            : &ARM::GPRRegClass;
6691
6692   // Grab constant pool and fixed stack memory operands.
6693   MachineMemOperand *CPMMO =
6694     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6695                              MachineMemOperand::MOLoad, 4, 4);
6696
6697   MachineMemOperand *FIMMOSt =
6698     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6699                              MachineMemOperand::MOStore, 4, 4);
6700
6701   // Load the address of the dispatch MBB into the jump buffer.
6702   if (isThumb2) {
6703     // Incoming value: jbuf
6704     //   ldr.n  r5, LCPI1_1
6705     //   orr    r5, r5, #1
6706     //   add    r5, pc
6707     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6708     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6709     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6710                    .addConstantPoolIndex(CPI)
6711                    .addMemOperand(CPMMO));
6712     // Set the low bit because of thumb mode.
6713     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6714     AddDefaultCC(
6715       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6716                      .addReg(NewVReg1, RegState::Kill)
6717                      .addImm(0x01)));
6718     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6719     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6720       .addReg(NewVReg2, RegState::Kill)
6721       .addImm(PCLabelId);
6722     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6723                    .addReg(NewVReg3, RegState::Kill)
6724                    .addFrameIndex(FI)
6725                    .addImm(36)  // &jbuf[1] :: pc
6726                    .addMemOperand(FIMMOSt));
6727   } else if (isThumb) {
6728     // Incoming value: jbuf
6729     //   ldr.n  r1, LCPI1_4
6730     //   add    r1, pc
6731     //   mov    r2, #1
6732     //   orrs   r1, r2
6733     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6734     //   str    r1, [r2]
6735     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6736     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6737                    .addConstantPoolIndex(CPI)
6738                    .addMemOperand(CPMMO));
6739     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6740     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6741       .addReg(NewVReg1, RegState::Kill)
6742       .addImm(PCLabelId);
6743     // Set the low bit because of thumb mode.
6744     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6745     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6746                    .addReg(ARM::CPSR, RegState::Define)
6747                    .addImm(1));
6748     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6749     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6750                    .addReg(ARM::CPSR, RegState::Define)
6751                    .addReg(NewVReg2, RegState::Kill)
6752                    .addReg(NewVReg3, RegState::Kill));
6753     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6754     BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
6755             .addFrameIndex(FI)
6756             .addImm(36); // &jbuf[1] :: pc
6757     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6758                    .addReg(NewVReg4, RegState::Kill)
6759                    .addReg(NewVReg5, RegState::Kill)
6760                    .addImm(0)
6761                    .addMemOperand(FIMMOSt));
6762   } else {
6763     // Incoming value: jbuf
6764     //   ldr  r1, LCPI1_1
6765     //   add  r1, pc, r1
6766     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6767     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6768     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6769                    .addConstantPoolIndex(CPI)
6770                    .addImm(0)
6771                    .addMemOperand(CPMMO));
6772     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6773     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6774                    .addReg(NewVReg1, RegState::Kill)
6775                    .addImm(PCLabelId));
6776     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6777                    .addReg(NewVReg2, RegState::Kill)
6778                    .addFrameIndex(FI)
6779                    .addImm(36)  // &jbuf[1] :: pc
6780                    .addMemOperand(FIMMOSt));
6781   }
6782 }
6783
6784 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr *MI,
6785                                               MachineBasicBlock *MBB) const {
6786   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6787   DebugLoc dl = MI->getDebugLoc();
6788   MachineFunction *MF = MBB->getParent();
6789   MachineRegisterInfo *MRI = &MF->getRegInfo();
6790   MachineFrameInfo *MFI = MF->getFrameInfo();
6791   int FI = MFI->getFunctionContextIndex();
6792
6793   const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
6794                                                         : &ARM::GPRnopcRegClass;
6795
6796   // Get a mapping of the call site numbers to all of the landing pads they're
6797   // associated with.
6798   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6799   unsigned MaxCSNum = 0;
6800   MachineModuleInfo &MMI = MF->getMMI();
6801   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6802        ++BB) {
6803     if (!BB->isLandingPad()) continue;
6804
6805     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6806     // pad.
6807     for (MachineBasicBlock::iterator
6808            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6809       if (!II->isEHLabel()) continue;
6810
6811       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6812       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6813
6814       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6815       for (SmallVectorImpl<unsigned>::iterator
6816              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6817            CSI != CSE; ++CSI) {
6818         CallSiteNumToLPad[*CSI].push_back(BB);
6819         MaxCSNum = std::max(MaxCSNum, *CSI);
6820       }
6821       break;
6822     }
6823   }
6824
6825   // Get an ordered list of the machine basic blocks for the jump table.
6826   std::vector<MachineBasicBlock*> LPadList;
6827   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6828   LPadList.reserve(CallSiteNumToLPad.size());
6829   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6830     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6831     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6832            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6833       LPadList.push_back(*II);
6834       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6835     }
6836   }
6837
6838   assert(!LPadList.empty() &&
6839          "No landing pad destinations for the dispatch jump table!");
6840
6841   // Create the jump table and associated information.
6842   MachineJumpTableInfo *JTI =
6843     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6844   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6845   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6846
6847   // Create the MBBs for the dispatch code.
6848
6849   // Shove the dispatch's address into the return slot in the function context.
6850   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6851   DispatchBB->setIsLandingPad();
6852
6853   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6854   unsigned trap_opcode;
6855   if (Subtarget->isThumb())
6856     trap_opcode = ARM::tTRAP;
6857   else
6858     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6859
6860   BuildMI(TrapBB, dl, TII->get(trap_opcode));
6861   DispatchBB->addSuccessor(TrapBB);
6862
6863   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6864   DispatchBB->addSuccessor(DispContBB);
6865
6866   // Insert and MBBs.
6867   MF->insert(MF->end(), DispatchBB);
6868   MF->insert(MF->end(), DispContBB);
6869   MF->insert(MF->end(), TrapBB);
6870
6871   // Insert code into the entry block that creates and registers the function
6872   // context.
6873   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6874
6875   MachineMemOperand *FIMMOLd =
6876     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6877                              MachineMemOperand::MOLoad |
6878                              MachineMemOperand::MOVolatile, 4, 4);
6879
6880   MachineInstrBuilder MIB;
6881   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6882
6883   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6884   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6885
6886   // Add a register mask with no preserved registers.  This results in all
6887   // registers being marked as clobbered.
6888   MIB.addRegMask(RI.getNoPreservedMask());
6889
6890   unsigned NumLPads = LPadList.size();
6891   if (Subtarget->isThumb2()) {
6892     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6893     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6894                    .addFrameIndex(FI)
6895                    .addImm(4)
6896                    .addMemOperand(FIMMOLd));
6897
6898     if (NumLPads < 256) {
6899       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6900                      .addReg(NewVReg1)
6901                      .addImm(LPadList.size()));
6902     } else {
6903       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6904       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6905                      .addImm(NumLPads & 0xFFFF));
6906
6907       unsigned VReg2 = VReg1;
6908       if ((NumLPads & 0xFFFF0000) != 0) {
6909         VReg2 = MRI->createVirtualRegister(TRC);
6910         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6911                        .addReg(VReg1)
6912                        .addImm(NumLPads >> 16));
6913       }
6914
6915       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6916                      .addReg(NewVReg1)
6917                      .addReg(VReg2));
6918     }
6919
6920     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6921       .addMBB(TrapBB)
6922       .addImm(ARMCC::HI)
6923       .addReg(ARM::CPSR);
6924
6925     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6926     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6927                    .addJumpTableIndex(MJTI));
6928
6929     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6930     AddDefaultCC(
6931       AddDefaultPred(
6932         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6933         .addReg(NewVReg3, RegState::Kill)
6934         .addReg(NewVReg1)
6935         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6936
6937     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6938       .addReg(NewVReg4, RegState::Kill)
6939       .addReg(NewVReg1)
6940       .addJumpTableIndex(MJTI);
6941   } else if (Subtarget->isThumb()) {
6942     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6943     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6944                    .addFrameIndex(FI)
6945                    .addImm(1)
6946                    .addMemOperand(FIMMOLd));
6947
6948     if (NumLPads < 256) {
6949       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6950                      .addReg(NewVReg1)
6951                      .addImm(NumLPads));
6952     } else {
6953       MachineConstantPool *ConstantPool = MF->getConstantPool();
6954       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6955       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6956
6957       // MachineConstantPool wants an explicit alignment.
6958       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
6959       if (Align == 0)
6960         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
6961       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6962
6963       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6964       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6965                      .addReg(VReg1, RegState::Define)
6966                      .addConstantPoolIndex(Idx));
6967       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6968                      .addReg(NewVReg1)
6969                      .addReg(VReg1));
6970     }
6971
6972     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6973       .addMBB(TrapBB)
6974       .addImm(ARMCC::HI)
6975       .addReg(ARM::CPSR);
6976
6977     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6978     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6979                    .addReg(ARM::CPSR, RegState::Define)
6980                    .addReg(NewVReg1)
6981                    .addImm(2));
6982
6983     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6984     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6985                    .addJumpTableIndex(MJTI));
6986
6987     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6988     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6989                    .addReg(ARM::CPSR, RegState::Define)
6990                    .addReg(NewVReg2, RegState::Kill)
6991                    .addReg(NewVReg3));
6992
6993     MachineMemOperand *JTMMOLd =
6994       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6995                                MachineMemOperand::MOLoad, 4, 4);
6996
6997     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6998     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6999                    .addReg(NewVReg4, RegState::Kill)
7000                    .addImm(0)
7001                    .addMemOperand(JTMMOLd));
7002
7003     unsigned NewVReg6 = NewVReg5;
7004     if (RelocM == Reloc::PIC_) {
7005       NewVReg6 = MRI->createVirtualRegister(TRC);
7006       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
7007                      .addReg(ARM::CPSR, RegState::Define)
7008                      .addReg(NewVReg5, RegState::Kill)
7009                      .addReg(NewVReg3));
7010     }
7011
7012     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
7013       .addReg(NewVReg6, RegState::Kill)
7014       .addJumpTableIndex(MJTI);
7015   } else {
7016     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7017     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
7018                    .addFrameIndex(FI)
7019                    .addImm(4)
7020                    .addMemOperand(FIMMOLd));
7021
7022     if (NumLPads < 256) {
7023       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
7024                      .addReg(NewVReg1)
7025                      .addImm(NumLPads));
7026     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
7027       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7028       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
7029                      .addImm(NumLPads & 0xFFFF));
7030
7031       unsigned VReg2 = VReg1;
7032       if ((NumLPads & 0xFFFF0000) != 0) {
7033         VReg2 = MRI->createVirtualRegister(TRC);
7034         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
7035                        .addReg(VReg1)
7036                        .addImm(NumLPads >> 16));
7037       }
7038
7039       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7040                      .addReg(NewVReg1)
7041                      .addReg(VReg2));
7042     } else {
7043       MachineConstantPool *ConstantPool = MF->getConstantPool();
7044       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7045       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7046
7047       // MachineConstantPool wants an explicit alignment.
7048       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7049       if (Align == 0)
7050         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7051       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7052
7053       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7054       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
7055                      .addReg(VReg1, RegState::Define)
7056                      .addConstantPoolIndex(Idx)
7057                      .addImm(0));
7058       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7059                      .addReg(NewVReg1)
7060                      .addReg(VReg1, RegState::Kill));
7061     }
7062
7063     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
7064       .addMBB(TrapBB)
7065       .addImm(ARMCC::HI)
7066       .addReg(ARM::CPSR);
7067
7068     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7069     AddDefaultCC(
7070       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
7071                      .addReg(NewVReg1)
7072                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7073     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7074     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
7075                    .addJumpTableIndex(MJTI));
7076
7077     MachineMemOperand *JTMMOLd =
7078       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
7079                                MachineMemOperand::MOLoad, 4, 4);
7080     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7081     AddDefaultPred(
7082       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
7083       .addReg(NewVReg3, RegState::Kill)
7084       .addReg(NewVReg4)
7085       .addImm(0)
7086       .addMemOperand(JTMMOLd));
7087
7088     if (RelocM == Reloc::PIC_) {
7089       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
7090         .addReg(NewVReg5, RegState::Kill)
7091         .addReg(NewVReg4)
7092         .addJumpTableIndex(MJTI);
7093     } else {
7094       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
7095         .addReg(NewVReg5, RegState::Kill)
7096         .addJumpTableIndex(MJTI);
7097     }
7098   }
7099
7100   // Add the jump table entries as successors to the MBB.
7101   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
7102   for (std::vector<MachineBasicBlock*>::iterator
7103          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
7104     MachineBasicBlock *CurMBB = *I;
7105     if (SeenMBBs.insert(CurMBB).second)
7106       DispContBB->addSuccessor(CurMBB);
7107   }
7108
7109   // N.B. the order the invoke BBs are processed in doesn't matter here.
7110   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
7111   SmallVector<MachineBasicBlock*, 64> MBBLPads;
7112   for (MachineBasicBlock *BB : InvokeBBs) {
7113
7114     // Remove the landing pad successor from the invoke block and replace it
7115     // with the new dispatch block.
7116     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
7117                                                   BB->succ_end());
7118     while (!Successors.empty()) {
7119       MachineBasicBlock *SMBB = Successors.pop_back_val();
7120       if (SMBB->isLandingPad()) {
7121         BB->removeSuccessor(SMBB);
7122         MBBLPads.push_back(SMBB);
7123       }
7124     }
7125
7126     BB->addSuccessor(DispatchBB);
7127
7128     // Find the invoke call and mark all of the callee-saved registers as
7129     // 'implicit defined' so that they're spilled. This prevents code from
7130     // moving instructions to before the EH block, where they will never be
7131     // executed.
7132     for (MachineBasicBlock::reverse_iterator
7133            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
7134       if (!II->isCall()) continue;
7135
7136       DenseMap<unsigned, bool> DefRegs;
7137       for (MachineInstr::mop_iterator
7138              OI = II->operands_begin(), OE = II->operands_end();
7139            OI != OE; ++OI) {
7140         if (!OI->isReg()) continue;
7141         DefRegs[OI->getReg()] = true;
7142       }
7143
7144       MachineInstrBuilder MIB(*MF, &*II);
7145
7146       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
7147         unsigned Reg = SavedRegs[i];
7148         if (Subtarget->isThumb2() &&
7149             !ARM::tGPRRegClass.contains(Reg) &&
7150             !ARM::hGPRRegClass.contains(Reg))
7151           continue;
7152         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
7153           continue;
7154         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7155           continue;
7156         if (!DefRegs[Reg])
7157           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7158       }
7159
7160       break;
7161     }
7162   }
7163
7164   // Mark all former landing pads as non-landing pads. The dispatch is the only
7165   // landing pad now.
7166   for (SmallVectorImpl<MachineBasicBlock*>::iterator
7167          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7168     (*I)->setIsLandingPad(false);
7169
7170   // The instruction is gone now.
7171   MI->eraseFromParent();
7172 }
7173
7174 static
7175 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7176   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7177        E = MBB->succ_end(); I != E; ++I)
7178     if (*I != Succ)
7179       return *I;
7180   llvm_unreachable("Expecting a BB with two successors!");
7181 }
7182
7183 /// Return the load opcode for a given load size. If load size >= 8,
7184 /// neon opcode will be returned.
7185 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7186   if (LdSize >= 8)
7187     return LdSize == 16 ? ARM::VLD1q32wb_fixed
7188                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7189   if (IsThumb1)
7190     return LdSize == 4 ? ARM::tLDRi
7191                        : LdSize == 2 ? ARM::tLDRHi
7192                                      : LdSize == 1 ? ARM::tLDRBi : 0;
7193   if (IsThumb2)
7194     return LdSize == 4 ? ARM::t2LDR_POST
7195                        : LdSize == 2 ? ARM::t2LDRH_POST
7196                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7197   return LdSize == 4 ? ARM::LDR_POST_IMM
7198                      : LdSize == 2 ? ARM::LDRH_POST
7199                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7200 }
7201
7202 /// Return the store opcode for a given store size. If store size >= 8,
7203 /// neon opcode will be returned.
7204 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7205   if (StSize >= 8)
7206     return StSize == 16 ? ARM::VST1q32wb_fixed
7207                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7208   if (IsThumb1)
7209     return StSize == 4 ? ARM::tSTRi
7210                        : StSize == 2 ? ARM::tSTRHi
7211                                      : StSize == 1 ? ARM::tSTRBi : 0;
7212   if (IsThumb2)
7213     return StSize == 4 ? ARM::t2STR_POST
7214                        : StSize == 2 ? ARM::t2STRH_POST
7215                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
7216   return StSize == 4 ? ARM::STR_POST_IMM
7217                      : StSize == 2 ? ARM::STRH_POST
7218                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7219 }
7220
7221 /// Emit a post-increment load operation with given size. The instructions
7222 /// will be added to BB at Pos.
7223 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7224                        const TargetInstrInfo *TII, DebugLoc dl,
7225                        unsigned LdSize, unsigned Data, unsigned AddrIn,
7226                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7227   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7228   assert(LdOpc != 0 && "Should have a load opcode");
7229   if (LdSize >= 8) {
7230     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7231                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7232                        .addImm(0));
7233   } else if (IsThumb1) {
7234     // load + update AddrIn
7235     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7236                        .addReg(AddrIn).addImm(0));
7237     MachineInstrBuilder MIB =
7238         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7239     MIB = AddDefaultT1CC(MIB);
7240     MIB.addReg(AddrIn).addImm(LdSize);
7241     AddDefaultPred(MIB);
7242   } else if (IsThumb2) {
7243     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7244                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7245                        .addImm(LdSize));
7246   } else { // arm
7247     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7248                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7249                        .addReg(0).addImm(LdSize));
7250   }
7251 }
7252
7253 /// Emit a post-increment store operation with given size. The instructions
7254 /// will be added to BB at Pos.
7255 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7256                        const TargetInstrInfo *TII, DebugLoc dl,
7257                        unsigned StSize, unsigned Data, unsigned AddrIn,
7258                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7259   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7260   assert(StOpc != 0 && "Should have a store opcode");
7261   if (StSize >= 8) {
7262     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7263                        .addReg(AddrIn).addImm(0).addReg(Data));
7264   } else if (IsThumb1) {
7265     // store + update AddrIn
7266     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7267                        .addReg(AddrIn).addImm(0));
7268     MachineInstrBuilder MIB =
7269         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7270     MIB = AddDefaultT1CC(MIB);
7271     MIB.addReg(AddrIn).addImm(StSize);
7272     AddDefaultPred(MIB);
7273   } else if (IsThumb2) {
7274     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7275                        .addReg(Data).addReg(AddrIn).addImm(StSize));
7276   } else { // arm
7277     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7278                        .addReg(Data).addReg(AddrIn).addReg(0)
7279                        .addImm(StSize));
7280   }
7281 }
7282
7283 MachineBasicBlock *
7284 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7285                                    MachineBasicBlock *BB) const {
7286   // This pseudo instruction has 3 operands: dst, src, size
7287   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7288   // Otherwise, we will generate unrolled scalar copies.
7289   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7290   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7291   MachineFunction::iterator It = BB;
7292   ++It;
7293
7294   unsigned dest = MI->getOperand(0).getReg();
7295   unsigned src = MI->getOperand(1).getReg();
7296   unsigned SizeVal = MI->getOperand(2).getImm();
7297   unsigned Align = MI->getOperand(3).getImm();
7298   DebugLoc dl = MI->getDebugLoc();
7299
7300   MachineFunction *MF = BB->getParent();
7301   MachineRegisterInfo &MRI = MF->getRegInfo();
7302   unsigned UnitSize = 0;
7303   const TargetRegisterClass *TRC = nullptr;
7304   const TargetRegisterClass *VecTRC = nullptr;
7305
7306   bool IsThumb1 = Subtarget->isThumb1Only();
7307   bool IsThumb2 = Subtarget->isThumb2();
7308
7309   if (Align & 1) {
7310     UnitSize = 1;
7311   } else if (Align & 2) {
7312     UnitSize = 2;
7313   } else {
7314     // Check whether we can use NEON instructions.
7315     if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
7316         Subtarget->hasNEON()) {
7317       if ((Align % 16 == 0) && SizeVal >= 16)
7318         UnitSize = 16;
7319       else if ((Align % 8 == 0) && SizeVal >= 8)
7320         UnitSize = 8;
7321     }
7322     // Can't use NEON instructions.
7323     if (UnitSize == 0)
7324       UnitSize = 4;
7325   }
7326
7327   // Select the correct opcode and register class for unit size load/store
7328   bool IsNeon = UnitSize >= 8;
7329   TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
7330   if (IsNeon)
7331     VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
7332                             : UnitSize == 8 ? &ARM::DPRRegClass
7333                                             : nullptr;
7334
7335   unsigned BytesLeft = SizeVal % UnitSize;
7336   unsigned LoopSize = SizeVal - BytesLeft;
7337
7338   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7339     // Use LDR and STR to copy.
7340     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7341     // [destOut] = STR_POST(scratch, destIn, UnitSize)
7342     unsigned srcIn = src;
7343     unsigned destIn = dest;
7344     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7345       unsigned srcOut = MRI.createVirtualRegister(TRC);
7346       unsigned destOut = MRI.createVirtualRegister(TRC);
7347       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7348       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7349                  IsThumb1, IsThumb2);
7350       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7351                  IsThumb1, IsThumb2);
7352       srcIn = srcOut;
7353       destIn = destOut;
7354     }
7355
7356     // Handle the leftover bytes with LDRB and STRB.
7357     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7358     // [destOut] = STRB_POST(scratch, destIn, 1)
7359     for (unsigned i = 0; i < BytesLeft; i++) {
7360       unsigned srcOut = MRI.createVirtualRegister(TRC);
7361       unsigned destOut = MRI.createVirtualRegister(TRC);
7362       unsigned scratch = MRI.createVirtualRegister(TRC);
7363       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7364                  IsThumb1, IsThumb2);
7365       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7366                  IsThumb1, IsThumb2);
7367       srcIn = srcOut;
7368       destIn = destOut;
7369     }
7370     MI->eraseFromParent();   // The instruction is gone now.
7371     return BB;
7372   }
7373
7374   // Expand the pseudo op to a loop.
7375   // thisMBB:
7376   //   ...
7377   //   movw varEnd, # --> with thumb2
7378   //   movt varEnd, #
7379   //   ldrcp varEnd, idx --> without thumb2
7380   //   fallthrough --> loopMBB
7381   // loopMBB:
7382   //   PHI varPhi, varEnd, varLoop
7383   //   PHI srcPhi, src, srcLoop
7384   //   PHI destPhi, dst, destLoop
7385   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7386   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7387   //   subs varLoop, varPhi, #UnitSize
7388   //   bne loopMBB
7389   //   fallthrough --> exitMBB
7390   // exitMBB:
7391   //   epilogue to handle left-over bytes
7392   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7393   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7394   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7395   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7396   MF->insert(It, loopMBB);
7397   MF->insert(It, exitMBB);
7398
7399   // Transfer the remainder of BB and its successor edges to exitMBB.
7400   exitMBB->splice(exitMBB->begin(), BB,
7401                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7402   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7403
7404   // Load an immediate to varEnd.
7405   unsigned varEnd = MRI.createVirtualRegister(TRC);
7406   if (Subtarget->useMovt(*MF)) {
7407     unsigned Vtmp = varEnd;
7408     if ((LoopSize & 0xFFFF0000) != 0)
7409       Vtmp = MRI.createVirtualRegister(TRC);
7410     AddDefaultPred(BuildMI(BB, dl,
7411                            TII->get(IsThumb2 ? ARM::t2MOVi16 : ARM::MOVi16),
7412                            Vtmp).addImm(LoopSize & 0xFFFF));
7413
7414     if ((LoopSize & 0xFFFF0000) != 0)
7415       AddDefaultPred(BuildMI(BB, dl,
7416                              TII->get(IsThumb2 ? ARM::t2MOVTi16 : ARM::MOVTi16),
7417                              varEnd)
7418                          .addReg(Vtmp)
7419                          .addImm(LoopSize >> 16));
7420   } else {
7421     MachineConstantPool *ConstantPool = MF->getConstantPool();
7422     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7423     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7424
7425     // MachineConstantPool wants an explicit alignment.
7426     unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7427     if (Align == 0)
7428       Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7429     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7430
7431     if (IsThumb1)
7432       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7433           varEnd, RegState::Define).addConstantPoolIndex(Idx));
7434     else
7435       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7436           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7437   }
7438   BB->addSuccessor(loopMBB);
7439
7440   // Generate the loop body:
7441   //   varPhi = PHI(varLoop, varEnd)
7442   //   srcPhi = PHI(srcLoop, src)
7443   //   destPhi = PHI(destLoop, dst)
7444   MachineBasicBlock *entryBB = BB;
7445   BB = loopMBB;
7446   unsigned varLoop = MRI.createVirtualRegister(TRC);
7447   unsigned varPhi = MRI.createVirtualRegister(TRC);
7448   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7449   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7450   unsigned destLoop = MRI.createVirtualRegister(TRC);
7451   unsigned destPhi = MRI.createVirtualRegister(TRC);
7452
7453   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7454     .addReg(varLoop).addMBB(loopMBB)
7455     .addReg(varEnd).addMBB(entryBB);
7456   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7457     .addReg(srcLoop).addMBB(loopMBB)
7458     .addReg(src).addMBB(entryBB);
7459   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7460     .addReg(destLoop).addMBB(loopMBB)
7461     .addReg(dest).addMBB(entryBB);
7462
7463   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7464   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7465   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7466   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7467              IsThumb1, IsThumb2);
7468   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7469              IsThumb1, IsThumb2);
7470
7471   // Decrement loop variable by UnitSize.
7472   if (IsThumb1) {
7473     MachineInstrBuilder MIB =
7474         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7475     MIB = AddDefaultT1CC(MIB);
7476     MIB.addReg(varPhi).addImm(UnitSize);
7477     AddDefaultPred(MIB);
7478   } else {
7479     MachineInstrBuilder MIB =
7480         BuildMI(*BB, BB->end(), dl,
7481                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7482     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7483     MIB->getOperand(5).setReg(ARM::CPSR);
7484     MIB->getOperand(5).setIsDef(true);
7485   }
7486   BuildMI(*BB, BB->end(), dl,
7487           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7488       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7489
7490   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7491   BB->addSuccessor(loopMBB);
7492   BB->addSuccessor(exitMBB);
7493
7494   // Add epilogue to handle BytesLeft.
7495   BB = exitMBB;
7496   MachineInstr *StartOfExit = exitMBB->begin();
7497
7498   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7499   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7500   unsigned srcIn = srcLoop;
7501   unsigned destIn = destLoop;
7502   for (unsigned i = 0; i < BytesLeft; i++) {
7503     unsigned srcOut = MRI.createVirtualRegister(TRC);
7504     unsigned destOut = MRI.createVirtualRegister(TRC);
7505     unsigned scratch = MRI.createVirtualRegister(TRC);
7506     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7507                IsThumb1, IsThumb2);
7508     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7509                IsThumb1, IsThumb2);
7510     srcIn = srcOut;
7511     destIn = destOut;
7512   }
7513
7514   MI->eraseFromParent();   // The instruction is gone now.
7515   return BB;
7516 }
7517
7518 MachineBasicBlock *
7519 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7520                                        MachineBasicBlock *MBB) const {
7521   const TargetMachine &TM = getTargetMachine();
7522   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
7523   DebugLoc DL = MI->getDebugLoc();
7524
7525   assert(Subtarget->isTargetWindows() &&
7526          "__chkstk is only supported on Windows");
7527   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7528
7529   // __chkstk takes the number of words to allocate on the stack in R4, and
7530   // returns the stack adjustment in number of bytes in R4.  This will not
7531   // clober any other registers (other than the obvious lr).
7532   //
7533   // Although, technically, IP should be considered a register which may be
7534   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
7535   // thumb-2 environment, so there is no interworking required.  As a result, we
7536   // do not expect a veneer to be emitted by the linker, clobbering IP.
7537   //
7538   // Each module receives its own copy of __chkstk, so no import thunk is
7539   // required, again, ensuring that IP is not clobbered.
7540   //
7541   // Finally, although some linkers may theoretically provide a trampoline for
7542   // out of range calls (which is quite common due to a 32M range limitation of
7543   // branches for Thumb), we can generate the long-call version via
7544   // -mcmodel=large, alleviating the need for the trampoline which may clobber
7545   // IP.
7546
7547   switch (TM.getCodeModel()) {
7548   case CodeModel::Small:
7549   case CodeModel::Medium:
7550   case CodeModel::Default:
7551   case CodeModel::Kernel:
7552     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7553       .addImm((unsigned)ARMCC::AL).addReg(0)
7554       .addExternalSymbol("__chkstk")
7555       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7556       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7557       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7558     break;
7559   case CodeModel::Large:
7560   case CodeModel::JITDefault: {
7561     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7562     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7563
7564     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7565       .addExternalSymbol("__chkstk");
7566     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7567       .addImm((unsigned)ARMCC::AL).addReg(0)
7568       .addReg(Reg, RegState::Kill)
7569       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7570       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7571       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7572     break;
7573   }
7574   }
7575
7576   AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7577                                       ARM::SP)
7578                               .addReg(ARM::SP).addReg(ARM::R4)));
7579
7580   MI->eraseFromParent();
7581   return MBB;
7582 }
7583
7584 MachineBasicBlock *
7585 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7586                                                MachineBasicBlock *BB) const {
7587   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7588   DebugLoc dl = MI->getDebugLoc();
7589   bool isThumb2 = Subtarget->isThumb2();
7590   switch (MI->getOpcode()) {
7591   default: {
7592     MI->dump();
7593     llvm_unreachable("Unexpected instr type to insert");
7594   }
7595   // The Thumb2 pre-indexed stores have the same MI operands, they just
7596   // define them differently in the .td files from the isel patterns, so
7597   // they need pseudos.
7598   case ARM::t2STR_preidx:
7599     MI->setDesc(TII->get(ARM::t2STR_PRE));
7600     return BB;
7601   case ARM::t2STRB_preidx:
7602     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7603     return BB;
7604   case ARM::t2STRH_preidx:
7605     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7606     return BB;
7607
7608   case ARM::STRi_preidx:
7609   case ARM::STRBi_preidx: {
7610     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7611       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7612     // Decode the offset.
7613     unsigned Offset = MI->getOperand(4).getImm();
7614     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7615     Offset = ARM_AM::getAM2Offset(Offset);
7616     if (isSub)
7617       Offset = -Offset;
7618
7619     MachineMemOperand *MMO = *MI->memoperands_begin();
7620     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7621       .addOperand(MI->getOperand(0))  // Rn_wb
7622       .addOperand(MI->getOperand(1))  // Rt
7623       .addOperand(MI->getOperand(2))  // Rn
7624       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7625       .addOperand(MI->getOperand(5))  // pred
7626       .addOperand(MI->getOperand(6))
7627       .addMemOperand(MMO);
7628     MI->eraseFromParent();
7629     return BB;
7630   }
7631   case ARM::STRr_preidx:
7632   case ARM::STRBr_preidx:
7633   case ARM::STRH_preidx: {
7634     unsigned NewOpc;
7635     switch (MI->getOpcode()) {
7636     default: llvm_unreachable("unexpected opcode!");
7637     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7638     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7639     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7640     }
7641     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7642     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7643       MIB.addOperand(MI->getOperand(i));
7644     MI->eraseFromParent();
7645     return BB;
7646   }
7647
7648   case ARM::tMOVCCr_pseudo: {
7649     // To "insert" a SELECT_CC instruction, we actually have to insert the
7650     // diamond control-flow pattern.  The incoming instruction knows the
7651     // destination vreg to set, the condition code register to branch on, the
7652     // true/false values to select between, and a branch opcode to use.
7653     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7654     MachineFunction::iterator It = BB;
7655     ++It;
7656
7657     //  thisMBB:
7658     //  ...
7659     //   TrueVal = ...
7660     //   cmpTY ccX, r1, r2
7661     //   bCC copy1MBB
7662     //   fallthrough --> copy0MBB
7663     MachineBasicBlock *thisMBB  = BB;
7664     MachineFunction *F = BB->getParent();
7665     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7666     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7667     F->insert(It, copy0MBB);
7668     F->insert(It, sinkMBB);
7669
7670     // Transfer the remainder of BB and its successor edges to sinkMBB.
7671     sinkMBB->splice(sinkMBB->begin(), BB,
7672                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7673     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7674
7675     BB->addSuccessor(copy0MBB);
7676     BB->addSuccessor(sinkMBB);
7677
7678     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7679       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7680
7681     //  copy0MBB:
7682     //   %FalseValue = ...
7683     //   # fallthrough to sinkMBB
7684     BB = copy0MBB;
7685
7686     // Update machine-CFG edges
7687     BB->addSuccessor(sinkMBB);
7688
7689     //  sinkMBB:
7690     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7691     //  ...
7692     BB = sinkMBB;
7693     BuildMI(*BB, BB->begin(), dl,
7694             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7695       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7696       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7697
7698     MI->eraseFromParent();   // The pseudo instruction is gone now.
7699     return BB;
7700   }
7701
7702   case ARM::BCCi64:
7703   case ARM::BCCZi64: {
7704     // If there is an unconditional branch to the other successor, remove it.
7705     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7706
7707     // Compare both parts that make up the double comparison separately for
7708     // equality.
7709     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7710
7711     unsigned LHS1 = MI->getOperand(1).getReg();
7712     unsigned LHS2 = MI->getOperand(2).getReg();
7713     if (RHSisZero) {
7714       AddDefaultPred(BuildMI(BB, dl,
7715                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7716                      .addReg(LHS1).addImm(0));
7717       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7718         .addReg(LHS2).addImm(0)
7719         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7720     } else {
7721       unsigned RHS1 = MI->getOperand(3).getReg();
7722       unsigned RHS2 = MI->getOperand(4).getReg();
7723       AddDefaultPred(BuildMI(BB, dl,
7724                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7725                      .addReg(LHS1).addReg(RHS1));
7726       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7727         .addReg(LHS2).addReg(RHS2)
7728         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7729     }
7730
7731     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7732     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7733     if (MI->getOperand(0).getImm() == ARMCC::NE)
7734       std::swap(destMBB, exitMBB);
7735
7736     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7737       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7738     if (isThumb2)
7739       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7740     else
7741       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7742
7743     MI->eraseFromParent();   // The pseudo instruction is gone now.
7744     return BB;
7745   }
7746
7747   case ARM::Int_eh_sjlj_setjmp:
7748   case ARM::Int_eh_sjlj_setjmp_nofp:
7749   case ARM::tInt_eh_sjlj_setjmp:
7750   case ARM::t2Int_eh_sjlj_setjmp:
7751   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7752     return BB;
7753
7754   case ARM::Int_eh_sjlj_setup_dispatch:
7755     EmitSjLjDispatchBlock(MI, BB);
7756     return BB;
7757
7758   case ARM::ABS:
7759   case ARM::t2ABS: {
7760     // To insert an ABS instruction, we have to insert the
7761     // diamond control-flow pattern.  The incoming instruction knows the
7762     // source vreg to test against 0, the destination vreg to set,
7763     // the condition code register to branch on, the
7764     // true/false values to select between, and a branch opcode to use.
7765     // It transforms
7766     //     V1 = ABS V0
7767     // into
7768     //     V2 = MOVS V0
7769     //     BCC                      (branch to SinkBB if V0 >= 0)
7770     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7771     //     SinkBB: V1 = PHI(V2, V3)
7772     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7773     MachineFunction::iterator BBI = BB;
7774     ++BBI;
7775     MachineFunction *Fn = BB->getParent();
7776     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7777     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7778     Fn->insert(BBI, RSBBB);
7779     Fn->insert(BBI, SinkBB);
7780
7781     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7782     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7783     bool ABSSrcKIll = MI->getOperand(1).isKill();
7784     bool isThumb2 = Subtarget->isThumb2();
7785     MachineRegisterInfo &MRI = Fn->getRegInfo();
7786     // In Thumb mode S must not be specified if source register is the SP or
7787     // PC and if destination register is the SP, so restrict register class
7788     unsigned NewRsbDstReg =
7789       MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
7790
7791     // Transfer the remainder of BB and its successor edges to sinkMBB.
7792     SinkBB->splice(SinkBB->begin(), BB,
7793                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
7794     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7795
7796     BB->addSuccessor(RSBBB);
7797     BB->addSuccessor(SinkBB);
7798
7799     // fall through to SinkMBB
7800     RSBBB->addSuccessor(SinkBB);
7801
7802     // insert a cmp at the end of BB
7803     AddDefaultPred(BuildMI(BB, dl,
7804                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7805                    .addReg(ABSSrcReg).addImm(0));
7806
7807     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7808     BuildMI(BB, dl,
7809       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7810       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7811
7812     // insert rsbri in RSBBB
7813     // Note: BCC and rsbri will be converted into predicated rsbmi
7814     // by if-conversion pass
7815     BuildMI(*RSBBB, RSBBB->begin(), dl,
7816       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7817       .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
7818       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7819
7820     // insert PHI in SinkBB,
7821     // reuse ABSDstReg to not change uses of ABS instruction
7822     BuildMI(*SinkBB, SinkBB->begin(), dl,
7823       TII->get(ARM::PHI), ABSDstReg)
7824       .addReg(NewRsbDstReg).addMBB(RSBBB)
7825       .addReg(ABSSrcReg).addMBB(BB);
7826
7827     // remove ABS instruction
7828     MI->eraseFromParent();
7829
7830     // return last added BB
7831     return SinkBB;
7832   }
7833   case ARM::COPY_STRUCT_BYVAL_I32:
7834     ++NumLoopByVals;
7835     return EmitStructByval(MI, BB);
7836   case ARM::WIN__CHKSTK:
7837     return EmitLowered__chkstk(MI, BB);
7838   }
7839 }
7840
7841 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7842                                                       SDNode *Node) const {
7843   const MCInstrDesc *MCID = &MI->getDesc();
7844   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7845   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7846   // operand is still set to noreg. If needed, set the optional operand's
7847   // register to CPSR, and remove the redundant implicit def.
7848   //
7849   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7850
7851   // Rename pseudo opcodes.
7852   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7853   if (NewOpc) {
7854     const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
7855     MCID = &TII->get(NewOpc);
7856
7857     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7858            "converted opcode should be the same except for cc_out");
7859
7860     MI->setDesc(*MCID);
7861
7862     // Add the optional cc_out operand
7863     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7864   }
7865   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7866
7867   // Any ARM instruction that sets the 's' bit should specify an optional
7868   // "cc_out" operand in the last operand position.
7869   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7870     assert(!NewOpc && "Optional cc_out operand required");
7871     return;
7872   }
7873   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7874   // since we already have an optional CPSR def.
7875   bool definesCPSR = false;
7876   bool deadCPSR = false;
7877   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7878        i != e; ++i) {
7879     const MachineOperand &MO = MI->getOperand(i);
7880     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7881       definesCPSR = true;
7882       if (MO.isDead())
7883         deadCPSR = true;
7884       MI->RemoveOperand(i);
7885       break;
7886     }
7887   }
7888   if (!definesCPSR) {
7889     assert(!NewOpc && "Optional cc_out operand required");
7890     return;
7891   }
7892   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7893   if (deadCPSR) {
7894     assert(!MI->getOperand(ccOutIdx).getReg() &&
7895            "expect uninitialized optional cc_out operand");
7896     return;
7897   }
7898
7899   // If this instruction was defined with an optional CPSR def and its dag node
7900   // had a live implicit CPSR def, then activate the optional CPSR def.
7901   MachineOperand &MO = MI->getOperand(ccOutIdx);
7902   MO.setReg(ARM::CPSR);
7903   MO.setIsDef(true);
7904 }
7905
7906 //===----------------------------------------------------------------------===//
7907 //                           ARM Optimization Hooks
7908 //===----------------------------------------------------------------------===//
7909
7910 // Helper function that checks if N is a null or all ones constant.
7911 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7912   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7913   if (!C)
7914     return false;
7915   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7916 }
7917
7918 // Return true if N is conditionally 0 or all ones.
7919 // Detects these expressions where cc is an i1 value:
7920 //
7921 //   (select cc 0, y)   [AllOnes=0]
7922 //   (select cc y, 0)   [AllOnes=0]
7923 //   (zext cc)          [AllOnes=0]
7924 //   (sext cc)          [AllOnes=0/1]
7925 //   (select cc -1, y)  [AllOnes=1]
7926 //   (select cc y, -1)  [AllOnes=1]
7927 //
7928 // Invert is set when N is the null/all ones constant when CC is false.
7929 // OtherOp is set to the alternative value of N.
7930 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7931                                        SDValue &CC, bool &Invert,
7932                                        SDValue &OtherOp,
7933                                        SelectionDAG &DAG) {
7934   switch (N->getOpcode()) {
7935   default: return false;
7936   case ISD::SELECT: {
7937     CC = N->getOperand(0);
7938     SDValue N1 = N->getOperand(1);
7939     SDValue N2 = N->getOperand(2);
7940     if (isZeroOrAllOnes(N1, AllOnes)) {
7941       Invert = false;
7942       OtherOp = N2;
7943       return true;
7944     }
7945     if (isZeroOrAllOnes(N2, AllOnes)) {
7946       Invert = true;
7947       OtherOp = N1;
7948       return true;
7949     }
7950     return false;
7951   }
7952   case ISD::ZERO_EXTEND:
7953     // (zext cc) can never be the all ones value.
7954     if (AllOnes)
7955       return false;
7956     // Fall through.
7957   case ISD::SIGN_EXTEND: {
7958     SDLoc dl(N);
7959     EVT VT = N->getValueType(0);
7960     CC = N->getOperand(0);
7961     if (CC.getValueType() != MVT::i1)
7962       return false;
7963     Invert = !AllOnes;
7964     if (AllOnes)
7965       // When looking for an AllOnes constant, N is an sext, and the 'other'
7966       // value is 0.
7967       OtherOp = DAG.getConstant(0, dl, VT);
7968     else if (N->getOpcode() == ISD::ZERO_EXTEND)
7969       // When looking for a 0 constant, N can be zext or sext.
7970       OtherOp = DAG.getConstant(1, dl, VT);
7971     else
7972       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
7973                                 VT);
7974     return true;
7975   }
7976   }
7977 }
7978
7979 // Combine a constant select operand into its use:
7980 //
7981 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
7982 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
7983 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
7984 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
7985 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
7986 //
7987 // The transform is rejected if the select doesn't have a constant operand that
7988 // is null, or all ones when AllOnes is set.
7989 //
7990 // Also recognize sext/zext from i1:
7991 //
7992 //   (add (zext cc), x) -> (select cc (add x, 1), x)
7993 //   (add (sext cc), x) -> (select cc (add x, -1), x)
7994 //
7995 // These transformations eventually create predicated instructions.
7996 //
7997 // @param N       The node to transform.
7998 // @param Slct    The N operand that is a select.
7999 // @param OtherOp The other N operand (x above).
8000 // @param DCI     Context.
8001 // @param AllOnes Require the select constant to be all ones instead of null.
8002 // @returns The new node, or SDValue() on failure.
8003 static
8004 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
8005                             TargetLowering::DAGCombinerInfo &DCI,
8006                             bool AllOnes = false) {
8007   SelectionDAG &DAG = DCI.DAG;
8008   EVT VT = N->getValueType(0);
8009   SDValue NonConstantVal;
8010   SDValue CCOp;
8011   bool SwapSelectOps;
8012   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
8013                                   NonConstantVal, DAG))
8014     return SDValue();
8015
8016   // Slct is now know to be the desired identity constant when CC is true.
8017   SDValue TrueVal = OtherOp;
8018   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
8019                                  OtherOp, NonConstantVal);
8020   // Unless SwapSelectOps says CC should be false.
8021   if (SwapSelectOps)
8022     std::swap(TrueVal, FalseVal);
8023
8024   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
8025                      CCOp, TrueVal, FalseVal);
8026 }
8027
8028 // Attempt combineSelectAndUse on each operand of a commutative operator N.
8029 static
8030 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
8031                                        TargetLowering::DAGCombinerInfo &DCI) {
8032   SDValue N0 = N->getOperand(0);
8033   SDValue N1 = N->getOperand(1);
8034   if (N0.getNode()->hasOneUse()) {
8035     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
8036     if (Result.getNode())
8037       return Result;
8038   }
8039   if (N1.getNode()->hasOneUse()) {
8040     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
8041     if (Result.getNode())
8042       return Result;
8043   }
8044   return SDValue();
8045 }
8046
8047 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
8048 // (only after legalization).
8049 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
8050                                  TargetLowering::DAGCombinerInfo &DCI,
8051                                  const ARMSubtarget *Subtarget) {
8052
8053   // Only perform optimization if after legalize, and if NEON is available. We
8054   // also expected both operands to be BUILD_VECTORs.
8055   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
8056       || N0.getOpcode() != ISD::BUILD_VECTOR
8057       || N1.getOpcode() != ISD::BUILD_VECTOR)
8058     return SDValue();
8059
8060   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
8061   EVT VT = N->getValueType(0);
8062   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
8063     return SDValue();
8064
8065   // Check that the vector operands are of the right form.
8066   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
8067   // operands, where N is the size of the formed vector.
8068   // Each EXTRACT_VECTOR should have the same input vector and odd or even
8069   // index such that we have a pair wise add pattern.
8070
8071   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
8072   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8073     return SDValue();
8074   SDValue Vec = N0->getOperand(0)->getOperand(0);
8075   SDNode *V = Vec.getNode();
8076   unsigned nextIndex = 0;
8077
8078   // For each operands to the ADD which are BUILD_VECTORs,
8079   // check to see if each of their operands are an EXTRACT_VECTOR with
8080   // the same vector and appropriate index.
8081   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
8082     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
8083         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8084
8085       SDValue ExtVec0 = N0->getOperand(i);
8086       SDValue ExtVec1 = N1->getOperand(i);
8087
8088       // First operand is the vector, verify its the same.
8089       if (V != ExtVec0->getOperand(0).getNode() ||
8090           V != ExtVec1->getOperand(0).getNode())
8091         return SDValue();
8092
8093       // Second is the constant, verify its correct.
8094       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
8095       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
8096
8097       // For the constant, we want to see all the even or all the odd.
8098       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
8099           || C1->getZExtValue() != nextIndex+1)
8100         return SDValue();
8101
8102       // Increment index.
8103       nextIndex+=2;
8104     } else
8105       return SDValue();
8106   }
8107
8108   // Create VPADDL node.
8109   SelectionDAG &DAG = DCI.DAG;
8110   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8111
8112   SDLoc dl(N);
8113
8114   // Build operand list.
8115   SmallVector<SDValue, 8> Ops;
8116   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
8117                                 TLI.getPointerTy(DAG.getDataLayout())));
8118
8119   // Input is the vector.
8120   Ops.push_back(Vec);
8121
8122   // Get widened type and narrowed type.
8123   MVT widenType;
8124   unsigned numElem = VT.getVectorNumElements();
8125   
8126   EVT inputLaneType = Vec.getValueType().getVectorElementType();
8127   switch (inputLaneType.getSimpleVT().SimpleTy) {
8128     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
8129     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
8130     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
8131     default:
8132       llvm_unreachable("Invalid vector element type for padd optimization.");
8133   }
8134
8135   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
8136   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
8137   return DAG.getNode(ExtOp, dl, VT, tmp);
8138 }
8139
8140 static SDValue findMUL_LOHI(SDValue V) {
8141   if (V->getOpcode() == ISD::UMUL_LOHI ||
8142       V->getOpcode() == ISD::SMUL_LOHI)
8143     return V;
8144   return SDValue();
8145 }
8146
8147 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
8148                                      TargetLowering::DAGCombinerInfo &DCI,
8149                                      const ARMSubtarget *Subtarget) {
8150
8151   if (Subtarget->isThumb1Only()) return SDValue();
8152
8153   // Only perform the checks after legalize when the pattern is available.
8154   if (DCI.isBeforeLegalize()) return SDValue();
8155
8156   // Look for multiply add opportunities.
8157   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8158   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8159   // a glue link from the first add to the second add.
8160   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8161   // a S/UMLAL instruction.
8162   //                  UMUL_LOHI
8163   //                 / :lo    \ :hi
8164   //                /          \          [no multiline comment]
8165   //    loAdd ->  ADDE         |
8166   //                 \ :glue  /
8167   //                  \      /
8168   //                    ADDC   <- hiAdd
8169   //
8170   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8171   SDValue AddcOp0 = AddcNode->getOperand(0);
8172   SDValue AddcOp1 = AddcNode->getOperand(1);
8173
8174   // Check if the two operands are from the same mul_lohi node.
8175   if (AddcOp0.getNode() == AddcOp1.getNode())
8176     return SDValue();
8177
8178   assert(AddcNode->getNumValues() == 2 &&
8179          AddcNode->getValueType(0) == MVT::i32 &&
8180          "Expect ADDC with two result values. First: i32");
8181
8182   // Check that we have a glued ADDC node.
8183   if (AddcNode->getValueType(1) != MVT::Glue)
8184     return SDValue();
8185
8186   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8187   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8188       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8189       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8190       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8191     return SDValue();
8192
8193   // Look for the glued ADDE.
8194   SDNode* AddeNode = AddcNode->getGluedUser();
8195   if (!AddeNode)
8196     return SDValue();
8197
8198   // Make sure it is really an ADDE.
8199   if (AddeNode->getOpcode() != ISD::ADDE)
8200     return SDValue();
8201
8202   assert(AddeNode->getNumOperands() == 3 &&
8203          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8204          "ADDE node has the wrong inputs");
8205
8206   // Check for the triangle shape.
8207   SDValue AddeOp0 = AddeNode->getOperand(0);
8208   SDValue AddeOp1 = AddeNode->getOperand(1);
8209
8210   // Make sure that the ADDE operands are not coming from the same node.
8211   if (AddeOp0.getNode() == AddeOp1.getNode())
8212     return SDValue();
8213
8214   // Find the MUL_LOHI node walking up ADDE's operands.
8215   bool IsLeftOperandMUL = false;
8216   SDValue MULOp = findMUL_LOHI(AddeOp0);
8217   if (MULOp == SDValue())
8218    MULOp = findMUL_LOHI(AddeOp1);
8219   else
8220     IsLeftOperandMUL = true;
8221   if (MULOp == SDValue())
8222     return SDValue();
8223
8224   // Figure out the right opcode.
8225   unsigned Opc = MULOp->getOpcode();
8226   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8227
8228   // Figure out the high and low input values to the MLAL node.
8229   SDValue* HiAdd = nullptr;
8230   SDValue* LoMul = nullptr;
8231   SDValue* LowAdd = nullptr;
8232
8233   // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
8234   if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
8235     return SDValue();
8236
8237   if (IsLeftOperandMUL)
8238     HiAdd = &AddeOp1;
8239   else
8240     HiAdd = &AddeOp0;
8241
8242
8243   // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
8244   // whose low result is fed to the ADDC we are checking.
8245
8246   if (AddcOp0 == MULOp.getValue(0)) {
8247     LoMul = &AddcOp0;
8248     LowAdd = &AddcOp1;
8249   }
8250   if (AddcOp1 == MULOp.getValue(0)) {
8251     LoMul = &AddcOp1;
8252     LowAdd = &AddcOp0;
8253   }
8254
8255   if (!LoMul)
8256     return SDValue();
8257
8258   // Create the merged node.
8259   SelectionDAG &DAG = DCI.DAG;
8260
8261   // Build operand list.
8262   SmallVector<SDValue, 8> Ops;
8263   Ops.push_back(LoMul->getOperand(0));
8264   Ops.push_back(LoMul->getOperand(1));
8265   Ops.push_back(*LowAdd);
8266   Ops.push_back(*HiAdd);
8267
8268   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
8269                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
8270
8271   // Replace the ADDs' nodes uses by the MLA node's values.
8272   SDValue HiMLALResult(MLALNode.getNode(), 1);
8273   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8274
8275   SDValue LoMLALResult(MLALNode.getNode(), 0);
8276   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8277
8278   // Return original node to notify the driver to stop replacing.
8279   SDValue resNode(AddcNode, 0);
8280   return resNode;
8281 }
8282
8283 /// PerformADDCCombine - Target-specific dag combine transform from
8284 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8285 static SDValue PerformADDCCombine(SDNode *N,
8286                                  TargetLowering::DAGCombinerInfo &DCI,
8287                                  const ARMSubtarget *Subtarget) {
8288
8289   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8290
8291 }
8292
8293 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8294 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
8295 /// called with the default operands, and if that fails, with commuted
8296 /// operands.
8297 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8298                                           TargetLowering::DAGCombinerInfo &DCI,
8299                                           const ARMSubtarget *Subtarget){
8300
8301   // Attempt to create vpaddl for this add.
8302   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8303   if (Result.getNode())
8304     return Result;
8305
8306   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8307   if (N0.getNode()->hasOneUse()) {
8308     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8309     if (Result.getNode()) return Result;
8310   }
8311   return SDValue();
8312 }
8313
8314 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8315 ///
8316 static SDValue PerformADDCombine(SDNode *N,
8317                                  TargetLowering::DAGCombinerInfo &DCI,
8318                                  const ARMSubtarget *Subtarget) {
8319   SDValue N0 = N->getOperand(0);
8320   SDValue N1 = N->getOperand(1);
8321
8322   // First try with the default operand order.
8323   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8324   if (Result.getNode())
8325     return Result;
8326
8327   // If that didn't work, try again with the operands commuted.
8328   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8329 }
8330
8331 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8332 ///
8333 static SDValue PerformSUBCombine(SDNode *N,
8334                                  TargetLowering::DAGCombinerInfo &DCI) {
8335   SDValue N0 = N->getOperand(0);
8336   SDValue N1 = N->getOperand(1);
8337
8338   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8339   if (N1.getNode()->hasOneUse()) {
8340     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8341     if (Result.getNode()) return Result;
8342   }
8343
8344   return SDValue();
8345 }
8346
8347 /// PerformVMULCombine
8348 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8349 /// special multiplier accumulator forwarding.
8350 ///   vmul d3, d0, d2
8351 ///   vmla d3, d1, d2
8352 /// is faster than
8353 ///   vadd d3, d0, d1
8354 ///   vmul d3, d3, d2
8355 //  However, for (A + B) * (A + B),
8356 //    vadd d2, d0, d1
8357 //    vmul d3, d0, d2
8358 //    vmla d3, d1, d2
8359 //  is slower than
8360 //    vadd d2, d0, d1
8361 //    vmul d3, d2, d2
8362 static SDValue PerformVMULCombine(SDNode *N,
8363                                   TargetLowering::DAGCombinerInfo &DCI,
8364                                   const ARMSubtarget *Subtarget) {
8365   if (!Subtarget->hasVMLxForwarding())
8366     return SDValue();
8367
8368   SelectionDAG &DAG = DCI.DAG;
8369   SDValue N0 = N->getOperand(0);
8370   SDValue N1 = N->getOperand(1);
8371   unsigned Opcode = N0.getOpcode();
8372   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8373       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8374     Opcode = N1.getOpcode();
8375     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8376         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8377       return SDValue();
8378     std::swap(N0, N1);
8379   }
8380
8381   if (N0 == N1)
8382     return SDValue();
8383
8384   EVT VT = N->getValueType(0);
8385   SDLoc DL(N);
8386   SDValue N00 = N0->getOperand(0);
8387   SDValue N01 = N0->getOperand(1);
8388   return DAG.getNode(Opcode, DL, VT,
8389                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8390                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8391 }
8392
8393 static SDValue PerformMULCombine(SDNode *N,
8394                                  TargetLowering::DAGCombinerInfo &DCI,
8395                                  const ARMSubtarget *Subtarget) {
8396   SelectionDAG &DAG = DCI.DAG;
8397
8398   if (Subtarget->isThumb1Only())
8399     return SDValue();
8400
8401   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8402     return SDValue();
8403
8404   EVT VT = N->getValueType(0);
8405   if (VT.is64BitVector() || VT.is128BitVector())
8406     return PerformVMULCombine(N, DCI, Subtarget);
8407   if (VT != MVT::i32)
8408     return SDValue();
8409
8410   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8411   if (!C)
8412     return SDValue();
8413
8414   int64_t MulAmt = C->getSExtValue();
8415   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8416
8417   ShiftAmt = ShiftAmt & (32 - 1);
8418   SDValue V = N->getOperand(0);
8419   SDLoc DL(N);
8420
8421   SDValue Res;
8422   MulAmt >>= ShiftAmt;
8423
8424   if (MulAmt >= 0) {
8425     if (isPowerOf2_32(MulAmt - 1)) {
8426       // (mul x, 2^N + 1) => (add (shl x, N), x)
8427       Res = DAG.getNode(ISD::ADD, DL, VT,
8428                         V,
8429                         DAG.getNode(ISD::SHL, DL, VT,
8430                                     V,
8431                                     DAG.getConstant(Log2_32(MulAmt - 1), DL,
8432                                                     MVT::i32)));
8433     } else if (isPowerOf2_32(MulAmt + 1)) {
8434       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8435       Res = DAG.getNode(ISD::SUB, DL, VT,
8436                         DAG.getNode(ISD::SHL, DL, VT,
8437                                     V,
8438                                     DAG.getConstant(Log2_32(MulAmt + 1), DL,
8439                                                     MVT::i32)),
8440                         V);
8441     } else
8442       return SDValue();
8443   } else {
8444     uint64_t MulAmtAbs = -MulAmt;
8445     if (isPowerOf2_32(MulAmtAbs + 1)) {
8446       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8447       Res = DAG.getNode(ISD::SUB, DL, VT,
8448                         V,
8449                         DAG.getNode(ISD::SHL, DL, VT,
8450                                     V,
8451                                     DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
8452                                                     MVT::i32)));
8453     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8454       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8455       Res = DAG.getNode(ISD::ADD, DL, VT,
8456                         V,
8457                         DAG.getNode(ISD::SHL, DL, VT,
8458                                     V,
8459                                     DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
8460                                                     MVT::i32)));
8461       Res = DAG.getNode(ISD::SUB, DL, VT,
8462                         DAG.getConstant(0, DL, MVT::i32), Res);
8463
8464     } else
8465       return SDValue();
8466   }
8467
8468   if (ShiftAmt != 0)
8469     Res = DAG.getNode(ISD::SHL, DL, VT,
8470                       Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
8471
8472   // Do not add new nodes to DAG combiner worklist.
8473   DCI.CombineTo(N, Res, false);
8474   return SDValue();
8475 }
8476
8477 static SDValue PerformANDCombine(SDNode *N,
8478                                  TargetLowering::DAGCombinerInfo &DCI,
8479                                  const ARMSubtarget *Subtarget) {
8480
8481   // Attempt to use immediate-form VBIC
8482   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8483   SDLoc dl(N);
8484   EVT VT = N->getValueType(0);
8485   SelectionDAG &DAG = DCI.DAG;
8486
8487   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8488     return SDValue();
8489
8490   APInt SplatBits, SplatUndef;
8491   unsigned SplatBitSize;
8492   bool HasAnyUndefs;
8493   if (BVN &&
8494       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8495     if (SplatBitSize <= 64) {
8496       EVT VbicVT;
8497       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8498                                       SplatUndef.getZExtValue(), SplatBitSize,
8499                                       DAG, dl, VbicVT, VT.is128BitVector(),
8500                                       OtherModImm);
8501       if (Val.getNode()) {
8502         SDValue Input =
8503           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8504         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8505         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8506       }
8507     }
8508   }
8509
8510   if (!Subtarget->isThumb1Only()) {
8511     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8512     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8513     if (Result.getNode())
8514       return Result;
8515   }
8516
8517   return SDValue();
8518 }
8519
8520 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8521 static SDValue PerformORCombine(SDNode *N,
8522                                 TargetLowering::DAGCombinerInfo &DCI,
8523                                 const ARMSubtarget *Subtarget) {
8524   // Attempt to use immediate-form VORR
8525   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8526   SDLoc dl(N);
8527   EVT VT = N->getValueType(0);
8528   SelectionDAG &DAG = DCI.DAG;
8529
8530   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8531     return SDValue();
8532
8533   APInt SplatBits, SplatUndef;
8534   unsigned SplatBitSize;
8535   bool HasAnyUndefs;
8536   if (BVN && Subtarget->hasNEON() &&
8537       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8538     if (SplatBitSize <= 64) {
8539       EVT VorrVT;
8540       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8541                                       SplatUndef.getZExtValue(), SplatBitSize,
8542                                       DAG, dl, VorrVT, VT.is128BitVector(),
8543                                       OtherModImm);
8544       if (Val.getNode()) {
8545         SDValue Input =
8546           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8547         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8548         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8549       }
8550     }
8551   }
8552
8553   if (!Subtarget->isThumb1Only()) {
8554     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8555     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8556     if (Result.getNode())
8557       return Result;
8558   }
8559
8560   // The code below optimizes (or (and X, Y), Z).
8561   // The AND operand needs to have a single user to make these optimizations
8562   // profitable.
8563   SDValue N0 = N->getOperand(0);
8564   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8565     return SDValue();
8566   SDValue N1 = N->getOperand(1);
8567
8568   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8569   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8570       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8571     APInt SplatUndef;
8572     unsigned SplatBitSize;
8573     bool HasAnyUndefs;
8574
8575     APInt SplatBits0, SplatBits1;
8576     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8577     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8578     // Ensure that the second operand of both ands are constants
8579     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8580                                       HasAnyUndefs) && !HasAnyUndefs) {
8581         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8582                                           HasAnyUndefs) && !HasAnyUndefs) {
8583             // Ensure that the bit width of the constants are the same and that
8584             // the splat arguments are logical inverses as per the pattern we
8585             // are trying to simplify.
8586             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8587                 SplatBits0 == ~SplatBits1) {
8588                 // Canonicalize the vector type to make instruction selection
8589                 // simpler.
8590                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8591                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8592                                              N0->getOperand(1),
8593                                              N0->getOperand(0),
8594                                              N1->getOperand(0));
8595                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8596             }
8597         }
8598     }
8599   }
8600
8601   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8602   // reasonable.
8603
8604   // BFI is only available on V6T2+
8605   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8606     return SDValue();
8607
8608   SDLoc DL(N);
8609   // 1) or (and A, mask), val => ARMbfi A, val, mask
8610   //      iff (val & mask) == val
8611   //
8612   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8613   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8614   //          && mask == ~mask2
8615   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8616   //          && ~mask == mask2
8617   //  (i.e., copy a bitfield value into another bitfield of the same width)
8618
8619   if (VT != MVT::i32)
8620     return SDValue();
8621
8622   SDValue N00 = N0.getOperand(0);
8623
8624   // The value and the mask need to be constants so we can verify this is
8625   // actually a bitfield set. If the mask is 0xffff, we can do better
8626   // via a movt instruction, so don't use BFI in that case.
8627   SDValue MaskOp = N0.getOperand(1);
8628   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8629   if (!MaskC)
8630     return SDValue();
8631   unsigned Mask = MaskC->getZExtValue();
8632   if (Mask == 0xffff)
8633     return SDValue();
8634   SDValue Res;
8635   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8636   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8637   if (N1C) {
8638     unsigned Val = N1C->getZExtValue();
8639     if ((Val & ~Mask) != Val)
8640       return SDValue();
8641
8642     if (ARM::isBitFieldInvertedMask(Mask)) {
8643       Val >>= countTrailingZeros(~Mask);
8644
8645       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8646                         DAG.getConstant(Val, DL, MVT::i32),
8647                         DAG.getConstant(Mask, DL, MVT::i32));
8648
8649       // Do not add new nodes to DAG combiner worklist.
8650       DCI.CombineTo(N, Res, false);
8651       return SDValue();
8652     }
8653   } else if (N1.getOpcode() == ISD::AND) {
8654     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8655     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8656     if (!N11C)
8657       return SDValue();
8658     unsigned Mask2 = N11C->getZExtValue();
8659
8660     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8661     // as is to match.
8662     if (ARM::isBitFieldInvertedMask(Mask) &&
8663         (Mask == ~Mask2)) {
8664       // The pack halfword instruction works better for masks that fit it,
8665       // so use that when it's available.
8666       if (Subtarget->hasT2ExtractPack() &&
8667           (Mask == 0xffff || Mask == 0xffff0000))
8668         return SDValue();
8669       // 2a
8670       unsigned amt = countTrailingZeros(Mask2);
8671       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8672                         DAG.getConstant(amt, DL, MVT::i32));
8673       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8674                         DAG.getConstant(Mask, DL, MVT::i32));
8675       // Do not add new nodes to DAG combiner worklist.
8676       DCI.CombineTo(N, Res, false);
8677       return SDValue();
8678     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8679                (~Mask == Mask2)) {
8680       // The pack halfword instruction works better for masks that fit it,
8681       // so use that when it's available.
8682       if (Subtarget->hasT2ExtractPack() &&
8683           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8684         return SDValue();
8685       // 2b
8686       unsigned lsb = countTrailingZeros(Mask);
8687       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8688                         DAG.getConstant(lsb, DL, MVT::i32));
8689       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8690                         DAG.getConstant(Mask2, DL, MVT::i32));
8691       // Do not add new nodes to DAG combiner worklist.
8692       DCI.CombineTo(N, Res, false);
8693       return SDValue();
8694     }
8695   }
8696
8697   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8698       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8699       ARM::isBitFieldInvertedMask(~Mask)) {
8700     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8701     // where lsb(mask) == #shamt and masked bits of B are known zero.
8702     SDValue ShAmt = N00.getOperand(1);
8703     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8704     unsigned LSB = countTrailingZeros(Mask);
8705     if (ShAmtC != LSB)
8706       return SDValue();
8707
8708     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8709                       DAG.getConstant(~Mask, DL, MVT::i32));
8710
8711     // Do not add new nodes to DAG combiner worklist.
8712     DCI.CombineTo(N, Res, false);
8713   }
8714
8715   return SDValue();
8716 }
8717
8718 static SDValue PerformXORCombine(SDNode *N,
8719                                  TargetLowering::DAGCombinerInfo &DCI,
8720                                  const ARMSubtarget *Subtarget) {
8721   EVT VT = N->getValueType(0);
8722   SelectionDAG &DAG = DCI.DAG;
8723
8724   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8725     return SDValue();
8726
8727   if (!Subtarget->isThumb1Only()) {
8728     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8729     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8730     if (Result.getNode())
8731       return Result;
8732   }
8733
8734   return SDValue();
8735 }
8736
8737 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8738 /// the bits being cleared by the AND are not demanded by the BFI.
8739 static SDValue PerformBFICombine(SDNode *N,
8740                                  TargetLowering::DAGCombinerInfo &DCI) {
8741   SDValue N1 = N->getOperand(1);
8742   if (N1.getOpcode() == ISD::AND) {
8743     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8744     if (!N11C)
8745       return SDValue();
8746     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8747     unsigned LSB = countTrailingZeros(~InvMask);
8748     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8749     assert(Width <
8750                static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
8751            "undefined behavior");
8752     unsigned Mask = (1u << Width) - 1;
8753     unsigned Mask2 = N11C->getZExtValue();
8754     if ((Mask & (~Mask2)) == 0)
8755       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8756                              N->getOperand(0), N1.getOperand(0),
8757                              N->getOperand(2));
8758   }
8759   return SDValue();
8760 }
8761
8762 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8763 /// ARMISD::VMOVRRD.
8764 static SDValue PerformVMOVRRDCombine(SDNode *N,
8765                                      TargetLowering::DAGCombinerInfo &DCI,
8766                                      const ARMSubtarget *Subtarget) {
8767   // vmovrrd(vmovdrr x, y) -> x,y
8768   SDValue InDouble = N->getOperand(0);
8769   if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
8770     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8771
8772   // vmovrrd(load f64) -> (load i32), (load i32)
8773   SDNode *InNode = InDouble.getNode();
8774   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8775       InNode->getValueType(0) == MVT::f64 &&
8776       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8777       !cast<LoadSDNode>(InNode)->isVolatile()) {
8778     // TODO: Should this be done for non-FrameIndex operands?
8779     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8780
8781     SelectionDAG &DAG = DCI.DAG;
8782     SDLoc DL(LD);
8783     SDValue BasePtr = LD->getBasePtr();
8784     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8785                                  LD->getPointerInfo(), LD->isVolatile(),
8786                                  LD->isNonTemporal(), LD->isInvariant(),
8787                                  LD->getAlignment());
8788
8789     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8790                                     DAG.getConstant(4, DL, MVT::i32));
8791     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8792                                  LD->getPointerInfo(), LD->isVolatile(),
8793                                  LD->isNonTemporal(), LD->isInvariant(),
8794                                  std::min(4U, LD->getAlignment() / 2));
8795
8796     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8797     if (DCI.DAG.getDataLayout().isBigEndian())
8798       std::swap (NewLD1, NewLD2);
8799     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8800     return Result;
8801   }
8802
8803   return SDValue();
8804 }
8805
8806 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8807 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8808 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8809   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8810   SDValue Op0 = N->getOperand(0);
8811   SDValue Op1 = N->getOperand(1);
8812   if (Op0.getOpcode() == ISD::BITCAST)
8813     Op0 = Op0.getOperand(0);
8814   if (Op1.getOpcode() == ISD::BITCAST)
8815     Op1 = Op1.getOperand(0);
8816   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8817       Op0.getNode() == Op1.getNode() &&
8818       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8819     return DAG.getNode(ISD::BITCAST, SDLoc(N),
8820                        N->getValueType(0), Op0.getOperand(0));
8821   return SDValue();
8822 }
8823
8824 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8825 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8826 /// i64 vector to have f64 elements, since the value can then be loaded
8827 /// directly into a VFP register.
8828 static bool hasNormalLoadOperand(SDNode *N) {
8829   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8830   for (unsigned i = 0; i < NumElts; ++i) {
8831     SDNode *Elt = N->getOperand(i).getNode();
8832     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8833       return true;
8834   }
8835   return false;
8836 }
8837
8838 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8839 /// ISD::BUILD_VECTOR.
8840 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8841                                           TargetLowering::DAGCombinerInfo &DCI,
8842                                           const ARMSubtarget *Subtarget) {
8843   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8844   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
8845   // into a pair of GPRs, which is fine when the value is used as a scalar,
8846   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8847   SelectionDAG &DAG = DCI.DAG;
8848   if (N->getNumOperands() == 2) {
8849     SDValue RV = PerformVMOVDRRCombine(N, DAG);
8850     if (RV.getNode())
8851       return RV;
8852   }
8853
8854   // Load i64 elements as f64 values so that type legalization does not split
8855   // them up into i32 values.
8856   EVT VT = N->getValueType(0);
8857   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8858     return SDValue();
8859   SDLoc dl(N);
8860   SmallVector<SDValue, 8> Ops;
8861   unsigned NumElts = VT.getVectorNumElements();
8862   for (unsigned i = 0; i < NumElts; ++i) {
8863     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8864     Ops.push_back(V);
8865     // Make the DAGCombiner fold the bitcast.
8866     DCI.AddToWorklist(V.getNode());
8867   }
8868   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8869   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8870   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8871 }
8872
8873 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8874 static SDValue
8875 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8876   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8877   // At that time, we may have inserted bitcasts from integer to float.
8878   // If these bitcasts have survived DAGCombine, change the lowering of this
8879   // BUILD_VECTOR in something more vector friendly, i.e., that does not
8880   // force to use floating point types.
8881
8882   // Make sure we can change the type of the vector.
8883   // This is possible iff:
8884   // 1. The vector is only used in a bitcast to a integer type. I.e.,
8885   //    1.1. Vector is used only once.
8886   //    1.2. Use is a bit convert to an integer type.
8887   // 2. The size of its operands are 32-bits (64-bits are not legal).
8888   EVT VT = N->getValueType(0);
8889   EVT EltVT = VT.getVectorElementType();
8890
8891   // Check 1.1. and 2.
8892   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8893     return SDValue();
8894
8895   // By construction, the input type must be float.
8896   assert(EltVT == MVT::f32 && "Unexpected type!");
8897
8898   // Check 1.2.
8899   SDNode *Use = *N->use_begin();
8900   if (Use->getOpcode() != ISD::BITCAST ||
8901       Use->getValueType(0).isFloatingPoint())
8902     return SDValue();
8903
8904   // Check profitability.
8905   // Model is, if more than half of the relevant operands are bitcast from
8906   // i32, turn the build_vector into a sequence of insert_vector_elt.
8907   // Relevant operands are everything that is not statically
8908   // (i.e., at compile time) bitcasted.
8909   unsigned NumOfBitCastedElts = 0;
8910   unsigned NumElts = VT.getVectorNumElements();
8911   unsigned NumOfRelevantElts = NumElts;
8912   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8913     SDValue Elt = N->getOperand(Idx);
8914     if (Elt->getOpcode() == ISD::BITCAST) {
8915       // Assume only bit cast to i32 will go away.
8916       if (Elt->getOperand(0).getValueType() == MVT::i32)
8917         ++NumOfBitCastedElts;
8918     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8919       // Constants are statically casted, thus do not count them as
8920       // relevant operands.
8921       --NumOfRelevantElts;
8922   }
8923
8924   // Check if more than half of the elements require a non-free bitcast.
8925   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8926     return SDValue();
8927
8928   SelectionDAG &DAG = DCI.DAG;
8929   // Create the new vector type.
8930   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8931   // Check if the type is legal.
8932   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8933   if (!TLI.isTypeLegal(VecVT))
8934     return SDValue();
8935
8936   // Combine:
8937   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8938   // => BITCAST INSERT_VECTOR_ELT
8939   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8940   //                      (BITCAST EN), N.
8941   SDValue Vec = DAG.getUNDEF(VecVT);
8942   SDLoc dl(N);
8943   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8944     SDValue V = N->getOperand(Idx);
8945     if (V.getOpcode() == ISD::UNDEF)
8946       continue;
8947     if (V.getOpcode() == ISD::BITCAST &&
8948         V->getOperand(0).getValueType() == MVT::i32)
8949       // Fold obvious case.
8950       V = V.getOperand(0);
8951     else {
8952       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
8953       // Make the DAGCombiner fold the bitcasts.
8954       DCI.AddToWorklist(V.getNode());
8955     }
8956     SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
8957     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8958   }
8959   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8960   // Make the DAGCombiner fold the bitcasts.
8961   DCI.AddToWorklist(Vec.getNode());
8962   return Vec;
8963 }
8964
8965 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8966 /// ISD::INSERT_VECTOR_ELT.
8967 static SDValue PerformInsertEltCombine(SDNode *N,
8968                                        TargetLowering::DAGCombinerInfo &DCI) {
8969   // Bitcast an i64 load inserted into a vector to f64.
8970   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8971   EVT VT = N->getValueType(0);
8972   SDNode *Elt = N->getOperand(1).getNode();
8973   if (VT.getVectorElementType() != MVT::i64 ||
8974       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8975     return SDValue();
8976
8977   SelectionDAG &DAG = DCI.DAG;
8978   SDLoc dl(N);
8979   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8980                                  VT.getVectorNumElements());
8981   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8982   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8983   // Make the DAGCombiner fold the bitcasts.
8984   DCI.AddToWorklist(Vec.getNode());
8985   DCI.AddToWorklist(V.getNode());
8986   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8987                                Vec, V, N->getOperand(2));
8988   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8989 }
8990
8991 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8992 /// ISD::VECTOR_SHUFFLE.
8993 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8994   // The LLVM shufflevector instruction does not require the shuffle mask
8995   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8996   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
8997   // operands do not match the mask length, they are extended by concatenating
8998   // them with undef vectors.  That is probably the right thing for other
8999   // targets, but for NEON it is better to concatenate two double-register
9000   // size vector operands into a single quad-register size vector.  Do that
9001   // transformation here:
9002   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
9003   //   shuffle(concat(v1, v2), undef)
9004   SDValue Op0 = N->getOperand(0);
9005   SDValue Op1 = N->getOperand(1);
9006   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
9007       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
9008       Op0.getNumOperands() != 2 ||
9009       Op1.getNumOperands() != 2)
9010     return SDValue();
9011   SDValue Concat0Op1 = Op0.getOperand(1);
9012   SDValue Concat1Op1 = Op1.getOperand(1);
9013   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
9014       Concat1Op1.getOpcode() != ISD::UNDEF)
9015     return SDValue();
9016   // Skip the transformation if any of the types are illegal.
9017   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9018   EVT VT = N->getValueType(0);
9019   if (!TLI.isTypeLegal(VT) ||
9020       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
9021       !TLI.isTypeLegal(Concat1Op1.getValueType()))
9022     return SDValue();
9023
9024   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
9025                                   Op0.getOperand(0), Op1.getOperand(0));
9026   // Translate the shuffle mask.
9027   SmallVector<int, 16> NewMask;
9028   unsigned NumElts = VT.getVectorNumElements();
9029   unsigned HalfElts = NumElts/2;
9030   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9031   for (unsigned n = 0; n < NumElts; ++n) {
9032     int MaskElt = SVN->getMaskElt(n);
9033     int NewElt = -1;
9034     if (MaskElt < (int)HalfElts)
9035       NewElt = MaskElt;
9036     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
9037       NewElt = HalfElts + MaskElt - NumElts;
9038     NewMask.push_back(NewElt);
9039   }
9040   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
9041                               DAG.getUNDEF(VT), NewMask.data());
9042 }
9043
9044 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
9045 /// NEON load/store intrinsics, and generic vector load/stores, to merge
9046 /// base address updates.
9047 /// For generic load/stores, the memory type is assumed to be a vector.
9048 /// The caller is assumed to have checked legality.
9049 static SDValue CombineBaseUpdate(SDNode *N,
9050                                  TargetLowering::DAGCombinerInfo &DCI) {
9051   SelectionDAG &DAG = DCI.DAG;
9052   const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9053                             N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9054   const bool isStore = N->getOpcode() == ISD::STORE;
9055   const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
9056   SDValue Addr = N->getOperand(AddrOpIdx);
9057   MemSDNode *MemN = cast<MemSDNode>(N);
9058   SDLoc dl(N);
9059
9060   // Search for a use of the address operand that is an increment.
9061   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9062          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9063     SDNode *User = *UI;
9064     if (User->getOpcode() != ISD::ADD ||
9065         UI.getUse().getResNo() != Addr.getResNo())
9066       continue;
9067
9068     // Check that the add is independent of the load/store.  Otherwise, folding
9069     // it would create a cycle.
9070     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9071       continue;
9072
9073     // Find the new opcode for the updating load/store.
9074     bool isLoadOp = true;
9075     bool isLaneOp = false;
9076     unsigned NewOpc = 0;
9077     unsigned NumVecs = 0;
9078     if (isIntrinsic) {
9079       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9080       switch (IntNo) {
9081       default: llvm_unreachable("unexpected intrinsic for Neon base update");
9082       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
9083         NumVecs = 1; break;
9084       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
9085         NumVecs = 2; break;
9086       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
9087         NumVecs = 3; break;
9088       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
9089         NumVecs = 4; break;
9090       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9091         NumVecs = 2; isLaneOp = true; break;
9092       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9093         NumVecs = 3; isLaneOp = true; break;
9094       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9095         NumVecs = 4; isLaneOp = true; break;
9096       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
9097         NumVecs = 1; isLoadOp = false; break;
9098       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
9099         NumVecs = 2; isLoadOp = false; break;
9100       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
9101         NumVecs = 3; isLoadOp = false; break;
9102       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
9103         NumVecs = 4; isLoadOp = false; break;
9104       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9105         NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
9106       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9107         NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
9108       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9109         NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
9110       }
9111     } else {
9112       isLaneOp = true;
9113       switch (N->getOpcode()) {
9114       default: llvm_unreachable("unexpected opcode for Neon base update");
9115       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9116       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9117       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9118       case ISD::LOAD:       NewOpc = ARMISD::VLD1_UPD;
9119         NumVecs = 1; isLaneOp = false; break;
9120       case ISD::STORE:      NewOpc = ARMISD::VST1_UPD;
9121         NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
9122       }
9123     }
9124
9125     // Find the size of memory referenced by the load/store.
9126     EVT VecTy;
9127     if (isLoadOp) {
9128       VecTy = N->getValueType(0);
9129     } else if (isIntrinsic) {
9130       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9131     } else {
9132       assert(isStore && "Node has to be a load, a store, or an intrinsic!");
9133       VecTy = N->getOperand(1).getValueType();
9134     }
9135
9136     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9137     if (isLaneOp)
9138       NumBytes /= VecTy.getVectorNumElements();
9139
9140     // If the increment is a constant, it must match the memory ref size.
9141     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9142     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9143       uint64_t IncVal = CInc->getZExtValue();
9144       if (IncVal != NumBytes)
9145         continue;
9146     } else if (NumBytes >= 3 * 16) {
9147       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9148       // separate instructions that make it harder to use a non-constant update.
9149       continue;
9150     }
9151
9152     // OK, we found an ADD we can fold into the base update.
9153     // Now, create a _UPD node, taking care of not breaking alignment.
9154
9155     EVT AlignedVecTy = VecTy;
9156     unsigned Alignment = MemN->getAlignment();
9157
9158     // If this is a less-than-standard-aligned load/store, change the type to
9159     // match the standard alignment.
9160     // The alignment is overlooked when selecting _UPD variants; and it's
9161     // easier to introduce bitcasts here than fix that.
9162     // There are 3 ways to get to this base-update combine:
9163     // - intrinsics: they are assumed to be properly aligned (to the standard
9164     //   alignment of the memory type), so we don't need to do anything.
9165     // - ARMISD::VLDx nodes: they are only generated from the aforementioned
9166     //   intrinsics, so, likewise, there's nothing to do.
9167     // - generic load/store instructions: the alignment is specified as an
9168     //   explicit operand, rather than implicitly as the standard alignment
9169     //   of the memory type (like the intrisics).  We need to change the
9170     //   memory type to match the explicit alignment.  That way, we don't
9171     //   generate non-standard-aligned ARMISD::VLDx nodes.
9172     if (isa<LSBaseSDNode>(N)) {
9173       if (Alignment == 0)
9174         Alignment = 1;
9175       if (Alignment < VecTy.getScalarSizeInBits() / 8) {
9176         MVT EltTy = MVT::getIntegerVT(Alignment * 8);
9177         assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
9178         assert(!isLaneOp && "Unexpected generic load/store lane.");
9179         unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
9180         AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
9181       }
9182       // Don't set an explicit alignment on regular load/stores that we want
9183       // to transform to VLD/VST 1_UPD nodes.
9184       // This matches the behavior of regular load/stores, which only get an
9185       // explicit alignment if the MMO alignment is larger than the standard
9186       // alignment of the memory type.
9187       // Intrinsics, however, always get an explicit alignment, set to the
9188       // alignment of the MMO.
9189       Alignment = 1;
9190     }
9191
9192     // Create the new updating load/store node.
9193     // First, create an SDVTList for the new updating node's results.
9194     EVT Tys[6];
9195     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
9196     unsigned n;
9197     for (n = 0; n < NumResultVecs; ++n)
9198       Tys[n] = AlignedVecTy;
9199     Tys[n++] = MVT::i32;
9200     Tys[n] = MVT::Other;
9201     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
9202
9203     // Then, gather the new node's operands.
9204     SmallVector<SDValue, 8> Ops;
9205     Ops.push_back(N->getOperand(0)); // incoming chain
9206     Ops.push_back(N->getOperand(AddrOpIdx));
9207     Ops.push_back(Inc);
9208
9209     if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
9210       // Try to match the intrinsic's signature
9211       Ops.push_back(StN->getValue());
9212     } else {
9213       // Loads (and of course intrinsics) match the intrinsics' signature,
9214       // so just add all but the alignment operand.
9215       for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
9216         Ops.push_back(N->getOperand(i));
9217     }
9218
9219     // For all node types, the alignment operand is always the last one.
9220     Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
9221
9222     // If this is a non-standard-aligned STORE, the penultimate operand is the
9223     // stored value.  Bitcast it to the aligned type.
9224     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
9225       SDValue &StVal = Ops[Ops.size()-2];
9226       StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
9227     }
9228
9229     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys,
9230                                            Ops, AlignedVecTy,
9231                                            MemN->getMemOperand());
9232
9233     // Update the uses.
9234     SmallVector<SDValue, 5> NewResults;
9235     for (unsigned i = 0; i < NumResultVecs; ++i)
9236       NewResults.push_back(SDValue(UpdN.getNode(), i));
9237
9238     // If this is an non-standard-aligned LOAD, the first result is the loaded
9239     // value.  Bitcast it to the expected result type.
9240     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
9241       SDValue &LdVal = NewResults[0];
9242       LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
9243     }
9244
9245     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9246     DCI.CombineTo(N, NewResults);
9247     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9248
9249     break;
9250   }
9251   return SDValue();
9252 }
9253
9254 static SDValue PerformVLDCombine(SDNode *N,
9255                                  TargetLowering::DAGCombinerInfo &DCI) {
9256   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9257     return SDValue();
9258
9259   return CombineBaseUpdate(N, DCI);
9260 }
9261
9262 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9263 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9264 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
9265 /// return true.
9266 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9267   SelectionDAG &DAG = DCI.DAG;
9268   EVT VT = N->getValueType(0);
9269   // vldN-dup instructions only support 64-bit vectors for N > 1.
9270   if (!VT.is64BitVector())
9271     return false;
9272
9273   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9274   SDNode *VLD = N->getOperand(0).getNode();
9275   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9276     return false;
9277   unsigned NumVecs = 0;
9278   unsigned NewOpc = 0;
9279   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9280   if (IntNo == Intrinsic::arm_neon_vld2lane) {
9281     NumVecs = 2;
9282     NewOpc = ARMISD::VLD2DUP;
9283   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9284     NumVecs = 3;
9285     NewOpc = ARMISD::VLD3DUP;
9286   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9287     NumVecs = 4;
9288     NewOpc = ARMISD::VLD4DUP;
9289   } else {
9290     return false;
9291   }
9292
9293   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9294   // numbers match the load.
9295   unsigned VLDLaneNo =
9296     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9297   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9298        UI != UE; ++UI) {
9299     // Ignore uses of the chain result.
9300     if (UI.getUse().getResNo() == NumVecs)
9301       continue;
9302     SDNode *User = *UI;
9303     if (User->getOpcode() != ARMISD::VDUPLANE ||
9304         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9305       return false;
9306   }
9307
9308   // Create the vldN-dup node.
9309   EVT Tys[5];
9310   unsigned n;
9311   for (n = 0; n < NumVecs; ++n)
9312     Tys[n] = VT;
9313   Tys[n] = MVT::Other;
9314   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9315   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9316   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9317   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9318                                            Ops, VLDMemInt->getMemoryVT(),
9319                                            VLDMemInt->getMemOperand());
9320
9321   // Update the uses.
9322   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9323        UI != UE; ++UI) {
9324     unsigned ResNo = UI.getUse().getResNo();
9325     // Ignore uses of the chain result.
9326     if (ResNo == NumVecs)
9327       continue;
9328     SDNode *User = *UI;
9329     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9330   }
9331
9332   // Now the vldN-lane intrinsic is dead except for its chain result.
9333   // Update uses of the chain.
9334   std::vector<SDValue> VLDDupResults;
9335   for (unsigned n = 0; n < NumVecs; ++n)
9336     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9337   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9338   DCI.CombineTo(VLD, VLDDupResults);
9339
9340   return true;
9341 }
9342
9343 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9344 /// ARMISD::VDUPLANE.
9345 static SDValue PerformVDUPLANECombine(SDNode *N,
9346                                       TargetLowering::DAGCombinerInfo &DCI) {
9347   SDValue Op = N->getOperand(0);
9348
9349   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9350   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9351   if (CombineVLDDUP(N, DCI))
9352     return SDValue(N, 0);
9353
9354   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9355   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9356   while (Op.getOpcode() == ISD::BITCAST)
9357     Op = Op.getOperand(0);
9358   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9359     return SDValue();
9360
9361   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9362   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9363   // The canonical VMOV for a zero vector uses a 32-bit element size.
9364   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9365   unsigned EltBits;
9366   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9367     EltSize = 8;
9368   EVT VT = N->getValueType(0);
9369   if (EltSize > VT.getVectorElementType().getSizeInBits())
9370     return SDValue();
9371
9372   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9373 }
9374
9375 static SDValue PerformLOADCombine(SDNode *N,
9376                                   TargetLowering::DAGCombinerInfo &DCI) {
9377   EVT VT = N->getValueType(0);
9378
9379   // If this is a legal vector load, try to combine it into a VLD1_UPD.
9380   if (ISD::isNormalLoad(N) && VT.isVector() &&
9381       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9382     return CombineBaseUpdate(N, DCI);
9383
9384   return SDValue();
9385 }
9386
9387 /// PerformSTORECombine - Target-specific dag combine xforms for
9388 /// ISD::STORE.
9389 static SDValue PerformSTORECombine(SDNode *N,
9390                                    TargetLowering::DAGCombinerInfo &DCI) {
9391   StoreSDNode *St = cast<StoreSDNode>(N);
9392   if (St->isVolatile())
9393     return SDValue();
9394
9395   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
9396   // pack all of the elements in one place.  Next, store to memory in fewer
9397   // chunks.
9398   SDValue StVal = St->getValue();
9399   EVT VT = StVal.getValueType();
9400   if (St->isTruncatingStore() && VT.isVector()) {
9401     SelectionDAG &DAG = DCI.DAG;
9402     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9403     EVT StVT = St->getMemoryVT();
9404     unsigned NumElems = VT.getVectorNumElements();
9405     assert(StVT != VT && "Cannot truncate to the same type");
9406     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
9407     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
9408
9409     // From, To sizes and ElemCount must be pow of two
9410     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
9411
9412     // We are going to use the original vector elt for storing.
9413     // Accumulated smaller vector elements must be a multiple of the store size.
9414     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
9415
9416     unsigned SizeRatio  = FromEltSz / ToEltSz;
9417     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
9418
9419     // Create a type on which we perform the shuffle.
9420     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9421                                      NumElems*SizeRatio);
9422     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9423
9424     SDLoc DL(St);
9425     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9426     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9427     for (unsigned i = 0; i < NumElems; ++i)
9428       ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
9429                           ? (i + 1) * SizeRatio - 1
9430                           : i * SizeRatio;
9431
9432     // Can't shuffle using an illegal type.
9433     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9434
9435     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9436                                 DAG.getUNDEF(WideVec.getValueType()),
9437                                 ShuffleVec.data());
9438     // At this point all of the data is stored at the bottom of the
9439     // register. We now need to save it to mem.
9440
9441     // Find the largest store unit
9442     MVT StoreType = MVT::i8;
9443     for (MVT Tp : MVT::integer_valuetypes()) {
9444       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9445         StoreType = Tp;
9446     }
9447     // Didn't find a legal store type.
9448     if (!TLI.isTypeLegal(StoreType))
9449       return SDValue();
9450
9451     // Bitcast the original vector into a vector of store-size units
9452     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9453             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9454     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9455     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9456     SmallVector<SDValue, 8> Chains;
9457     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
9458                                         TLI.getPointerTy(DAG.getDataLayout()));
9459     SDValue BasePtr = St->getBasePtr();
9460
9461     // Perform one or more big stores into memory.
9462     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9463     for (unsigned I = 0; I < E; I++) {
9464       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9465                                    StoreType, ShuffWide,
9466                                    DAG.getIntPtrConstant(I, DL));
9467       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9468                                 St->getPointerInfo(), St->isVolatile(),
9469                                 St->isNonTemporal(), St->getAlignment());
9470       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9471                             Increment);
9472       Chains.push_back(Ch);
9473     }
9474     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
9475   }
9476
9477   if (!ISD::isNormalStore(St))
9478     return SDValue();
9479
9480   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9481   // ARM stores of arguments in the same cache line.
9482   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9483       StVal.getNode()->hasOneUse()) {
9484     SelectionDAG  &DAG = DCI.DAG;
9485     bool isBigEndian = DAG.getDataLayout().isBigEndian();
9486     SDLoc DL(St);
9487     SDValue BasePtr = St->getBasePtr();
9488     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9489                                   StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
9490                                   BasePtr, St->getPointerInfo(), St->isVolatile(),
9491                                   St->isNonTemporal(), St->getAlignment());
9492
9493     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9494                                     DAG.getConstant(4, DL, MVT::i32));
9495     return DAG.getStore(NewST1.getValue(0), DL,
9496                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
9497                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9498                         St->isNonTemporal(),
9499                         std::min(4U, St->getAlignment() / 2));
9500   }
9501
9502   if (StVal.getValueType() == MVT::i64 &&
9503       StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9504
9505     // Bitcast an i64 store extracted from a vector to f64.
9506     // Otherwise, the i64 value will be legalized to a pair of i32 values.
9507     SelectionDAG &DAG = DCI.DAG;
9508     SDLoc dl(StVal);
9509     SDValue IntVec = StVal.getOperand(0);
9510     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9511                                    IntVec.getValueType().getVectorNumElements());
9512     SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9513     SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9514                                  Vec, StVal.getOperand(1));
9515     dl = SDLoc(N);
9516     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9517     // Make the DAGCombiner fold the bitcasts.
9518     DCI.AddToWorklist(Vec.getNode());
9519     DCI.AddToWorklist(ExtElt.getNode());
9520     DCI.AddToWorklist(V.getNode());
9521     return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9522                         St->getPointerInfo(), St->isVolatile(),
9523                         St->isNonTemporal(), St->getAlignment(),
9524                         St->getAAInfo());
9525   }
9526
9527   // If this is a legal vector store, try to combine it into a VST1_UPD.
9528   if (ISD::isNormalStore(N) && VT.isVector() &&
9529       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9530     return CombineBaseUpdate(N, DCI);
9531
9532   return SDValue();
9533 }
9534
9535 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9536 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9537 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9538 {
9539   integerPart cN;
9540   integerPart c0 = 0;
9541   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9542        I != E; I++) {
9543     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9544     if (!C)
9545       return false;
9546
9547     bool isExact;
9548     APFloat APF = C->getValueAPF();
9549     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9550         != APFloat::opOK || !isExact)
9551       return false;
9552
9553     c0 = (I == 0) ? cN : c0;
9554     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9555       return false;
9556   }
9557   C = c0;
9558   return true;
9559 }
9560
9561 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9562 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9563 /// when the VMUL has a constant operand that is a power of 2.
9564 ///
9565 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9566 ///  vmul.f32        d16, d17, d16
9567 ///  vcvt.s32.f32    d16, d16
9568 /// becomes:
9569 ///  vcvt.s32.f32    d16, d16, #3
9570 static SDValue PerformVCVTCombine(SDNode *N,
9571                                   TargetLowering::DAGCombinerInfo &DCI,
9572                                   const ARMSubtarget *Subtarget) {
9573   SelectionDAG &DAG = DCI.DAG;
9574   SDValue Op = N->getOperand(0);
9575
9576   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9577       Op.getOpcode() != ISD::FMUL)
9578     return SDValue();
9579
9580   uint64_t C;
9581   SDValue N0 = Op->getOperand(0);
9582   SDValue ConstVec = Op->getOperand(1);
9583   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9584
9585   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9586       !isConstVecPow2(ConstVec, isSigned, C))
9587     return SDValue();
9588
9589   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9590   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9591   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9592   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32 ||
9593       NumLanes > 4) {
9594     // These instructions only exist converting from f32 to i32. We can handle
9595     // smaller integers by generating an extra truncate, but larger ones would
9596     // be lossy. We also can't handle more then 4 lanes, since these intructions
9597     // only support v2i32/v4i32 types.
9598     return SDValue();
9599   }
9600
9601   SDLoc dl(N);
9602   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9603     Intrinsic::arm_neon_vcvtfp2fxu;
9604   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9605                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9606                                  DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9607                                  N0,
9608                                  DAG.getConstant(Log2_64(C), dl, MVT::i32));
9609
9610   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9611     FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
9612
9613   return FixConv;
9614 }
9615
9616 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9617 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9618 /// when the VDIV has a constant operand that is a power of 2.
9619 ///
9620 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9621 ///  vcvt.f32.s32    d16, d16
9622 ///  vdiv.f32        d16, d17, d16
9623 /// becomes:
9624 ///  vcvt.f32.s32    d16, d16, #3
9625 static SDValue PerformVDIVCombine(SDNode *N,
9626                                   TargetLowering::DAGCombinerInfo &DCI,
9627                                   const ARMSubtarget *Subtarget) {
9628   SelectionDAG &DAG = DCI.DAG;
9629   SDValue Op = N->getOperand(0);
9630   unsigned OpOpcode = Op.getNode()->getOpcode();
9631
9632   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9633       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9634     return SDValue();
9635
9636   uint64_t C;
9637   SDValue ConstVec = N->getOperand(1);
9638   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9639
9640   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9641       !isConstVecPow2(ConstVec, isSigned, C))
9642     return SDValue();
9643
9644   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9645   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9646   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9647     // These instructions only exist converting from i32 to f32. We can handle
9648     // smaller integers by generating an extra extend, but larger ones would
9649     // be lossy.
9650     return SDValue();
9651   }
9652
9653   SDLoc dl(N);
9654   SDValue ConvInput = Op.getOperand(0);
9655   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9656   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9657     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9658                             dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9659                             ConvInput);
9660
9661   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9662     Intrinsic::arm_neon_vcvtfxu2fp;
9663   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9664                      Op.getValueType(),
9665                      DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9666                      ConvInput, DAG.getConstant(Log2_64(C), dl, MVT::i32));
9667 }
9668
9669 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9670 /// operand of a vector shift operation, where all the elements of the
9671 /// build_vector must have the same constant integer value.
9672 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9673   // Ignore bit_converts.
9674   while (Op.getOpcode() == ISD::BITCAST)
9675     Op = Op.getOperand(0);
9676   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9677   APInt SplatBits, SplatUndef;
9678   unsigned SplatBitSize;
9679   bool HasAnyUndefs;
9680   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9681                                       HasAnyUndefs, ElementBits) ||
9682       SplatBitSize > ElementBits)
9683     return false;
9684   Cnt = SplatBits.getSExtValue();
9685   return true;
9686 }
9687
9688 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9689 /// operand of a vector shift left operation.  That value must be in the range:
9690 ///   0 <= Value < ElementBits for a left shift; or
9691 ///   0 <= Value <= ElementBits for a long left shift.
9692 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9693   assert(VT.isVector() && "vector shift count is not a vector type");
9694   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
9695   if (! getVShiftImm(Op, ElementBits, Cnt))
9696     return false;
9697   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9698 }
9699
9700 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9701 /// operand of a vector shift right operation.  For a shift opcode, the value
9702 /// is positive, but for an intrinsic the value count must be negative. The
9703 /// absolute value must be in the range:
9704 ///   1 <= |Value| <= ElementBits for a right shift; or
9705 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9706 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9707                          int64_t &Cnt) {
9708   assert(VT.isVector() && "vector shift count is not a vector type");
9709   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
9710   if (! getVShiftImm(Op, ElementBits, Cnt))
9711     return false;
9712   if (!isIntrinsic)
9713     return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9714   if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) {
9715     Cnt = -Cnt;
9716     return true;
9717   }
9718   return false;
9719 }
9720
9721 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9722 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9723   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9724   switch (IntNo) {
9725   default:
9726     // Don't do anything for most intrinsics.
9727     break;
9728
9729   case Intrinsic::arm_neon_vabds:
9730     if (!N->getValueType(0).isInteger())
9731       return SDValue();
9732     return DAG.getNode(ISD::SABSDIFF, SDLoc(N), N->getValueType(0),
9733                        N->getOperand(1), N->getOperand(2));
9734   case Intrinsic::arm_neon_vabdu:
9735     return DAG.getNode(ISD::UABSDIFF, SDLoc(N), N->getValueType(0),
9736                        N->getOperand(1), N->getOperand(2));
9737
9738   // Vector shifts: check for immediate versions and lower them.
9739   // Note: This is done during DAG combining instead of DAG legalizing because
9740   // the build_vectors for 64-bit vector element shift counts are generally
9741   // not legal, and it is hard to see their values after they get legalized to
9742   // loads from a constant pool.
9743   case Intrinsic::arm_neon_vshifts:
9744   case Intrinsic::arm_neon_vshiftu:
9745   case Intrinsic::arm_neon_vrshifts:
9746   case Intrinsic::arm_neon_vrshiftu:
9747   case Intrinsic::arm_neon_vrshiftn:
9748   case Intrinsic::arm_neon_vqshifts:
9749   case Intrinsic::arm_neon_vqshiftu:
9750   case Intrinsic::arm_neon_vqshiftsu:
9751   case Intrinsic::arm_neon_vqshiftns:
9752   case Intrinsic::arm_neon_vqshiftnu:
9753   case Intrinsic::arm_neon_vqshiftnsu:
9754   case Intrinsic::arm_neon_vqrshiftns:
9755   case Intrinsic::arm_neon_vqrshiftnu:
9756   case Intrinsic::arm_neon_vqrshiftnsu: {
9757     EVT VT = N->getOperand(1).getValueType();
9758     int64_t Cnt;
9759     unsigned VShiftOpc = 0;
9760
9761     switch (IntNo) {
9762     case Intrinsic::arm_neon_vshifts:
9763     case Intrinsic::arm_neon_vshiftu:
9764       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9765         VShiftOpc = ARMISD::VSHL;
9766         break;
9767       }
9768       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9769         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9770                      ARMISD::VSHRs : ARMISD::VSHRu);
9771         break;
9772       }
9773       return SDValue();
9774
9775     case Intrinsic::arm_neon_vrshifts:
9776     case Intrinsic::arm_neon_vrshiftu:
9777       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9778         break;
9779       return SDValue();
9780
9781     case Intrinsic::arm_neon_vqshifts:
9782     case Intrinsic::arm_neon_vqshiftu:
9783       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9784         break;
9785       return SDValue();
9786
9787     case Intrinsic::arm_neon_vqshiftsu:
9788       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9789         break;
9790       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9791
9792     case Intrinsic::arm_neon_vrshiftn:
9793     case Intrinsic::arm_neon_vqshiftns:
9794     case Intrinsic::arm_neon_vqshiftnu:
9795     case Intrinsic::arm_neon_vqshiftnsu:
9796     case Intrinsic::arm_neon_vqrshiftns:
9797     case Intrinsic::arm_neon_vqrshiftnu:
9798     case Intrinsic::arm_neon_vqrshiftnsu:
9799       // Narrowing shifts require an immediate right shift.
9800       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9801         break;
9802       llvm_unreachable("invalid shift count for narrowing vector shift "
9803                        "intrinsic");
9804
9805     default:
9806       llvm_unreachable("unhandled vector shift");
9807     }
9808
9809     switch (IntNo) {
9810     case Intrinsic::arm_neon_vshifts:
9811     case Intrinsic::arm_neon_vshiftu:
9812       // Opcode already set above.
9813       break;
9814     case Intrinsic::arm_neon_vrshifts:
9815       VShiftOpc = ARMISD::VRSHRs; break;
9816     case Intrinsic::arm_neon_vrshiftu:
9817       VShiftOpc = ARMISD::VRSHRu; break;
9818     case Intrinsic::arm_neon_vrshiftn:
9819       VShiftOpc = ARMISD::VRSHRN; break;
9820     case Intrinsic::arm_neon_vqshifts:
9821       VShiftOpc = ARMISD::VQSHLs; break;
9822     case Intrinsic::arm_neon_vqshiftu:
9823       VShiftOpc = ARMISD::VQSHLu; break;
9824     case Intrinsic::arm_neon_vqshiftsu:
9825       VShiftOpc = ARMISD::VQSHLsu; break;
9826     case Intrinsic::arm_neon_vqshiftns:
9827       VShiftOpc = ARMISD::VQSHRNs; break;
9828     case Intrinsic::arm_neon_vqshiftnu:
9829       VShiftOpc = ARMISD::VQSHRNu; break;
9830     case Intrinsic::arm_neon_vqshiftnsu:
9831       VShiftOpc = ARMISD::VQSHRNsu; break;
9832     case Intrinsic::arm_neon_vqrshiftns:
9833       VShiftOpc = ARMISD::VQRSHRNs; break;
9834     case Intrinsic::arm_neon_vqrshiftnu:
9835       VShiftOpc = ARMISD::VQRSHRNu; break;
9836     case Intrinsic::arm_neon_vqrshiftnsu:
9837       VShiftOpc = ARMISD::VQRSHRNsu; break;
9838     }
9839
9840     SDLoc dl(N);
9841     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
9842                        N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
9843   }
9844
9845   case Intrinsic::arm_neon_vshiftins: {
9846     EVT VT = N->getOperand(1).getValueType();
9847     int64_t Cnt;
9848     unsigned VShiftOpc = 0;
9849
9850     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9851       VShiftOpc = ARMISD::VSLI;
9852     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9853       VShiftOpc = ARMISD::VSRI;
9854     else {
9855       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9856     }
9857
9858     SDLoc dl(N);
9859     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
9860                        N->getOperand(1), N->getOperand(2),
9861                        DAG.getConstant(Cnt, dl, MVT::i32));
9862   }
9863
9864   case Intrinsic::arm_neon_vqrshifts:
9865   case Intrinsic::arm_neon_vqrshiftu:
9866     // No immediate versions of these to check for.
9867     break;
9868   }
9869
9870   return SDValue();
9871 }
9872
9873 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9874 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9875 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9876 /// vector element shift counts are generally not legal, and it is hard to see
9877 /// their values after they get legalized to loads from a constant pool.
9878 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9879                                    const ARMSubtarget *ST) {
9880   EVT VT = N->getValueType(0);
9881   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9882     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9883     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9884     SDValue N1 = N->getOperand(1);
9885     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9886       SDValue N0 = N->getOperand(0);
9887       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9888           DAG.MaskedValueIsZero(N0.getOperand(0),
9889                                 APInt::getHighBitsSet(32, 16)))
9890         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9891     }
9892   }
9893
9894   // Nothing to be done for scalar shifts.
9895   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9896   if (!VT.isVector() || !TLI.isTypeLegal(VT))
9897     return SDValue();
9898
9899   assert(ST->hasNEON() && "unexpected vector shift");
9900   int64_t Cnt;
9901
9902   switch (N->getOpcode()) {
9903   default: llvm_unreachable("unexpected shift opcode");
9904
9905   case ISD::SHL:
9906     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
9907       SDLoc dl(N);
9908       return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
9909                          DAG.getConstant(Cnt, dl, MVT::i32));
9910     }
9911     break;
9912
9913   case ISD::SRA:
9914   case ISD::SRL:
9915     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9916       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9917                             ARMISD::VSHRs : ARMISD::VSHRu);
9918       SDLoc dl(N);
9919       return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
9920                          DAG.getConstant(Cnt, dl, MVT::i32));
9921     }
9922   }
9923   return SDValue();
9924 }
9925
9926 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9927 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9928 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9929                                     const ARMSubtarget *ST) {
9930   SDValue N0 = N->getOperand(0);
9931
9932   // Check for sign- and zero-extensions of vector extract operations of 8-
9933   // and 16-bit vector elements.  NEON supports these directly.  They are
9934   // handled during DAG combining because type legalization will promote them
9935   // to 32-bit types and it is messy to recognize the operations after that.
9936   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9937     SDValue Vec = N0.getOperand(0);
9938     SDValue Lane = N0.getOperand(1);
9939     EVT VT = N->getValueType(0);
9940     EVT EltVT = N0.getValueType();
9941     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9942
9943     if (VT == MVT::i32 &&
9944         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9945         TLI.isTypeLegal(Vec.getValueType()) &&
9946         isa<ConstantSDNode>(Lane)) {
9947
9948       unsigned Opc = 0;
9949       switch (N->getOpcode()) {
9950       default: llvm_unreachable("unexpected opcode");
9951       case ISD::SIGN_EXTEND:
9952         Opc = ARMISD::VGETLANEs;
9953         break;
9954       case ISD::ZERO_EXTEND:
9955       case ISD::ANY_EXTEND:
9956         Opc = ARMISD::VGETLANEu;
9957         break;
9958       }
9959       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9960     }
9961   }
9962
9963   return SDValue();
9964 }
9965
9966 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9967 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9968 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9969                                        const ARMSubtarget *ST) {
9970   // If the target supports NEON, try to use vmax/vmin instructions for f32
9971   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
9972   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
9973   // a NaN; only do the transformation when it matches that behavior.
9974
9975   // For now only do this when using NEON for FP operations; if using VFP, it
9976   // is not obvious that the benefit outweighs the cost of switching to the
9977   // NEON pipeline.
9978   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9979       N->getValueType(0) != MVT::f32)
9980     return SDValue();
9981
9982   SDValue CondLHS = N->getOperand(0);
9983   SDValue CondRHS = N->getOperand(1);
9984   SDValue LHS = N->getOperand(2);
9985   SDValue RHS = N->getOperand(3);
9986   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9987
9988   unsigned Opcode = 0;
9989   bool IsReversed;
9990   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9991     IsReversed = false; // x CC y ? x : y
9992   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9993     IsReversed = true ; // x CC y ? y : x
9994   } else {
9995     return SDValue();
9996   }
9997
9998   bool IsUnordered;
9999   switch (CC) {
10000   default: break;
10001   case ISD::SETOLT:
10002   case ISD::SETOLE:
10003   case ISD::SETLT:
10004   case ISD::SETLE:
10005   case ISD::SETULT:
10006   case ISD::SETULE:
10007     // If LHS is NaN, an ordered comparison will be false and the result will
10008     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
10009     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
10010     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
10011     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
10012       break;
10013     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
10014     // will return -0, so vmin can only be used for unsafe math or if one of
10015     // the operands is known to be nonzero.
10016     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
10017         !DAG.getTarget().Options.UnsafeFPMath &&
10018         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10019       break;
10020     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
10021     break;
10022
10023   case ISD::SETOGT:
10024   case ISD::SETOGE:
10025   case ISD::SETGT:
10026   case ISD::SETGE:
10027   case ISD::SETUGT:
10028   case ISD::SETUGE:
10029     // If LHS is NaN, an ordered comparison will be false and the result will
10030     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
10031     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
10032     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
10033     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
10034       break;
10035     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
10036     // will return +0, so vmax can only be used for unsafe math or if one of
10037     // the operands is known to be nonzero.
10038     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
10039         !DAG.getTarget().Options.UnsafeFPMath &&
10040         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10041       break;
10042     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
10043     break;
10044   }
10045
10046   if (!Opcode)
10047     return SDValue();
10048   return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
10049 }
10050
10051 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
10052 SDValue
10053 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
10054   SDValue Cmp = N->getOperand(4);
10055   if (Cmp.getOpcode() != ARMISD::CMPZ)
10056     // Only looking at EQ and NE cases.
10057     return SDValue();
10058
10059   EVT VT = N->getValueType(0);
10060   SDLoc dl(N);
10061   SDValue LHS = Cmp.getOperand(0);
10062   SDValue RHS = Cmp.getOperand(1);
10063   SDValue FalseVal = N->getOperand(0);
10064   SDValue TrueVal = N->getOperand(1);
10065   SDValue ARMcc = N->getOperand(2);
10066   ARMCC::CondCodes CC =
10067     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
10068
10069   // Simplify
10070   //   mov     r1, r0
10071   //   cmp     r1, x
10072   //   mov     r0, y
10073   //   moveq   r0, x
10074   // to
10075   //   cmp     r0, x
10076   //   movne   r0, y
10077   //
10078   //   mov     r1, r0
10079   //   cmp     r1, x
10080   //   mov     r0, x
10081   //   movne   r0, y
10082   // to
10083   //   cmp     r0, x
10084   //   movne   r0, y
10085   /// FIXME: Turn this into a target neutral optimization?
10086   SDValue Res;
10087   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
10088     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
10089                       N->getOperand(3), Cmp);
10090   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
10091     SDValue ARMcc;
10092     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
10093     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
10094                       N->getOperand(3), NewCmp);
10095   }
10096
10097   if (Res.getNode()) {
10098     APInt KnownZero, KnownOne;
10099     DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
10100     // Capture demanded bits information that would be otherwise lost.
10101     if (KnownZero == 0xfffffffe)
10102       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10103                         DAG.getValueType(MVT::i1));
10104     else if (KnownZero == 0xffffff00)
10105       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10106                         DAG.getValueType(MVT::i8));
10107     else if (KnownZero == 0xffff0000)
10108       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10109                         DAG.getValueType(MVT::i16));
10110   }
10111
10112   return Res;
10113 }
10114
10115 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
10116                                              DAGCombinerInfo &DCI) const {
10117   switch (N->getOpcode()) {
10118   default: break;
10119   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
10120   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
10121   case ISD::SUB:        return PerformSUBCombine(N, DCI);
10122   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
10123   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
10124   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
10125   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
10126   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
10127   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
10128   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
10129   case ISD::STORE:      return PerformSTORECombine(N, DCI);
10130   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
10131   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
10132   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
10133   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
10134   case ISD::FP_TO_SINT:
10135   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
10136   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
10137   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
10138   case ISD::SHL:
10139   case ISD::SRA:
10140   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
10141   case ISD::SIGN_EXTEND:
10142   case ISD::ZERO_EXTEND:
10143   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
10144   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
10145   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
10146   case ISD::LOAD:       return PerformLOADCombine(N, DCI);
10147   case ARMISD::VLD2DUP:
10148   case ARMISD::VLD3DUP:
10149   case ARMISD::VLD4DUP:
10150     return PerformVLDCombine(N, DCI);
10151   case ARMISD::BUILD_VECTOR:
10152     return PerformARMBUILD_VECTORCombine(N, DCI);
10153   case ISD::INTRINSIC_VOID:
10154   case ISD::INTRINSIC_W_CHAIN:
10155     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10156     case Intrinsic::arm_neon_vld1:
10157     case Intrinsic::arm_neon_vld2:
10158     case Intrinsic::arm_neon_vld3:
10159     case Intrinsic::arm_neon_vld4:
10160     case Intrinsic::arm_neon_vld2lane:
10161     case Intrinsic::arm_neon_vld3lane:
10162     case Intrinsic::arm_neon_vld4lane:
10163     case Intrinsic::arm_neon_vst1:
10164     case Intrinsic::arm_neon_vst2:
10165     case Intrinsic::arm_neon_vst3:
10166     case Intrinsic::arm_neon_vst4:
10167     case Intrinsic::arm_neon_vst2lane:
10168     case Intrinsic::arm_neon_vst3lane:
10169     case Intrinsic::arm_neon_vst4lane:
10170       return PerformVLDCombine(N, DCI);
10171     default: break;
10172     }
10173     break;
10174   }
10175   return SDValue();
10176 }
10177
10178 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
10179                                                           EVT VT) const {
10180   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
10181 }
10182
10183 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
10184                                                        unsigned,
10185                                                        unsigned,
10186                                                        bool *Fast) const {
10187   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
10188   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
10189
10190   switch (VT.getSimpleVT().SimpleTy) {
10191   default:
10192     return false;
10193   case MVT::i8:
10194   case MVT::i16:
10195   case MVT::i32: {
10196     // Unaligned access can use (for example) LRDB, LRDH, LDR
10197     if (AllowsUnaligned) {
10198       if (Fast)
10199         *Fast = Subtarget->hasV7Ops();
10200       return true;
10201     }
10202     return false;
10203   }
10204   case MVT::f64:
10205   case MVT::v2f64: {
10206     // For any little-endian targets with neon, we can support unaligned ld/st
10207     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10208     // A big-endian target may also explicitly support unaligned accesses
10209     if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
10210       if (Fast)
10211         *Fast = true;
10212       return true;
10213     }
10214     return false;
10215   }
10216   }
10217 }
10218
10219 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10220                        unsigned AlignCheck) {
10221   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10222           (DstAlign == 0 || DstAlign % AlignCheck == 0));
10223 }
10224
10225 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10226                                            unsigned DstAlign, unsigned SrcAlign,
10227                                            bool IsMemset, bool ZeroMemset,
10228                                            bool MemcpyStrSrc,
10229                                            MachineFunction &MF) const {
10230   const Function *F = MF.getFunction();
10231
10232   // See if we can use NEON instructions for this...
10233   if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
10234       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10235     bool Fast;
10236     if (Size >= 16 &&
10237         (memOpAlign(SrcAlign, DstAlign, 16) ||
10238          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
10239       return MVT::v2f64;
10240     } else if (Size >= 8 &&
10241                (memOpAlign(SrcAlign, DstAlign, 8) ||
10242                 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
10243                  Fast))) {
10244       return MVT::f64;
10245     }
10246   }
10247
10248   // Lowering to i32/i16 if the size permits.
10249   if (Size >= 4)
10250     return MVT::i32;
10251   else if (Size >= 2)
10252     return MVT::i16;
10253
10254   // Let the target-independent logic figure it out.
10255   return MVT::Other;
10256 }
10257
10258 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10259   if (Val.getOpcode() != ISD::LOAD)
10260     return false;
10261
10262   EVT VT1 = Val.getValueType();
10263   if (!VT1.isSimple() || !VT1.isInteger() ||
10264       !VT2.isSimple() || !VT2.isInteger())
10265     return false;
10266
10267   switch (VT1.getSimpleVT().SimpleTy) {
10268   default: break;
10269   case MVT::i1:
10270   case MVT::i8:
10271   case MVT::i16:
10272     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10273     return true;
10274   }
10275
10276   return false;
10277 }
10278
10279 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
10280   EVT VT = ExtVal.getValueType();
10281
10282   if (!isTypeLegal(VT))
10283     return false;
10284
10285   // Don't create a loadext if we can fold the extension into a wide/long
10286   // instruction.
10287   // If there's more than one user instruction, the loadext is desirable no
10288   // matter what.  There can be two uses by the same instruction.
10289   if (ExtVal->use_empty() ||
10290       !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
10291     return true;
10292
10293   SDNode *U = *ExtVal->use_begin();
10294   if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
10295        U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
10296     return false;
10297
10298   return true;
10299 }
10300
10301 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10302   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10303     return false;
10304
10305   if (!isTypeLegal(EVT::getEVT(Ty1)))
10306     return false;
10307
10308   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10309
10310   // Assuming the caller doesn't have a zeroext or signext return parameter,
10311   // truncation all the way down to i1 is valid.
10312   return true;
10313 }
10314
10315
10316 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10317   if (V < 0)
10318     return false;
10319
10320   unsigned Scale = 1;
10321   switch (VT.getSimpleVT().SimpleTy) {
10322   default: return false;
10323   case MVT::i1:
10324   case MVT::i8:
10325     // Scale == 1;
10326     break;
10327   case MVT::i16:
10328     // Scale == 2;
10329     Scale = 2;
10330     break;
10331   case MVT::i32:
10332     // Scale == 4;
10333     Scale = 4;
10334     break;
10335   }
10336
10337   if ((V & (Scale - 1)) != 0)
10338     return false;
10339   V /= Scale;
10340   return V == (V & ((1LL << 5) - 1));
10341 }
10342
10343 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10344                                       const ARMSubtarget *Subtarget) {
10345   bool isNeg = false;
10346   if (V < 0) {
10347     isNeg = true;
10348     V = - V;
10349   }
10350
10351   switch (VT.getSimpleVT().SimpleTy) {
10352   default: return false;
10353   case MVT::i1:
10354   case MVT::i8:
10355   case MVT::i16:
10356   case MVT::i32:
10357     // + imm12 or - imm8
10358     if (isNeg)
10359       return V == (V & ((1LL << 8) - 1));
10360     return V == (V & ((1LL << 12) - 1));
10361   case MVT::f32:
10362   case MVT::f64:
10363     // Same as ARM mode. FIXME: NEON?
10364     if (!Subtarget->hasVFP2())
10365       return false;
10366     if ((V & 3) != 0)
10367       return false;
10368     V >>= 2;
10369     return V == (V & ((1LL << 8) - 1));
10370   }
10371 }
10372
10373 /// isLegalAddressImmediate - Return true if the integer value can be used
10374 /// as the offset of the target addressing mode for load / store of the
10375 /// given type.
10376 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10377                                     const ARMSubtarget *Subtarget) {
10378   if (V == 0)
10379     return true;
10380
10381   if (!VT.isSimple())
10382     return false;
10383
10384   if (Subtarget->isThumb1Only())
10385     return isLegalT1AddressImmediate(V, VT);
10386   else if (Subtarget->isThumb2())
10387     return isLegalT2AddressImmediate(V, VT, Subtarget);
10388
10389   // ARM mode.
10390   if (V < 0)
10391     V = - V;
10392   switch (VT.getSimpleVT().SimpleTy) {
10393   default: return false;
10394   case MVT::i1:
10395   case MVT::i8:
10396   case MVT::i32:
10397     // +- imm12
10398     return V == (V & ((1LL << 12) - 1));
10399   case MVT::i16:
10400     // +- imm8
10401     return V == (V & ((1LL << 8) - 1));
10402   case MVT::f32:
10403   case MVT::f64:
10404     if (!Subtarget->hasVFP2()) // FIXME: NEON?
10405       return false;
10406     if ((V & 3) != 0)
10407       return false;
10408     V >>= 2;
10409     return V == (V & ((1LL << 8) - 1));
10410   }
10411 }
10412
10413 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10414                                                       EVT VT) const {
10415   int Scale = AM.Scale;
10416   if (Scale < 0)
10417     return false;
10418
10419   switch (VT.getSimpleVT().SimpleTy) {
10420   default: return false;
10421   case MVT::i1:
10422   case MVT::i8:
10423   case MVT::i16:
10424   case MVT::i32:
10425     if (Scale == 1)
10426       return true;
10427     // r + r << imm
10428     Scale = Scale & ~1;
10429     return Scale == 2 || Scale == 4 || Scale == 8;
10430   case MVT::i64:
10431     // r + r
10432     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10433       return true;
10434     return false;
10435   case MVT::isVoid:
10436     // Note, we allow "void" uses (basically, uses that aren't loads or
10437     // stores), because arm allows folding a scale into many arithmetic
10438     // operations.  This should be made more precise and revisited later.
10439
10440     // Allow r << imm, but the imm has to be a multiple of two.
10441     if (Scale & 1) return false;
10442     return isPowerOf2_32(Scale);
10443   }
10444 }
10445
10446 /// isLegalAddressingMode - Return true if the addressing mode represented
10447 /// by AM is legal for this target, for a load/store of the specified type.
10448 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
10449                                               const AddrMode &AM, Type *Ty,
10450                                               unsigned AS) const {
10451   EVT VT = getValueType(DL, Ty, true);
10452   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10453     return false;
10454
10455   // Can never fold addr of global into load/store.
10456   if (AM.BaseGV)
10457     return false;
10458
10459   switch (AM.Scale) {
10460   case 0:  // no scale reg, must be "r+i" or "r", or "i".
10461     break;
10462   case 1:
10463     if (Subtarget->isThumb1Only())
10464       return false;
10465     // FALL THROUGH.
10466   default:
10467     // ARM doesn't support any R+R*scale+imm addr modes.
10468     if (AM.BaseOffs)
10469       return false;
10470
10471     if (!VT.isSimple())
10472       return false;
10473
10474     if (Subtarget->isThumb2())
10475       return isLegalT2ScaledAddressingMode(AM, VT);
10476
10477     int Scale = AM.Scale;
10478     switch (VT.getSimpleVT().SimpleTy) {
10479     default: return false;
10480     case MVT::i1:
10481     case MVT::i8:
10482     case MVT::i32:
10483       if (Scale < 0) Scale = -Scale;
10484       if (Scale == 1)
10485         return true;
10486       // r + r << imm
10487       return isPowerOf2_32(Scale & ~1);
10488     case MVT::i16:
10489     case MVT::i64:
10490       // r + r
10491       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10492         return true;
10493       return false;
10494
10495     case MVT::isVoid:
10496       // Note, we allow "void" uses (basically, uses that aren't loads or
10497       // stores), because arm allows folding a scale into many arithmetic
10498       // operations.  This should be made more precise and revisited later.
10499
10500       // Allow r << imm, but the imm has to be a multiple of two.
10501       if (Scale & 1) return false;
10502       return isPowerOf2_32(Scale);
10503     }
10504   }
10505   return true;
10506 }
10507
10508 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10509 /// icmp immediate, that is the target has icmp instructions which can compare
10510 /// a register against the immediate without having to materialize the
10511 /// immediate into a register.
10512 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10513   // Thumb2 and ARM modes can use cmn for negative immediates.
10514   if (!Subtarget->isThumb())
10515     return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
10516   if (Subtarget->isThumb2())
10517     return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
10518   // Thumb1 doesn't have cmn, and only 8-bit immediates.
10519   return Imm >= 0 && Imm <= 255;
10520 }
10521
10522 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10523 /// *or sub* immediate, that is the target has add or sub instructions which can
10524 /// add a register with the immediate without having to materialize the
10525 /// immediate into a register.
10526 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10527   // Same encoding for add/sub, just flip the sign.
10528   int64_t AbsImm = std::abs(Imm);
10529   if (!Subtarget->isThumb())
10530     return ARM_AM::getSOImmVal(AbsImm) != -1;
10531   if (Subtarget->isThumb2())
10532     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10533   // Thumb1 only has 8-bit unsigned immediate.
10534   return AbsImm >= 0 && AbsImm <= 255;
10535 }
10536
10537 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10538                                       bool isSEXTLoad, SDValue &Base,
10539                                       SDValue &Offset, bool &isInc,
10540                                       SelectionDAG &DAG) {
10541   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10542     return false;
10543
10544   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10545     // AddressingMode 3
10546     Base = Ptr->getOperand(0);
10547     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10548       int RHSC = (int)RHS->getZExtValue();
10549       if (RHSC < 0 && RHSC > -256) {
10550         assert(Ptr->getOpcode() == ISD::ADD);
10551         isInc = false;
10552         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10553         return true;
10554       }
10555     }
10556     isInc = (Ptr->getOpcode() == ISD::ADD);
10557     Offset = Ptr->getOperand(1);
10558     return true;
10559   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10560     // AddressingMode 2
10561     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10562       int RHSC = (int)RHS->getZExtValue();
10563       if (RHSC < 0 && RHSC > -0x1000) {
10564         assert(Ptr->getOpcode() == ISD::ADD);
10565         isInc = false;
10566         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10567         Base = Ptr->getOperand(0);
10568         return true;
10569       }
10570     }
10571
10572     if (Ptr->getOpcode() == ISD::ADD) {
10573       isInc = true;
10574       ARM_AM::ShiftOpc ShOpcVal=
10575         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10576       if (ShOpcVal != ARM_AM::no_shift) {
10577         Base = Ptr->getOperand(1);
10578         Offset = Ptr->getOperand(0);
10579       } else {
10580         Base = Ptr->getOperand(0);
10581         Offset = Ptr->getOperand(1);
10582       }
10583       return true;
10584     }
10585
10586     isInc = (Ptr->getOpcode() == ISD::ADD);
10587     Base = Ptr->getOperand(0);
10588     Offset = Ptr->getOperand(1);
10589     return true;
10590   }
10591
10592   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10593   return false;
10594 }
10595
10596 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10597                                      bool isSEXTLoad, SDValue &Base,
10598                                      SDValue &Offset, bool &isInc,
10599                                      SelectionDAG &DAG) {
10600   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10601     return false;
10602
10603   Base = Ptr->getOperand(0);
10604   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10605     int RHSC = (int)RHS->getZExtValue();
10606     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10607       assert(Ptr->getOpcode() == ISD::ADD);
10608       isInc = false;
10609       Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10610       return true;
10611     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10612       isInc = Ptr->getOpcode() == ISD::ADD;
10613       Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
10614       return true;
10615     }
10616   }
10617
10618   return false;
10619 }
10620
10621 /// getPreIndexedAddressParts - returns true by value, base pointer and
10622 /// offset pointer and addressing mode by reference if the node's address
10623 /// can be legally represented as pre-indexed load / store address.
10624 bool
10625 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10626                                              SDValue &Offset,
10627                                              ISD::MemIndexedMode &AM,
10628                                              SelectionDAG &DAG) const {
10629   if (Subtarget->isThumb1Only())
10630     return false;
10631
10632   EVT VT;
10633   SDValue Ptr;
10634   bool isSEXTLoad = false;
10635   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10636     Ptr = LD->getBasePtr();
10637     VT  = LD->getMemoryVT();
10638     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10639   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10640     Ptr = ST->getBasePtr();
10641     VT  = ST->getMemoryVT();
10642   } else
10643     return false;
10644
10645   bool isInc;
10646   bool isLegal = false;
10647   if (Subtarget->isThumb2())
10648     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10649                                        Offset, isInc, DAG);
10650   else
10651     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10652                                         Offset, isInc, DAG);
10653   if (!isLegal)
10654     return false;
10655
10656   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10657   return true;
10658 }
10659
10660 /// getPostIndexedAddressParts - returns true by value, base pointer and
10661 /// offset pointer and addressing mode by reference if this node can be
10662 /// combined with a load / store to form a post-indexed load / store.
10663 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10664                                                    SDValue &Base,
10665                                                    SDValue &Offset,
10666                                                    ISD::MemIndexedMode &AM,
10667                                                    SelectionDAG &DAG) const {
10668   if (Subtarget->isThumb1Only())
10669     return false;
10670
10671   EVT VT;
10672   SDValue Ptr;
10673   bool isSEXTLoad = false;
10674   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10675     VT  = LD->getMemoryVT();
10676     Ptr = LD->getBasePtr();
10677     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10678   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10679     VT  = ST->getMemoryVT();
10680     Ptr = ST->getBasePtr();
10681   } else
10682     return false;
10683
10684   bool isInc;
10685   bool isLegal = false;
10686   if (Subtarget->isThumb2())
10687     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10688                                        isInc, DAG);
10689   else
10690     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10691                                         isInc, DAG);
10692   if (!isLegal)
10693     return false;
10694
10695   if (Ptr != Base) {
10696     // Swap base ptr and offset to catch more post-index load / store when
10697     // it's legal. In Thumb2 mode, offset must be an immediate.
10698     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10699         !Subtarget->isThumb2())
10700       std::swap(Base, Offset);
10701
10702     // Post-indexed load / store update the base pointer.
10703     if (Ptr != Base)
10704       return false;
10705   }
10706
10707   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10708   return true;
10709 }
10710
10711 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10712                                                       APInt &KnownZero,
10713                                                       APInt &KnownOne,
10714                                                       const SelectionDAG &DAG,
10715                                                       unsigned Depth) const {
10716   unsigned BitWidth = KnownOne.getBitWidth();
10717   KnownZero = KnownOne = APInt(BitWidth, 0);
10718   switch (Op.getOpcode()) {
10719   default: break;
10720   case ARMISD::ADDC:
10721   case ARMISD::ADDE:
10722   case ARMISD::SUBC:
10723   case ARMISD::SUBE:
10724     // These nodes' second result is a boolean
10725     if (Op.getResNo() == 0)
10726       break;
10727     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10728     break;
10729   case ARMISD::CMOV: {
10730     // Bits are known zero/one if known on the LHS and RHS.
10731     DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10732     if (KnownZero == 0 && KnownOne == 0) return;
10733
10734     APInt KnownZeroRHS, KnownOneRHS;
10735     DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10736     KnownZero &= KnownZeroRHS;
10737     KnownOne  &= KnownOneRHS;
10738     return;
10739   }
10740   case ISD::INTRINSIC_W_CHAIN: {
10741     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10742     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10743     switch (IntID) {
10744     default: return;
10745     case Intrinsic::arm_ldaex:
10746     case Intrinsic::arm_ldrex: {
10747       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10748       unsigned MemBits = VT.getScalarType().getSizeInBits();
10749       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10750       return;
10751     }
10752     }
10753   }
10754   }
10755 }
10756
10757 //===----------------------------------------------------------------------===//
10758 //                           ARM Inline Assembly Support
10759 //===----------------------------------------------------------------------===//
10760
10761 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10762   // Looking for "rev" which is V6+.
10763   if (!Subtarget->hasV6Ops())
10764     return false;
10765
10766   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10767   std::string AsmStr = IA->getAsmString();
10768   SmallVector<StringRef, 4> AsmPieces;
10769   SplitString(AsmStr, AsmPieces, ";\n");
10770
10771   switch (AsmPieces.size()) {
10772   default: return false;
10773   case 1:
10774     AsmStr = AsmPieces[0];
10775     AsmPieces.clear();
10776     SplitString(AsmStr, AsmPieces, " \t,");
10777
10778     // rev $0, $1
10779     if (AsmPieces.size() == 3 &&
10780         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10781         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10782       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10783       if (Ty && Ty->getBitWidth() == 32)
10784         return IntrinsicLowering::LowerToByteSwap(CI);
10785     }
10786     break;
10787   }
10788
10789   return false;
10790 }
10791
10792 /// getConstraintType - Given a constraint letter, return the type of
10793 /// constraint it is for this target.
10794 ARMTargetLowering::ConstraintType
10795 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
10796   if (Constraint.size() == 1) {
10797     switch (Constraint[0]) {
10798     default:  break;
10799     case 'l': return C_RegisterClass;
10800     case 'w': return C_RegisterClass;
10801     case 'h': return C_RegisterClass;
10802     case 'x': return C_RegisterClass;
10803     case 't': return C_RegisterClass;
10804     case 'j': return C_Other; // Constant for movw.
10805       // An address with a single base register. Due to the way we
10806       // currently handle addresses it is the same as an 'r' memory constraint.
10807     case 'Q': return C_Memory;
10808     }
10809   } else if (Constraint.size() == 2) {
10810     switch (Constraint[0]) {
10811     default: break;
10812     // All 'U+' constraints are addresses.
10813     case 'U': return C_Memory;
10814     }
10815   }
10816   return TargetLowering::getConstraintType(Constraint);
10817 }
10818
10819 /// Examine constraint type and operand type and determine a weight value.
10820 /// This object must already have been set up with the operand type
10821 /// and the current alternative constraint selected.
10822 TargetLowering::ConstraintWeight
10823 ARMTargetLowering::getSingleConstraintMatchWeight(
10824     AsmOperandInfo &info, const char *constraint) const {
10825   ConstraintWeight weight = CW_Invalid;
10826   Value *CallOperandVal = info.CallOperandVal;
10827     // If we don't have a value, we can't do a match,
10828     // but allow it at the lowest weight.
10829   if (!CallOperandVal)
10830     return CW_Default;
10831   Type *type = CallOperandVal->getType();
10832   // Look at the constraint type.
10833   switch (*constraint) {
10834   default:
10835     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10836     break;
10837   case 'l':
10838     if (type->isIntegerTy()) {
10839       if (Subtarget->isThumb())
10840         weight = CW_SpecificReg;
10841       else
10842         weight = CW_Register;
10843     }
10844     break;
10845   case 'w':
10846     if (type->isFloatingPointTy())
10847       weight = CW_Register;
10848     break;
10849   }
10850   return weight;
10851 }
10852
10853 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10854 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
10855     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
10856   if (Constraint.size() == 1) {
10857     // GCC ARM Constraint Letters
10858     switch (Constraint[0]) {
10859     case 'l': // Low regs or general regs.
10860       if (Subtarget->isThumb())
10861         return RCPair(0U, &ARM::tGPRRegClass);
10862       return RCPair(0U, &ARM::GPRRegClass);
10863     case 'h': // High regs or no regs.
10864       if (Subtarget->isThumb())
10865         return RCPair(0U, &ARM::hGPRRegClass);
10866       break;
10867     case 'r':
10868       if (Subtarget->isThumb1Only())
10869         return RCPair(0U, &ARM::tGPRRegClass);
10870       return RCPair(0U, &ARM::GPRRegClass);
10871     case 'w':
10872       if (VT == MVT::Other)
10873         break;
10874       if (VT == MVT::f32)
10875         return RCPair(0U, &ARM::SPRRegClass);
10876       if (VT.getSizeInBits() == 64)
10877         return RCPair(0U, &ARM::DPRRegClass);
10878       if (VT.getSizeInBits() == 128)
10879         return RCPair(0U, &ARM::QPRRegClass);
10880       break;
10881     case 'x':
10882       if (VT == MVT::Other)
10883         break;
10884       if (VT == MVT::f32)
10885         return RCPair(0U, &ARM::SPR_8RegClass);
10886       if (VT.getSizeInBits() == 64)
10887         return RCPair(0U, &ARM::DPR_8RegClass);
10888       if (VT.getSizeInBits() == 128)
10889         return RCPair(0U, &ARM::QPR_8RegClass);
10890       break;
10891     case 't':
10892       if (VT == MVT::f32)
10893         return RCPair(0U, &ARM::SPRRegClass);
10894       break;
10895     }
10896   }
10897   if (StringRef("{cc}").equals_lower(Constraint))
10898     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10899
10900   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10901 }
10902
10903 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10904 /// vector.  If it is invalid, don't add anything to Ops.
10905 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10906                                                      std::string &Constraint,
10907                                                      std::vector<SDValue>&Ops,
10908                                                      SelectionDAG &DAG) const {
10909   SDValue Result;
10910
10911   // Currently only support length 1 constraints.
10912   if (Constraint.length() != 1) return;
10913
10914   char ConstraintLetter = Constraint[0];
10915   switch (ConstraintLetter) {
10916   default: break;
10917   case 'j':
10918   case 'I': case 'J': case 'K': case 'L':
10919   case 'M': case 'N': case 'O':
10920     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10921     if (!C)
10922       return;
10923
10924     int64_t CVal64 = C->getSExtValue();
10925     int CVal = (int) CVal64;
10926     // None of these constraints allow values larger than 32 bits.  Check
10927     // that the value fits in an int.
10928     if (CVal != CVal64)
10929       return;
10930
10931     switch (ConstraintLetter) {
10932       case 'j':
10933         // Constant suitable for movw, must be between 0 and
10934         // 65535.
10935         if (Subtarget->hasV6T2Ops())
10936           if (CVal >= 0 && CVal <= 65535)
10937             break;
10938         return;
10939       case 'I':
10940         if (Subtarget->isThumb1Only()) {
10941           // This must be a constant between 0 and 255, for ADD
10942           // immediates.
10943           if (CVal >= 0 && CVal <= 255)
10944             break;
10945         } else if (Subtarget->isThumb2()) {
10946           // A constant that can be used as an immediate value in a
10947           // data-processing instruction.
10948           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10949             break;
10950         } else {
10951           // A constant that can be used as an immediate value in a
10952           // data-processing instruction.
10953           if (ARM_AM::getSOImmVal(CVal) != -1)
10954             break;
10955         }
10956         return;
10957
10958       case 'J':
10959         if (Subtarget->isThumb()) {  // FIXME thumb2
10960           // This must be a constant between -255 and -1, for negated ADD
10961           // immediates. This can be used in GCC with an "n" modifier that
10962           // prints the negated value, for use with SUB instructions. It is
10963           // not useful otherwise but is implemented for compatibility.
10964           if (CVal >= -255 && CVal <= -1)
10965             break;
10966         } else {
10967           // This must be a constant between -4095 and 4095. It is not clear
10968           // what this constraint is intended for. Implemented for
10969           // compatibility with GCC.
10970           if (CVal >= -4095 && CVal <= 4095)
10971             break;
10972         }
10973         return;
10974
10975       case 'K':
10976         if (Subtarget->isThumb1Only()) {
10977           // A 32-bit value where only one byte has a nonzero value. Exclude
10978           // zero to match GCC. This constraint is used by GCC internally for
10979           // constants that can be loaded with a move/shift combination.
10980           // It is not useful otherwise but is implemented for compatibility.
10981           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10982             break;
10983         } else if (Subtarget->isThumb2()) {
10984           // A constant whose bitwise inverse can be used as an immediate
10985           // value in a data-processing instruction. This can be used in GCC
10986           // with a "B" modifier that prints the inverted value, for use with
10987           // BIC and MVN instructions. It is not useful otherwise but is
10988           // implemented for compatibility.
10989           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10990             break;
10991         } else {
10992           // A constant whose bitwise inverse can be used as an immediate
10993           // value in a data-processing instruction. This can be used in GCC
10994           // with a "B" modifier that prints the inverted value, for use with
10995           // BIC and MVN instructions. It is not useful otherwise but is
10996           // implemented for compatibility.
10997           if (ARM_AM::getSOImmVal(~CVal) != -1)
10998             break;
10999         }
11000         return;
11001
11002       case 'L':
11003         if (Subtarget->isThumb1Only()) {
11004           // This must be a constant between -7 and 7,
11005           // for 3-operand ADD/SUB immediate instructions.
11006           if (CVal >= -7 && CVal < 7)
11007             break;
11008         } else if (Subtarget->isThumb2()) {
11009           // A constant whose negation can be used as an immediate value in a
11010           // data-processing instruction. This can be used in GCC with an "n"
11011           // modifier that prints the negated value, for use with SUB
11012           // instructions. It is not useful otherwise but is implemented for
11013           // compatibility.
11014           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
11015             break;
11016         } else {
11017           // A constant whose negation can be used as an immediate value in a
11018           // data-processing instruction. This can be used in GCC with an "n"
11019           // modifier that prints the negated value, for use with SUB
11020           // instructions. It is not useful otherwise but is implemented for
11021           // compatibility.
11022           if (ARM_AM::getSOImmVal(-CVal) != -1)
11023             break;
11024         }
11025         return;
11026
11027       case 'M':
11028         if (Subtarget->isThumb()) { // FIXME thumb2
11029           // This must be a multiple of 4 between 0 and 1020, for
11030           // ADD sp + immediate.
11031           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
11032             break;
11033         } else {
11034           // A power of two or a constant between 0 and 32.  This is used in
11035           // GCC for the shift amount on shifted register operands, but it is
11036           // useful in general for any shift amounts.
11037           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
11038             break;
11039         }
11040         return;
11041
11042       case 'N':
11043         if (Subtarget->isThumb()) {  // FIXME thumb2
11044           // This must be a constant between 0 and 31, for shift amounts.
11045           if (CVal >= 0 && CVal <= 31)
11046             break;
11047         }
11048         return;
11049
11050       case 'O':
11051         if (Subtarget->isThumb()) {  // FIXME thumb2
11052           // This must be a multiple of 4 between -508 and 508, for
11053           // ADD/SUB sp = sp + immediate.
11054           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
11055             break;
11056         }
11057         return;
11058     }
11059     Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
11060     break;
11061   }
11062
11063   if (Result.getNode()) {
11064     Ops.push_back(Result);
11065     return;
11066   }
11067   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11068 }
11069
11070 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
11071   assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
11072   unsigned Opcode = Op->getOpcode();
11073   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
11074          "Invalid opcode for Div/Rem lowering");
11075   bool isSigned = (Opcode == ISD::SDIVREM);
11076   EVT VT = Op->getValueType(0);
11077   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
11078
11079   RTLIB::Libcall LC;
11080   switch (VT.getSimpleVT().SimpleTy) {
11081   default: llvm_unreachable("Unexpected request for libcall!");
11082   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
11083   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
11084   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
11085   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
11086   }
11087
11088   SDValue InChain = DAG.getEntryNode();
11089
11090   TargetLowering::ArgListTy Args;
11091   TargetLowering::ArgListEntry Entry;
11092   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
11093     EVT ArgVT = Op->getOperand(i).getValueType();
11094     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11095     Entry.Node = Op->getOperand(i);
11096     Entry.Ty = ArgTy;
11097     Entry.isSExt = isSigned;
11098     Entry.isZExt = !isSigned;
11099     Args.push_back(Entry);
11100   }
11101
11102   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11103                                          getPointerTy(DAG.getDataLayout()));
11104
11105   Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
11106
11107   SDLoc dl(Op);
11108   TargetLowering::CallLoweringInfo CLI(DAG);
11109   CLI.setDebugLoc(dl).setChain(InChain)
11110     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
11111     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
11112
11113   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
11114   return CallInfo.first;
11115 }
11116
11117 SDValue
11118 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
11119   assert(Subtarget->isTargetWindows() && "unsupported target platform");
11120   SDLoc DL(Op);
11121
11122   // Get the inputs.
11123   SDValue Chain = Op.getOperand(0);
11124   SDValue Size  = Op.getOperand(1);
11125
11126   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
11127                               DAG.getConstant(2, DL, MVT::i32));
11128
11129   SDValue Flag;
11130   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
11131   Flag = Chain.getValue(1);
11132
11133   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11134   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
11135
11136   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
11137   Chain = NewSP.getValue(1);
11138
11139   SDValue Ops[2] = { NewSP, Chain };
11140   return DAG.getMergeValues(Ops, DL);
11141 }
11142
11143 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
11144   assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
11145          "Unexpected type for custom-lowering FP_EXTEND");
11146
11147   RTLIB::Libcall LC;
11148   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
11149
11150   SDValue SrcVal = Op.getOperand(0);
11151   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
11152                      /*isSigned*/ false, SDLoc(Op)).first;
11153 }
11154
11155 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
11156   assert(Op.getOperand(0).getValueType() == MVT::f64 &&
11157          Subtarget->isFPOnlySP() &&
11158          "Unexpected type for custom-lowering FP_ROUND");
11159
11160   RTLIB::Libcall LC;
11161   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
11162
11163   SDValue SrcVal = Op.getOperand(0);
11164   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
11165                      /*isSigned*/ false, SDLoc(Op)).first;
11166 }
11167
11168 bool
11169 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11170   // The ARM target isn't yet aware of offsets.
11171   return false;
11172 }
11173
11174 bool ARM::isBitFieldInvertedMask(unsigned v) {
11175   if (v == 0xffffffff)
11176     return false;
11177
11178   // there can be 1's on either or both "outsides", all the "inside"
11179   // bits must be 0's
11180   return isShiftedMask_32(~v);
11181 }
11182
11183 /// isFPImmLegal - Returns true if the target can instruction select the
11184 /// specified FP immediate natively. If false, the legalizer will
11185 /// materialize the FP immediate as a load from a constant pool.
11186 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
11187   if (!Subtarget->hasVFP3())
11188     return false;
11189   if (VT == MVT::f32)
11190     return ARM_AM::getFP32Imm(Imm) != -1;
11191   if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
11192     return ARM_AM::getFP64Imm(Imm) != -1;
11193   return false;
11194 }
11195
11196 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
11197 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
11198 /// specified in the intrinsic calls.
11199 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11200                                            const CallInst &I,
11201                                            unsigned Intrinsic) const {
11202   switch (Intrinsic) {
11203   case Intrinsic::arm_neon_vld1:
11204   case Intrinsic::arm_neon_vld2:
11205   case Intrinsic::arm_neon_vld3:
11206   case Intrinsic::arm_neon_vld4:
11207   case Intrinsic::arm_neon_vld2lane:
11208   case Intrinsic::arm_neon_vld3lane:
11209   case Intrinsic::arm_neon_vld4lane: {
11210     Info.opc = ISD::INTRINSIC_W_CHAIN;
11211     // Conservatively set memVT to the entire set of vectors loaded.
11212     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11213     uint64_t NumElts = DL.getTypeAllocSize(I.getType()) / 8;
11214     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11215     Info.ptrVal = I.getArgOperand(0);
11216     Info.offset = 0;
11217     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11218     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11219     Info.vol = false; // volatile loads with NEON intrinsics not supported
11220     Info.readMem = true;
11221     Info.writeMem = false;
11222     return true;
11223   }
11224   case Intrinsic::arm_neon_vst1:
11225   case Intrinsic::arm_neon_vst2:
11226   case Intrinsic::arm_neon_vst3:
11227   case Intrinsic::arm_neon_vst4:
11228   case Intrinsic::arm_neon_vst2lane:
11229   case Intrinsic::arm_neon_vst3lane:
11230   case Intrinsic::arm_neon_vst4lane: {
11231     Info.opc = ISD::INTRINSIC_VOID;
11232     // Conservatively set memVT to the entire set of vectors stored.
11233     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11234     unsigned NumElts = 0;
11235     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11236       Type *ArgTy = I.getArgOperand(ArgI)->getType();
11237       if (!ArgTy->isVectorTy())
11238         break;
11239       NumElts += DL.getTypeAllocSize(ArgTy) / 8;
11240     }
11241     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11242     Info.ptrVal = I.getArgOperand(0);
11243     Info.offset = 0;
11244     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11245     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11246     Info.vol = false; // volatile stores with NEON intrinsics not supported
11247     Info.readMem = false;
11248     Info.writeMem = true;
11249     return true;
11250   }
11251   case Intrinsic::arm_ldaex:
11252   case Intrinsic::arm_ldrex: {
11253     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11254     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11255     Info.opc = ISD::INTRINSIC_W_CHAIN;
11256     Info.memVT = MVT::getVT(PtrTy->getElementType());
11257     Info.ptrVal = I.getArgOperand(0);
11258     Info.offset = 0;
11259     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11260     Info.vol = true;
11261     Info.readMem = true;
11262     Info.writeMem = false;
11263     return true;
11264   }
11265   case Intrinsic::arm_stlex:
11266   case Intrinsic::arm_strex: {
11267     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11268     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11269     Info.opc = ISD::INTRINSIC_W_CHAIN;
11270     Info.memVT = MVT::getVT(PtrTy->getElementType());
11271     Info.ptrVal = I.getArgOperand(1);
11272     Info.offset = 0;
11273     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11274     Info.vol = true;
11275     Info.readMem = false;
11276     Info.writeMem = true;
11277     return true;
11278   }
11279   case Intrinsic::arm_stlexd:
11280   case Intrinsic::arm_strexd: {
11281     Info.opc = ISD::INTRINSIC_W_CHAIN;
11282     Info.memVT = MVT::i64;
11283     Info.ptrVal = I.getArgOperand(2);
11284     Info.offset = 0;
11285     Info.align = 8;
11286     Info.vol = true;
11287     Info.readMem = false;
11288     Info.writeMem = true;
11289     return true;
11290   }
11291   case Intrinsic::arm_ldaexd:
11292   case Intrinsic::arm_ldrexd: {
11293     Info.opc = ISD::INTRINSIC_W_CHAIN;
11294     Info.memVT = MVT::i64;
11295     Info.ptrVal = I.getArgOperand(0);
11296     Info.offset = 0;
11297     Info.align = 8;
11298     Info.vol = true;
11299     Info.readMem = true;
11300     Info.writeMem = false;
11301     return true;
11302   }
11303   default:
11304     break;
11305   }
11306
11307   return false;
11308 }
11309
11310 /// \brief Returns true if it is beneficial to convert a load of a constant
11311 /// to just the constant itself.
11312 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11313                                                           Type *Ty) const {
11314   assert(Ty->isIntegerTy());
11315
11316   unsigned Bits = Ty->getPrimitiveSizeInBits();
11317   if (Bits == 0 || Bits > 32)
11318     return false;
11319   return true;
11320 }
11321
11322 bool ARMTargetLowering::hasLoadLinkedStoreConditional() const { return true; }
11323
11324 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
11325                                         ARM_MB::MemBOpt Domain) const {
11326   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11327
11328   // First, if the target has no DMB, see what fallback we can use.
11329   if (!Subtarget->hasDataBarrier()) {
11330     // Some ARMv6 cpus can support data barriers with an mcr instruction.
11331     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
11332     // here.
11333     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
11334       Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
11335       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
11336                         Builder.getInt32(0), Builder.getInt32(7),
11337                         Builder.getInt32(10), Builder.getInt32(5)};
11338       return Builder.CreateCall(MCR, args);
11339     } else {
11340       // Instead of using barriers, atomic accesses on these subtargets use
11341       // libcalls.
11342       llvm_unreachable("makeDMB on a target so old that it has no barriers");
11343     }
11344   } else {
11345     Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
11346     // Only a full system barrier exists in the M-class architectures.
11347     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
11348     Constant *CDomain = Builder.getInt32(Domain);
11349     return Builder.CreateCall(DMB, CDomain);
11350   }
11351 }
11352
11353 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11354 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11355                                          AtomicOrdering Ord, bool IsStore,
11356                                          bool IsLoad) const {
11357   if (!getInsertFencesForAtomic())
11358     return nullptr;
11359
11360   switch (Ord) {
11361   case NotAtomic:
11362   case Unordered:
11363     llvm_unreachable("Invalid fence: unordered/non-atomic");
11364   case Monotonic:
11365   case Acquire:
11366     return nullptr; // Nothing to do
11367   case SequentiallyConsistent:
11368     if (!IsStore)
11369       return nullptr; // Nothing to do
11370     /*FALLTHROUGH*/
11371   case Release:
11372   case AcquireRelease:
11373     if (Subtarget->isSwift())
11374       return makeDMB(Builder, ARM_MB::ISHST);
11375     // FIXME: add a comment with a link to documentation justifying this.
11376     else
11377       return makeDMB(Builder, ARM_MB::ISH);
11378   }
11379   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
11380 }
11381
11382 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11383                                           AtomicOrdering Ord, bool IsStore,
11384                                           bool IsLoad) const {
11385   if (!getInsertFencesForAtomic())
11386     return nullptr;
11387
11388   switch (Ord) {
11389   case NotAtomic:
11390   case Unordered:
11391     llvm_unreachable("Invalid fence: unordered/not-atomic");
11392   case Monotonic:
11393   case Release:
11394     return nullptr; // Nothing to do
11395   case Acquire:
11396   case AcquireRelease:
11397   case SequentiallyConsistent:
11398     return makeDMB(Builder, ARM_MB::ISH);
11399   }
11400   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
11401 }
11402
11403 // Loads and stores less than 64-bits are already atomic; ones above that
11404 // are doomed anyway, so defer to the default libcall and blame the OS when
11405 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11406 // anything for those.
11407 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11408   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11409   return (Size == 64) && !Subtarget->isMClass();
11410 }
11411
11412 // Loads and stores less than 64-bits are already atomic; ones above that
11413 // are doomed anyway, so defer to the default libcall and blame the OS when
11414 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11415 // anything for those.
11416 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
11417 // guarantee, see DDI0406C ARM architecture reference manual,
11418 // sections A8.8.72-74 LDRD)
11419 bool ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11420   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11421   return (Size == 64) && !Subtarget->isMClass();
11422 }
11423
11424 // For the real atomic operations, we have ldrex/strex up to 32 bits,
11425 // and up to 64 bits on the non-M profiles
11426 TargetLoweringBase::AtomicRMWExpansionKind
11427 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11428   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11429   return (Size <= (Subtarget->isMClass() ? 32U : 64U))
11430              ? AtomicRMWExpansionKind::LLSC
11431              : AtomicRMWExpansionKind::None;
11432 }
11433
11434 // This has so far only been implemented for MachO.
11435 bool ARMTargetLowering::useLoadStackGuardNode() const {
11436   return Subtarget->isTargetMachO();
11437 }
11438
11439 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
11440                                                   unsigned &Cost) const {
11441   // If we do not have NEON, vector types are not natively supported.
11442   if (!Subtarget->hasNEON())
11443     return false;
11444
11445   // Floating point values and vector values map to the same register file.
11446   // Therefore, althought we could do a store extract of a vector type, this is
11447   // better to leave at float as we have more freedom in the addressing mode for
11448   // those.
11449   if (VectorTy->isFPOrFPVectorTy())
11450     return false;
11451
11452   // If the index is unknown at compile time, this is very expensive to lower
11453   // and it is not possible to combine the store with the extract.
11454   if (!isa<ConstantInt>(Idx))
11455     return false;
11456
11457   assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
11458   unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
11459   // We can do a store + vector extract on any vector that fits perfectly in a D
11460   // or Q register.
11461   if (BitWidth == 64 || BitWidth == 128) {
11462     Cost = 0;
11463     return true;
11464   }
11465   return false;
11466 }
11467
11468 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11469                                          AtomicOrdering Ord) const {
11470   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11471   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11472   bool IsAcquire = isAtLeastAcquire(Ord);
11473
11474   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
11475   // intrinsic must return {i32, i32} and we have to recombine them into a
11476   // single i64 here.
11477   if (ValTy->getPrimitiveSizeInBits() == 64) {
11478     Intrinsic::ID Int =
11479         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
11480     Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
11481
11482     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11483     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
11484
11485     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11486     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11487     if (!Subtarget->isLittle())
11488       std::swap (Lo, Hi);
11489     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11490     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11491     return Builder.CreateOr(
11492         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
11493   }
11494
11495   Type *Tys[] = { Addr->getType() };
11496   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
11497   Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
11498
11499   return Builder.CreateTruncOrBitCast(
11500       Builder.CreateCall(Ldrex, Addr),
11501       cast<PointerType>(Addr->getType())->getElementType());
11502 }
11503
11504 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
11505                                                Value *Addr,
11506                                                AtomicOrdering Ord) const {
11507   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11508   bool IsRelease = isAtLeastRelease(Ord);
11509
11510   // Since the intrinsics must have legal type, the i64 intrinsics take two
11511   // parameters: "i32, i32". We must marshal Val into the appropriate form
11512   // before the call.
11513   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
11514     Intrinsic::ID Int =
11515         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
11516     Function *Strex = Intrinsic::getDeclaration(M, Int);
11517     Type *Int32Ty = Type::getInt32Ty(M->getContext());
11518
11519     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
11520     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
11521     if (!Subtarget->isLittle())
11522       std::swap (Lo, Hi);
11523     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11524     return Builder.CreateCall(Strex, {Lo, Hi, Addr});
11525   }
11526
11527   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
11528   Type *Tys[] = { Addr->getType() };
11529   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
11530
11531   return Builder.CreateCall(
11532       Strex, {Builder.CreateZExtOrBitCast(
11533                   Val, Strex->getFunctionType()->getParamType(0)),
11534               Addr});
11535 }
11536
11537 /// \brief Lower an interleaved load into a vldN intrinsic.
11538 ///
11539 /// E.g. Lower an interleaved load (Factor = 2):
11540 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
11541 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
11542 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
11543 ///
11544 ///      Into:
11545 ///        %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
11546 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
11547 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
11548 bool ARMTargetLowering::lowerInterleavedLoad(
11549     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
11550     ArrayRef<unsigned> Indices, unsigned Factor) const {
11551   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
11552          "Invalid interleave factor");
11553   assert(!Shuffles.empty() && "Empty shufflevector input");
11554   assert(Shuffles.size() == Indices.size() &&
11555          "Unmatched number of shufflevectors and indices");
11556
11557   VectorType *VecTy = Shuffles[0]->getType();
11558   Type *EltTy = VecTy->getVectorElementType();
11559
11560   const DataLayout &DL = LI->getModule()->getDataLayout();
11561   unsigned VecSize = DL.getTypeAllocSizeInBits(VecTy);
11562   bool EltIs64Bits = DL.getTypeAllocSizeInBits(EltTy) == 64;
11563
11564   // Skip illegal vector types and vector types of i64/f64 element (vldN doesn't
11565   // support i64/f64 element).
11566   if ((VecSize != 64 && VecSize != 128) || EltIs64Bits)
11567     return false;
11568
11569   // A pointer vector can not be the return type of the ldN intrinsics. Need to
11570   // load integer vectors first and then convert to pointer vectors.
11571   if (EltTy->isPointerTy())
11572     VecTy =
11573         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
11574
11575   static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
11576                                             Intrinsic::arm_neon_vld3,
11577                                             Intrinsic::arm_neon_vld4};
11578
11579   Function *VldnFunc =
11580       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], VecTy);
11581
11582   IRBuilder<> Builder(LI);
11583   SmallVector<Value *, 2> Ops;
11584
11585   Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
11586   Ops.push_back(Builder.CreateBitCast(LI->getPointerOperand(), Int8Ptr));
11587   Ops.push_back(Builder.getInt32(LI->getAlignment()));
11588
11589   CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
11590
11591   // Replace uses of each shufflevector with the corresponding vector loaded
11592   // by ldN.
11593   for (unsigned i = 0; i < Shuffles.size(); i++) {
11594     ShuffleVectorInst *SV = Shuffles[i];
11595     unsigned Index = Indices[i];
11596
11597     Value *SubVec = Builder.CreateExtractValue(VldN, Index);
11598
11599     // Convert the integer vector to pointer vector if the element is pointer.
11600     if (EltTy->isPointerTy())
11601       SubVec = Builder.CreateIntToPtr(SubVec, SV->getType());
11602
11603     SV->replaceAllUsesWith(SubVec);
11604   }
11605
11606   return true;
11607 }
11608
11609 /// \brief Get a mask consisting of sequential integers starting from \p Start.
11610 ///
11611 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
11612 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
11613                                    unsigned NumElts) {
11614   SmallVector<Constant *, 16> Mask;
11615   for (unsigned i = 0; i < NumElts; i++)
11616     Mask.push_back(Builder.getInt32(Start + i));
11617
11618   return ConstantVector::get(Mask);
11619 }
11620
11621 /// \brief Lower an interleaved store into a vstN intrinsic.
11622 ///
11623 /// E.g. Lower an interleaved store (Factor = 3):
11624 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
11625 ///                                  <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
11626 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
11627 ///
11628 ///      Into:
11629 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
11630 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
11631 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
11632 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
11633 ///
11634 /// Note that the new shufflevectors will be removed and we'll only generate one
11635 /// vst3 instruction in CodeGen.
11636 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
11637                                               ShuffleVectorInst *SVI,
11638                                               unsigned Factor) const {
11639   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
11640          "Invalid interleave factor");
11641
11642   VectorType *VecTy = SVI->getType();
11643   assert(VecTy->getVectorNumElements() % Factor == 0 &&
11644          "Invalid interleaved store");
11645
11646   unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
11647   Type *EltTy = VecTy->getVectorElementType();
11648   VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
11649
11650   const DataLayout &DL = SI->getModule()->getDataLayout();
11651   unsigned SubVecSize = DL.getTypeAllocSizeInBits(SubVecTy);
11652   bool EltIs64Bits = DL.getTypeAllocSizeInBits(EltTy) == 64;
11653
11654   // Skip illegal sub vector types and vector types of i64/f64 element (vstN
11655   // doesn't support i64/f64 element).
11656   if ((SubVecSize != 64 && SubVecSize != 128) || EltIs64Bits)
11657     return false;
11658
11659   Value *Op0 = SVI->getOperand(0);
11660   Value *Op1 = SVI->getOperand(1);
11661   IRBuilder<> Builder(SI);
11662
11663   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
11664   // vectors to integer vectors.
11665   if (EltTy->isPointerTy()) {
11666     Type *IntTy = DL.getIntPtrType(EltTy);
11667
11668     // Convert to the corresponding integer vector.
11669     Type *IntVecTy =
11670         VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
11671     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
11672     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
11673
11674     SubVecTy = VectorType::get(IntTy, NumSubElts);
11675   }
11676
11677   static Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
11678                                        Intrinsic::arm_neon_vst3,
11679                                        Intrinsic::arm_neon_vst4};
11680   Function *VstNFunc = Intrinsic::getDeclaration(
11681       SI->getModule(), StoreInts[Factor - 2], SubVecTy);
11682
11683   SmallVector<Value *, 6> Ops;
11684
11685   Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
11686   Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), Int8Ptr));
11687
11688   // Split the shufflevector operands into sub vectors for the new vstN call.
11689   for (unsigned i = 0; i < Factor; i++)
11690     Ops.push_back(Builder.CreateShuffleVector(
11691         Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
11692
11693   Ops.push_back(Builder.getInt32(SI->getAlignment()));
11694   Builder.CreateCall(VstNFunc, Ops);
11695   return true;
11696 }
11697
11698 enum HABaseType {
11699   HA_UNKNOWN = 0,
11700   HA_FLOAT,
11701   HA_DOUBLE,
11702   HA_VECT64,
11703   HA_VECT128
11704 };
11705
11706 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
11707                                    uint64_t &Members) {
11708   if (const StructType *ST = dyn_cast<StructType>(Ty)) {
11709     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
11710       uint64_t SubMembers = 0;
11711       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
11712         return false;
11713       Members += SubMembers;
11714     }
11715   } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
11716     uint64_t SubMembers = 0;
11717     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
11718       return false;
11719     Members += SubMembers * AT->getNumElements();
11720   } else if (Ty->isFloatTy()) {
11721     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
11722       return false;
11723     Members = 1;
11724     Base = HA_FLOAT;
11725   } else if (Ty->isDoubleTy()) {
11726     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
11727       return false;
11728     Members = 1;
11729     Base = HA_DOUBLE;
11730   } else if (const VectorType *VT = dyn_cast<VectorType>(Ty)) {
11731     Members = 1;
11732     switch (Base) {
11733     case HA_FLOAT:
11734     case HA_DOUBLE:
11735       return false;
11736     case HA_VECT64:
11737       return VT->getBitWidth() == 64;
11738     case HA_VECT128:
11739       return VT->getBitWidth() == 128;
11740     case HA_UNKNOWN:
11741       switch (VT->getBitWidth()) {
11742       case 64:
11743         Base = HA_VECT64;
11744         return true;
11745       case 128:
11746         Base = HA_VECT128;
11747         return true;
11748       default:
11749         return false;
11750       }
11751     }
11752   }
11753
11754   return (Members > 0 && Members <= 4);
11755 }
11756
11757 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
11758 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
11759 /// passing according to AAPCS rules.
11760 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
11761     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11762   if (getEffectiveCallingConv(CallConv, isVarArg) !=
11763       CallingConv::ARM_AAPCS_VFP)
11764     return false;
11765
11766   HABaseType Base = HA_UNKNOWN;
11767   uint64_t Members = 0;
11768   bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
11769   DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
11770
11771   bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
11772   return IsHA || IsIntArray;
11773 }