Re-commit of r238201 with fix for building with shared libraries.
[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 cl::opt<bool>
64 EnableARMLongCalls("arm-long-calls", cl::Hidden,
65   cl::desc("Generate calls via indirect call instructions"),
66   cl::init(false));
67
68 static cl::opt<bool>
69 ARMInterworking("arm-interworking", cl::Hidden,
70   cl::desc("Enable / disable ARM interworking (for debugging only)"),
71   cl::init(true));
72
73 namespace {
74   class ARMCCState : public CCState {
75   public:
76     ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
77                SmallVectorImpl<CCValAssign> &locs, LLVMContext &C,
78                ParmContext PC)
79         : CCState(CC, isVarArg, MF, locs, C) {
80       assert(((PC == Call) || (PC == Prologue)) &&
81              "ARMCCState users must specify whether their context is call"
82              "or prologue generation.");
83       CallOrPrologue = PC;
84     }
85   };
86 }
87
88 // The APCS parameter registers.
89 static const MCPhysReg GPRArgRegs[] = {
90   ARM::R0, ARM::R1, ARM::R2, ARM::R3
91 };
92
93 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
94                                        MVT PromotedBitwiseVT) {
95   if (VT != PromotedLdStVT) {
96     setOperationAction(ISD::LOAD, VT, Promote);
97     AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
98
99     setOperationAction(ISD::STORE, VT, Promote);
100     AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
101   }
102
103   MVT ElemTy = VT.getVectorElementType();
104   if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
105     setOperationAction(ISD::SETCC, VT, Custom);
106   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
107   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
108   if (ElemTy == MVT::i32) {
109     setOperationAction(ISD::SINT_TO_FP, VT, Custom);
110     setOperationAction(ISD::UINT_TO_FP, VT, Custom);
111     setOperationAction(ISD::FP_TO_SINT, VT, Custom);
112     setOperationAction(ISD::FP_TO_UINT, VT, Custom);
113   } else {
114     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
115     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
116     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
117     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
118   }
119   setOperationAction(ISD::BUILD_VECTOR,      VT, Custom);
120   setOperationAction(ISD::VECTOR_SHUFFLE,    VT, Custom);
121   setOperationAction(ISD::CONCAT_VECTORS,    VT, Legal);
122   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
123   setOperationAction(ISD::SELECT,            VT, Expand);
124   setOperationAction(ISD::SELECT_CC,         VT, Expand);
125   setOperationAction(ISD::VSELECT,           VT, Expand);
126   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
127   if (VT.isInteger()) {
128     setOperationAction(ISD::SHL, VT, Custom);
129     setOperationAction(ISD::SRA, VT, Custom);
130     setOperationAction(ISD::SRL, VT, Custom);
131   }
132
133   // Promote all bit-wise operations.
134   if (VT.isInteger() && VT != PromotedBitwiseVT) {
135     setOperationAction(ISD::AND, VT, Promote);
136     AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
137     setOperationAction(ISD::OR,  VT, Promote);
138     AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
139     setOperationAction(ISD::XOR, VT, Promote);
140     AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
141   }
142
143   // Neon does not support vector divide/remainder operations.
144   setOperationAction(ISD::SDIV, VT, Expand);
145   setOperationAction(ISD::UDIV, VT, Expand);
146   setOperationAction(ISD::FDIV, VT, Expand);
147   setOperationAction(ISD::SREM, VT, Expand);
148   setOperationAction(ISD::UREM, VT, Expand);
149   setOperationAction(ISD::FREM, VT, Expand);
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 only has FMA instructions as of VFP4.
552     if (!Subtarget->hasVFP4()) {
553       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
554       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
555     }
556
557     setTargetDAGCombine(ISD::INTRINSIC_VOID);
558     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
559     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
560     setTargetDAGCombine(ISD::SHL);
561     setTargetDAGCombine(ISD::SRL);
562     setTargetDAGCombine(ISD::SRA);
563     setTargetDAGCombine(ISD::SIGN_EXTEND);
564     setTargetDAGCombine(ISD::ZERO_EXTEND);
565     setTargetDAGCombine(ISD::ANY_EXTEND);
566     setTargetDAGCombine(ISD::SELECT_CC);
567     setTargetDAGCombine(ISD::BUILD_VECTOR);
568     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
569     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
570     setTargetDAGCombine(ISD::STORE);
571     setTargetDAGCombine(ISD::FP_TO_SINT);
572     setTargetDAGCombine(ISD::FP_TO_UINT);
573     setTargetDAGCombine(ISD::FDIV);
574     setTargetDAGCombine(ISD::LOAD);
575
576     // It is legal to extload from v4i8 to v4i16 or v4i32.
577     for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
578                    MVT::v2i32}) {
579       for (MVT VT : MVT::integer_vector_valuetypes()) {
580         setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
581         setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
582         setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
583       }
584     }
585   }
586
587   // ARM and Thumb2 support UMLAL/SMLAL.
588   if (!Subtarget->isThumb1Only())
589     setTargetDAGCombine(ISD::ADDC);
590
591   if (Subtarget->isFPOnlySP()) {
592     // When targetting a floating-point unit with only single-precision
593     // operations, f64 is legal for the few double-precision instructions which
594     // are present However, no double-precision operations other than moves,
595     // loads and stores are provided by the hardware.
596     setOperationAction(ISD::FADD,       MVT::f64, Expand);
597     setOperationAction(ISD::FSUB,       MVT::f64, Expand);
598     setOperationAction(ISD::FMUL,       MVT::f64, Expand);
599     setOperationAction(ISD::FMA,        MVT::f64, Expand);
600     setOperationAction(ISD::FDIV,       MVT::f64, Expand);
601     setOperationAction(ISD::FREM,       MVT::f64, Expand);
602     setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
603     setOperationAction(ISD::FGETSIGN,   MVT::f64, Expand);
604     setOperationAction(ISD::FNEG,       MVT::f64, Expand);
605     setOperationAction(ISD::FABS,       MVT::f64, Expand);
606     setOperationAction(ISD::FSQRT,      MVT::f64, Expand);
607     setOperationAction(ISD::FSIN,       MVT::f64, Expand);
608     setOperationAction(ISD::FCOS,       MVT::f64, Expand);
609     setOperationAction(ISD::FPOWI,      MVT::f64, Expand);
610     setOperationAction(ISD::FPOW,       MVT::f64, Expand);
611     setOperationAction(ISD::FLOG,       MVT::f64, Expand);
612     setOperationAction(ISD::FLOG2,      MVT::f64, Expand);
613     setOperationAction(ISD::FLOG10,     MVT::f64, Expand);
614     setOperationAction(ISD::FEXP,       MVT::f64, Expand);
615     setOperationAction(ISD::FEXP2,      MVT::f64, Expand);
616     setOperationAction(ISD::FCEIL,      MVT::f64, Expand);
617     setOperationAction(ISD::FTRUNC,     MVT::f64, Expand);
618     setOperationAction(ISD::FRINT,      MVT::f64, Expand);
619     setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
620     setOperationAction(ISD::FFLOOR,     MVT::f64, Expand);
621     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
622     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
623     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
624     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
625     setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
626     setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
627     setOperationAction(ISD::FP_ROUND,   MVT::f32, Custom);
628     setOperationAction(ISD::FP_EXTEND,  MVT::f64, Custom);
629   }
630
631   computeRegisterProperties(Subtarget->getRegisterInfo());
632
633   // ARM does not have floating-point extending loads.
634   for (MVT VT : MVT::fp_valuetypes()) {
635     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
636     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
637   }
638
639   // ... or truncating stores
640   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
641   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
642   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
643
644   // ARM does not have i1 sign extending load.
645   for (MVT VT : MVT::integer_valuetypes())
646     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
647
648   // ARM supports all 4 flavors of integer indexed load / store.
649   if (!Subtarget->isThumb1Only()) {
650     for (unsigned im = (unsigned)ISD::PRE_INC;
651          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
652       setIndexedLoadAction(im,  MVT::i1,  Legal);
653       setIndexedLoadAction(im,  MVT::i8,  Legal);
654       setIndexedLoadAction(im,  MVT::i16, Legal);
655       setIndexedLoadAction(im,  MVT::i32, Legal);
656       setIndexedStoreAction(im, MVT::i1,  Legal);
657       setIndexedStoreAction(im, MVT::i8,  Legal);
658       setIndexedStoreAction(im, MVT::i16, Legal);
659       setIndexedStoreAction(im, MVT::i32, Legal);
660     }
661   }
662
663   setOperationAction(ISD::SADDO, MVT::i32, Custom);
664   setOperationAction(ISD::UADDO, MVT::i32, Custom);
665   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
666   setOperationAction(ISD::USUBO, MVT::i32, Custom);
667
668   // i64 operation support.
669   setOperationAction(ISD::MUL,     MVT::i64, Expand);
670   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
671   if (Subtarget->isThumb1Only()) {
672     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
673     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
674   }
675   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
676       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
677     setOperationAction(ISD::MULHS, MVT::i32, Expand);
678
679   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
680   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
681   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
682   setOperationAction(ISD::SRL,       MVT::i64, Custom);
683   setOperationAction(ISD::SRA,       MVT::i64, Custom);
684
685   if (!Subtarget->isThumb1Only()) {
686     // FIXME: We should do this for Thumb1 as well.
687     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
688     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
689     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
690     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
691   }
692
693   // ARM does not have ROTL.
694   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
695   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
696   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
697   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
698     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
699
700   // These just redirect to CTTZ and CTLZ on ARM.
701   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
702   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
703
704   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
705
706   // Only ARMv6 has BSWAP.
707   if (!Subtarget->hasV6Ops())
708     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
709
710   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
711       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
712     // These are expanded into libcalls if the cpu doesn't have HW divider.
713     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
714     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
715   }
716
717   // FIXME: Also set divmod for SREM on EABI
718   setOperationAction(ISD::SREM,  MVT::i32, Expand);
719   setOperationAction(ISD::UREM,  MVT::i32, Expand);
720   // Register based DivRem for AEABI (RTABI 4.2)
721   if (Subtarget->isTargetAEABI()) {
722     setLibcallName(RTLIB::SDIVREM_I8,  "__aeabi_idivmod");
723     setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
724     setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
725     setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
726     setLibcallName(RTLIB::UDIVREM_I8,  "__aeabi_uidivmod");
727     setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
728     setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
729     setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
730
731     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
732     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
733     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
734     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
735     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
736     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
737     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
738     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
739
740     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
741     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
742   } else {
743     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
744     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
745   }
746
747   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
748   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
749   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
750   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
751   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
752
753   setOperationAction(ISD::TRAP, MVT::Other, Legal);
754
755   // Use the default implementation.
756   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
757   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
758   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
759   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
760   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
761   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
762
763   if (!Subtarget->isTargetMachO()) {
764     // Non-MachO platforms may return values in these registers via the
765     // personality function.
766     setExceptionPointerRegister(ARM::R0);
767     setExceptionSelectorRegister(ARM::R1);
768   }
769
770   if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
771     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
772   else
773     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
774
775   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
776   // the default expansion. If we are targeting a single threaded system,
777   // then set them all for expand so we can lower them later into their
778   // non-atomic form.
779   if (TM.Options.ThreadModel == ThreadModel::Single)
780     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
781   else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
782     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
783     // to ldrex/strex loops already.
784     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
785
786     // On v8, we have particularly efficient implementations of atomic fences
787     // if they can be combined with nearby atomic loads and stores.
788     if (!Subtarget->hasV8Ops()) {
789       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
790       setInsertFencesForAtomic(true);
791     }
792   } else {
793     // If there's anything we can use as a barrier, go through custom lowering
794     // for ATOMIC_FENCE.
795     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
796                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
797
798     // Set them all for expansion, which will force libcalls.
799     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
800     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
801     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
802     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
803     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
804     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
805     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
806     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
807     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
808     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
809     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
810     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
811     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
812     // Unordered/Monotonic case.
813     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
814     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
815   }
816
817   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
818
819   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
820   if (!Subtarget->hasV6Ops()) {
821     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
822     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
823   }
824   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
825
826   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
827       !Subtarget->isThumb1Only()) {
828     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
829     // iff target supports vfp2.
830     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
831     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
832   }
833
834   // We want to custom lower some of our intrinsics.
835   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
836   if (Subtarget->isTargetDarwin()) {
837     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
838     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
839     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
840   }
841
842   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
843   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
844   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
845   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
846   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
847   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
848   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
849   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
850   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
851
852   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
853   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
854   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
855   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
856   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
857
858   // We don't support sin/cos/fmod/copysign/pow
859   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
860   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
861   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
862   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
863   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
864   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
865   setOperationAction(ISD::FREM,      MVT::f64, Expand);
866   setOperationAction(ISD::FREM,      MVT::f32, Expand);
867   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
868       !Subtarget->isThumb1Only()) {
869     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
870     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
871   }
872   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
873   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
874
875   if (!Subtarget->hasVFP4()) {
876     setOperationAction(ISD::FMA, MVT::f64, Expand);
877     setOperationAction(ISD::FMA, MVT::f32, Expand);
878   }
879
880   // Various VFP goodness
881   if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
882     // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
883     if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
884       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
885       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
886     }
887
888     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
889     if (!Subtarget->hasFP16()) {
890       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
891       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
892     }
893   }
894
895   // Combine sin / cos into one node or libcall if possible.
896   if (Subtarget->hasSinCos()) {
897     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
898     setLibcallName(RTLIB::SINCOS_F64, "sincos");
899     if (Subtarget->getTargetTriple().isiOS()) {
900       // For iOS, we don't want to the normal expansion of a libcall to
901       // sincos. We want to issue a libcall to __sincos_stret.
902       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
903       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
904     }
905   }
906
907   // FP-ARMv8 implements a lot of rounding-like FP operations.
908   if (Subtarget->hasFPARMv8()) {
909     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
910     setOperationAction(ISD::FCEIL, MVT::f32, Legal);
911     setOperationAction(ISD::FROUND, MVT::f32, Legal);
912     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
913     setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
914     setOperationAction(ISD::FRINT, MVT::f32, Legal);
915     if (!Subtarget->isFPOnlySP()) {
916       setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
917       setOperationAction(ISD::FCEIL, MVT::f64, Legal);
918       setOperationAction(ISD::FROUND, MVT::f64, Legal);
919       setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
920       setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
921       setOperationAction(ISD::FRINT, MVT::f64, Legal);
922     }
923   }
924   // We have target-specific dag combine patterns for the following nodes:
925   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
926   setTargetDAGCombine(ISD::ADD);
927   setTargetDAGCombine(ISD::SUB);
928   setTargetDAGCombine(ISD::MUL);
929   setTargetDAGCombine(ISD::AND);
930   setTargetDAGCombine(ISD::OR);
931   setTargetDAGCombine(ISD::XOR);
932
933   if (Subtarget->hasV6Ops())
934     setTargetDAGCombine(ISD::SRL);
935
936   setStackPointerRegisterToSaveRestore(ARM::SP);
937
938   if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
939       !Subtarget->hasVFP2())
940     setSchedulingPreference(Sched::RegPressure);
941   else
942     setSchedulingPreference(Sched::Hybrid);
943
944   //// temporary - rewrite interface to use type
945   MaxStoresPerMemset = 8;
946   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
947   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
948   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
949   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
950   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
951
952   // On ARM arguments smaller than 4 bytes are extended, so all arguments
953   // are at least 4 bytes aligned.
954   setMinStackArgumentAlignment(4);
955
956   // Prefer likely predicted branches to selects on out-of-order cores.
957   PredictableSelectIsExpensive = Subtarget->isLikeA9();
958
959   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
960 }
961
962 bool ARMTargetLowering::useSoftFloat() const {
963   return Subtarget->useSoftFloat();
964 }
965
966 // FIXME: It might make sense to define the representative register class as the
967 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
968 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
969 // SPR's representative would be DPR_VFP2. This should work well if register
970 // pressure tracking were modified such that a register use would increment the
971 // pressure of the register class's representative and all of it's super
972 // classes' representatives transitively. We have not implemented this because
973 // of the difficulty prior to coalescing of modeling operand register classes
974 // due to the common occurrence of cross class copies and subregister insertions
975 // and extractions.
976 std::pair<const TargetRegisterClass *, uint8_t>
977 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
978                                            MVT VT) const {
979   const TargetRegisterClass *RRC = nullptr;
980   uint8_t Cost = 1;
981   switch (VT.SimpleTy) {
982   default:
983     return TargetLowering::findRepresentativeClass(TRI, VT);
984   // Use DPR as representative register class for all floating point
985   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
986   // the cost is 1 for both f32 and f64.
987   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
988   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
989     RRC = &ARM::DPRRegClass;
990     // When NEON is used for SP, only half of the register file is available
991     // because operations that define both SP and DP results will be constrained
992     // to the VFP2 class (D0-D15). We currently model this constraint prior to
993     // coalescing by double-counting the SP regs. See the FIXME above.
994     if (Subtarget->useNEONForSinglePrecisionFP())
995       Cost = 2;
996     break;
997   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
998   case MVT::v4f32: case MVT::v2f64:
999     RRC = &ARM::DPRRegClass;
1000     Cost = 2;
1001     break;
1002   case MVT::v4i64:
1003     RRC = &ARM::DPRRegClass;
1004     Cost = 4;
1005     break;
1006   case MVT::v8i64:
1007     RRC = &ARM::DPRRegClass;
1008     Cost = 8;
1009     break;
1010   }
1011   return std::make_pair(RRC, Cost);
1012 }
1013
1014 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1015   switch ((ARMISD::NodeType)Opcode) {
1016   case ARMISD::FIRST_NUMBER:  break;
1017   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1018   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1019   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1020   case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1021   case ARMISD::CALL:          return "ARMISD::CALL";
1022   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1023   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1024   case ARMISD::tCALL:         return "ARMISD::tCALL";
1025   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1026   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1027   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1028   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1029   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1030   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1031   case ARMISD::CMP:           return "ARMISD::CMP";
1032   case ARMISD::CMN:           return "ARMISD::CMN";
1033   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1034   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1035   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1036   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1037   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1038
1039   case ARMISD::CMOV:          return "ARMISD::CMOV";
1040
1041   case ARMISD::RBIT:          return "ARMISD::RBIT";
1042
1043   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1044   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1045   case ARMISD::RRX:           return "ARMISD::RRX";
1046
1047   case ARMISD::ADDC:          return "ARMISD::ADDC";
1048   case ARMISD::ADDE:          return "ARMISD::ADDE";
1049   case ARMISD::SUBC:          return "ARMISD::SUBC";
1050   case ARMISD::SUBE:          return "ARMISD::SUBE";
1051
1052   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1053   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1054
1055   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1056   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
1057
1058   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1059
1060   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1061
1062   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1063
1064   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1065
1066   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1067
1068   case ARMISD::WIN__CHKSTK:   return "ARMISD:::WIN__CHKSTK";
1069
1070   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1071   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1072   case ARMISD::VCGE:          return "ARMISD::VCGE";
1073   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1074   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1075   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1076   case ARMISD::VCGT:          return "ARMISD::VCGT";
1077   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1078   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1079   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1080   case ARMISD::VTST:          return "ARMISD::VTST";
1081
1082   case ARMISD::VSHL:          return "ARMISD::VSHL";
1083   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1084   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1085   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1086   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1087   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1088   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1089   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1090   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1091   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1092   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1093   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1094   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1095   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1096   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1097   case ARMISD::VSLI:          return "ARMISD::VSLI";
1098   case ARMISD::VSRI:          return "ARMISD::VSRI";
1099   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1100   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1101   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1102   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1103   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1104   case ARMISD::VDUP:          return "ARMISD::VDUP";
1105   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1106   case ARMISD::VEXT:          return "ARMISD::VEXT";
1107   case ARMISD::VREV64:        return "ARMISD::VREV64";
1108   case ARMISD::VREV32:        return "ARMISD::VREV32";
1109   case ARMISD::VREV16:        return "ARMISD::VREV16";
1110   case ARMISD::VZIP:          return "ARMISD::VZIP";
1111   case ARMISD::VUZP:          return "ARMISD::VUZP";
1112   case ARMISD::VTRN:          return "ARMISD::VTRN";
1113   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1114   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1115   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1116   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1117   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1118   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1119   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1120   case ARMISD::FMAX:          return "ARMISD::FMAX";
1121   case ARMISD::FMIN:          return "ARMISD::FMIN";
1122   case ARMISD::VMAXNM:        return "ARMISD::VMAX";
1123   case ARMISD::VMINNM:        return "ARMISD::VMIN";
1124   case ARMISD::BFI:           return "ARMISD::BFI";
1125   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1126   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1127   case ARMISD::VBSL:          return "ARMISD::VBSL";
1128   case ARMISD::MCOPY:         return "ARMISD::MCOPY";
1129   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1130   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1131   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1132   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1133   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1134   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1135   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1136   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1137   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1138   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1139   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1140   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1141   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1142   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1143   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1144   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1145   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1146   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1147   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1148   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1149   }
1150   return nullptr;
1151 }
1152
1153 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1154   if (!VT.isVector()) return getPointerTy();
1155   return VT.changeVectorElementTypeToInteger();
1156 }
1157
1158 /// getRegClassFor - Return the register class that should be used for the
1159 /// specified value type.
1160 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1161   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1162   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1163   // load / store 4 to 8 consecutive D registers.
1164   if (Subtarget->hasNEON()) {
1165     if (VT == MVT::v4i64)
1166       return &ARM::QQPRRegClass;
1167     if (VT == MVT::v8i64)
1168       return &ARM::QQQQPRRegClass;
1169   }
1170   return TargetLowering::getRegClassFor(VT);
1171 }
1172
1173 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1174 // source/dest is aligned and the copy size is large enough. We therefore want
1175 // to align such objects passed to memory intrinsics.
1176 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1177                                                unsigned &PrefAlign) const {
1178   if (!isa<MemIntrinsic>(CI))
1179     return false;
1180   MinSize = 8;
1181   // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1182   // cycle faster than 4-byte aligned LDM.
1183   PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1184   return true;
1185 }
1186
1187 // Create a fast isel object.
1188 FastISel *
1189 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1190                                   const TargetLibraryInfo *libInfo) const {
1191   return ARM::createFastISel(funcInfo, libInfo);
1192 }
1193
1194 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1195   unsigned NumVals = N->getNumValues();
1196   if (!NumVals)
1197     return Sched::RegPressure;
1198
1199   for (unsigned i = 0; i != NumVals; ++i) {
1200     EVT VT = N->getValueType(i);
1201     if (VT == MVT::Glue || VT == MVT::Other)
1202       continue;
1203     if (VT.isFloatingPoint() || VT.isVector())
1204       return Sched::ILP;
1205   }
1206
1207   if (!N->isMachineOpcode())
1208     return Sched::RegPressure;
1209
1210   // Load are scheduled for latency even if there instruction itinerary
1211   // is not available.
1212   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1213   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1214
1215   if (MCID.getNumDefs() == 0)
1216     return Sched::RegPressure;
1217   if (!Itins->isEmpty() &&
1218       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1219     return Sched::ILP;
1220
1221   return Sched::RegPressure;
1222 }
1223
1224 //===----------------------------------------------------------------------===//
1225 // Lowering Code
1226 //===----------------------------------------------------------------------===//
1227
1228 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1229 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1230   switch (CC) {
1231   default: llvm_unreachable("Unknown condition code!");
1232   case ISD::SETNE:  return ARMCC::NE;
1233   case ISD::SETEQ:  return ARMCC::EQ;
1234   case ISD::SETGT:  return ARMCC::GT;
1235   case ISD::SETGE:  return ARMCC::GE;
1236   case ISD::SETLT:  return ARMCC::LT;
1237   case ISD::SETLE:  return ARMCC::LE;
1238   case ISD::SETUGT: return ARMCC::HI;
1239   case ISD::SETUGE: return ARMCC::HS;
1240   case ISD::SETULT: return ARMCC::LO;
1241   case ISD::SETULE: return ARMCC::LS;
1242   }
1243 }
1244
1245 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1246 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1247                         ARMCC::CondCodes &CondCode2) {
1248   CondCode2 = ARMCC::AL;
1249   switch (CC) {
1250   default: llvm_unreachable("Unknown FP condition!");
1251   case ISD::SETEQ:
1252   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1253   case ISD::SETGT:
1254   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1255   case ISD::SETGE:
1256   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1257   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1258   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1259   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1260   case ISD::SETO:   CondCode = ARMCC::VC; break;
1261   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1262   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1263   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1264   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1265   case ISD::SETLT:
1266   case ISD::SETULT: CondCode = ARMCC::LT; break;
1267   case ISD::SETLE:
1268   case ISD::SETULE: CondCode = ARMCC::LE; break;
1269   case ISD::SETNE:
1270   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1271   }
1272 }
1273
1274 //===----------------------------------------------------------------------===//
1275 //                      Calling Convention Implementation
1276 //===----------------------------------------------------------------------===//
1277
1278 #include "ARMGenCallingConv.inc"
1279
1280 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1281 /// account presence of floating point hardware and calling convention
1282 /// limitations, such as support for variadic functions.
1283 CallingConv::ID
1284 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1285                                            bool isVarArg) const {
1286   switch (CC) {
1287   default:
1288     llvm_unreachable("Unsupported calling convention");
1289   case CallingConv::ARM_AAPCS:
1290   case CallingConv::ARM_APCS:
1291   case CallingConv::GHC:
1292     return CC;
1293   case CallingConv::ARM_AAPCS_VFP:
1294     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1295   case CallingConv::C:
1296     if (!Subtarget->isAAPCS_ABI())
1297       return CallingConv::ARM_APCS;
1298     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1299              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1300              !isVarArg)
1301       return CallingConv::ARM_AAPCS_VFP;
1302     else
1303       return CallingConv::ARM_AAPCS;
1304   case CallingConv::Fast:
1305     if (!Subtarget->isAAPCS_ABI()) {
1306       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1307         return CallingConv::Fast;
1308       return CallingConv::ARM_APCS;
1309     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1310       return CallingConv::ARM_AAPCS_VFP;
1311     else
1312       return CallingConv::ARM_AAPCS;
1313   }
1314 }
1315
1316 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1317 /// CallingConvention.
1318 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1319                                                  bool Return,
1320                                                  bool isVarArg) const {
1321   switch (getEffectiveCallingConv(CC, isVarArg)) {
1322   default:
1323     llvm_unreachable("Unsupported calling convention");
1324   case CallingConv::ARM_APCS:
1325     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1326   case CallingConv::ARM_AAPCS:
1327     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1328   case CallingConv::ARM_AAPCS_VFP:
1329     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1330   case CallingConv::Fast:
1331     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1332   case CallingConv::GHC:
1333     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1334   }
1335 }
1336
1337 /// LowerCallResult - Lower the result values of a call into the
1338 /// appropriate copies out of appropriate physical registers.
1339 SDValue
1340 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1341                                    CallingConv::ID CallConv, bool isVarArg,
1342                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1343                                    SDLoc dl, SelectionDAG &DAG,
1344                                    SmallVectorImpl<SDValue> &InVals,
1345                                    bool isThisReturn, SDValue ThisVal) const {
1346
1347   // Assign locations to each value returned by this call.
1348   SmallVector<CCValAssign, 16> RVLocs;
1349   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1350                     *DAG.getContext(), Call);
1351   CCInfo.AnalyzeCallResult(Ins,
1352                            CCAssignFnForNode(CallConv, /* Return*/ true,
1353                                              isVarArg));
1354
1355   // Copy all of the result registers out of their specified physreg.
1356   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1357     CCValAssign VA = RVLocs[i];
1358
1359     // Pass 'this' value directly from the argument to return value, to avoid
1360     // reg unit interference
1361     if (i == 0 && isThisReturn) {
1362       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1363              "unexpected return calling convention register assignment");
1364       InVals.push_back(ThisVal);
1365       continue;
1366     }
1367
1368     SDValue Val;
1369     if (VA.needsCustom()) {
1370       // Handle f64 or half of a v2f64.
1371       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1372                                       InFlag);
1373       Chain = Lo.getValue(1);
1374       InFlag = Lo.getValue(2);
1375       VA = RVLocs[++i]; // skip ahead to next loc
1376       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1377                                       InFlag);
1378       Chain = Hi.getValue(1);
1379       InFlag = Hi.getValue(2);
1380       if (!Subtarget->isLittle())
1381         std::swap (Lo, Hi);
1382       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1383
1384       if (VA.getLocVT() == MVT::v2f64) {
1385         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1386         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1387                           DAG.getConstant(0, dl, MVT::i32));
1388
1389         VA = RVLocs[++i]; // skip ahead to next loc
1390         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1391         Chain = Lo.getValue(1);
1392         InFlag = Lo.getValue(2);
1393         VA = RVLocs[++i]; // skip ahead to next loc
1394         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1395         Chain = Hi.getValue(1);
1396         InFlag = Hi.getValue(2);
1397         if (!Subtarget->isLittle())
1398           std::swap (Lo, Hi);
1399         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1400         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1401                           DAG.getConstant(1, dl, MVT::i32));
1402       }
1403     } else {
1404       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1405                                InFlag);
1406       Chain = Val.getValue(1);
1407       InFlag = Val.getValue(2);
1408     }
1409
1410     switch (VA.getLocInfo()) {
1411     default: llvm_unreachable("Unknown loc info!");
1412     case CCValAssign::Full: break;
1413     case CCValAssign::BCvt:
1414       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1415       break;
1416     }
1417
1418     InVals.push_back(Val);
1419   }
1420
1421   return Chain;
1422 }
1423
1424 /// LowerMemOpCallTo - Store the argument to the stack.
1425 SDValue
1426 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1427                                     SDValue StackPtr, SDValue Arg,
1428                                     SDLoc dl, SelectionDAG &DAG,
1429                                     const CCValAssign &VA,
1430                                     ISD::ArgFlagsTy Flags) const {
1431   unsigned LocMemOffset = VA.getLocMemOffset();
1432   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1433   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1434   return DAG.getStore(Chain, dl, Arg, PtrOff,
1435                       MachinePointerInfo::getStack(LocMemOffset),
1436                       false, false, 0);
1437 }
1438
1439 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1440                                          SDValue Chain, SDValue &Arg,
1441                                          RegsToPassVector &RegsToPass,
1442                                          CCValAssign &VA, CCValAssign &NextVA,
1443                                          SDValue &StackPtr,
1444                                          SmallVectorImpl<SDValue> &MemOpChains,
1445                                          ISD::ArgFlagsTy Flags) const {
1446
1447   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1448                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1449   unsigned id = Subtarget->isLittle() ? 0 : 1;
1450   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1451
1452   if (NextVA.isRegLoc())
1453     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1454   else {
1455     assert(NextVA.isMemLoc());
1456     if (!StackPtr.getNode())
1457       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1458
1459     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1460                                            dl, DAG, NextVA,
1461                                            Flags));
1462   }
1463 }
1464
1465 /// LowerCall - Lowering a call into a callseq_start <-
1466 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1467 /// nodes.
1468 SDValue
1469 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1470                              SmallVectorImpl<SDValue> &InVals) const {
1471   SelectionDAG &DAG                     = CLI.DAG;
1472   SDLoc &dl                             = CLI.DL;
1473   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1474   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1475   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1476   SDValue Chain                         = CLI.Chain;
1477   SDValue Callee                        = CLI.Callee;
1478   bool &isTailCall                      = CLI.IsTailCall;
1479   CallingConv::ID CallConv              = CLI.CallConv;
1480   bool doesNotRet                       = CLI.DoesNotReturn;
1481   bool isVarArg                         = CLI.IsVarArg;
1482
1483   MachineFunction &MF = DAG.getMachineFunction();
1484   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1485   bool isThisReturn   = false;
1486   bool isSibCall      = false;
1487
1488   // Disable tail calls if they're not supported.
1489   if (!Subtarget->supportsTailCall() || MF.getTarget().Options.DisableTailCalls)
1490     isTailCall = false;
1491
1492   if (isTailCall) {
1493     // Check if it's really possible to do a tail call.
1494     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1495                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1496                                                    Outs, OutVals, Ins, DAG);
1497     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1498       report_fatal_error("failed to perform tail call elimination on a call "
1499                          "site marked musttail");
1500     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1501     // detected sibcalls.
1502     if (isTailCall) {
1503       ++NumTailCalls;
1504       isSibCall = true;
1505     }
1506   }
1507
1508   // Analyze operands of the call, assigning locations to each operand.
1509   SmallVector<CCValAssign, 16> ArgLocs;
1510   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1511                     *DAG.getContext(), Call);
1512   CCInfo.AnalyzeCallOperands(Outs,
1513                              CCAssignFnForNode(CallConv, /* Return*/ false,
1514                                                isVarArg));
1515
1516   // Get a count of how many bytes are to be pushed on the stack.
1517   unsigned NumBytes = CCInfo.getNextStackOffset();
1518
1519   // For tail calls, memory operands are available in our caller's stack.
1520   if (isSibCall)
1521     NumBytes = 0;
1522
1523   // Adjust the stack pointer for the new arguments...
1524   // These operations are automatically eliminated by the prolog/epilog pass
1525   if (!isSibCall)
1526     Chain = DAG.getCALLSEQ_START(Chain,
1527                                  DAG.getIntPtrConstant(NumBytes, dl, true), dl);
1528
1529   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1530
1531   RegsToPassVector RegsToPass;
1532   SmallVector<SDValue, 8> MemOpChains;
1533
1534   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1535   // of tail call optimization, arguments are handled later.
1536   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1537        i != e;
1538        ++i, ++realArgIdx) {
1539     CCValAssign &VA = ArgLocs[i];
1540     SDValue Arg = OutVals[realArgIdx];
1541     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1542     bool isByVal = Flags.isByVal();
1543
1544     // Promote the value if needed.
1545     switch (VA.getLocInfo()) {
1546     default: llvm_unreachable("Unknown loc info!");
1547     case CCValAssign::Full: break;
1548     case CCValAssign::SExt:
1549       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1550       break;
1551     case CCValAssign::ZExt:
1552       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1553       break;
1554     case CCValAssign::AExt:
1555       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1556       break;
1557     case CCValAssign::BCvt:
1558       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1559       break;
1560     }
1561
1562     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1563     if (VA.needsCustom()) {
1564       if (VA.getLocVT() == MVT::v2f64) {
1565         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1566                                   DAG.getConstant(0, dl, MVT::i32));
1567         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1568                                   DAG.getConstant(1, dl, MVT::i32));
1569
1570         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1571                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1572
1573         VA = ArgLocs[++i]; // skip ahead to next loc
1574         if (VA.isRegLoc()) {
1575           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1576                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1577         } else {
1578           assert(VA.isMemLoc());
1579
1580           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1581                                                  dl, DAG, VA, Flags));
1582         }
1583       } else {
1584         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1585                          StackPtr, MemOpChains, Flags);
1586       }
1587     } else if (VA.isRegLoc()) {
1588       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1589         assert(VA.getLocVT() == MVT::i32 &&
1590                "unexpected calling convention register assignment");
1591         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1592                "unexpected use of 'returned'");
1593         isThisReturn = true;
1594       }
1595       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1596     } else if (isByVal) {
1597       assert(VA.isMemLoc());
1598       unsigned offset = 0;
1599
1600       // True if this byval aggregate will be split between registers
1601       // and memory.
1602       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1603       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1604
1605       if (CurByValIdx < ByValArgsCount) {
1606
1607         unsigned RegBegin, RegEnd;
1608         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1609
1610         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1611         unsigned int i, j;
1612         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1613           SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1614           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1615           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1616                                      MachinePointerInfo(),
1617                                      false, false, false,
1618                                      DAG.InferPtrAlignment(AddArg));
1619           MemOpChains.push_back(Load.getValue(1));
1620           RegsToPass.push_back(std::make_pair(j, Load));
1621         }
1622
1623         // If parameter size outsides register area, "offset" value
1624         // helps us to calculate stack slot for remained part properly.
1625         offset = RegEnd - RegBegin;
1626
1627         CCInfo.nextInRegsParam();
1628       }
1629
1630       if (Flags.getByValSize() > 4*offset) {
1631         unsigned LocMemOffset = VA.getLocMemOffset();
1632         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1633         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1634                                   StkPtrOff);
1635         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1636         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1637         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1638                                            MVT::i32);
1639         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1640                                             MVT::i32);
1641
1642         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1643         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1644         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1645                                           Ops));
1646       }
1647     } else if (!isSibCall) {
1648       assert(VA.isMemLoc());
1649
1650       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1651                                              dl, DAG, VA, Flags));
1652     }
1653   }
1654
1655   if (!MemOpChains.empty())
1656     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1657
1658   // Build a sequence of copy-to-reg nodes chained together with token chain
1659   // and flag operands which copy the outgoing args into the appropriate regs.
1660   SDValue InFlag;
1661   // Tail call byval lowering might overwrite argument registers so in case of
1662   // tail call optimization the copies to registers are lowered later.
1663   if (!isTailCall)
1664     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1665       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1666                                RegsToPass[i].second, InFlag);
1667       InFlag = Chain.getValue(1);
1668     }
1669
1670   // For tail calls lower the arguments to the 'real' stack slot.
1671   if (isTailCall) {
1672     // Force all the incoming stack arguments to be loaded from the stack
1673     // before any new outgoing arguments are stored to the stack, because the
1674     // outgoing stack slots may alias the incoming argument stack slots, and
1675     // the alias isn't otherwise explicit. This is slightly more conservative
1676     // than necessary, because it means that each store effectively depends
1677     // on every argument instead of just those arguments it would clobber.
1678
1679     // Do not flag preceding copytoreg stuff together with the following stuff.
1680     InFlag = SDValue();
1681     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1682       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1683                                RegsToPass[i].second, InFlag);
1684       InFlag = Chain.getValue(1);
1685     }
1686     InFlag = SDValue();
1687   }
1688
1689   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1690   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1691   // node so that legalize doesn't hack it.
1692   bool isDirect = false;
1693   bool isARMFunc = false;
1694   bool isLocalARMFunc = false;
1695   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1696
1697   if (EnableARMLongCalls) {
1698     assert((Subtarget->isTargetWindows() ||
1699             getTargetMachine().getRelocationModel() == Reloc::Static) &&
1700            "long-calls with non-static relocation model!");
1701     // Handle a global address or an external symbol. If it's not one of
1702     // those, the target's already in a register, so we don't need to do
1703     // anything extra.
1704     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1705       const GlobalValue *GV = G->getGlobal();
1706       // Create a constant pool entry for the callee address
1707       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1708       ARMConstantPoolValue *CPV =
1709         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1710
1711       // Get the address of the callee into a register
1712       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1713       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1714       Callee = DAG.getLoad(getPointerTy(), dl,
1715                            DAG.getEntryNode(), CPAddr,
1716                            MachinePointerInfo::getConstantPool(),
1717                            false, false, false, 0);
1718     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1719       const char *Sym = S->getSymbol();
1720
1721       // Create a constant pool entry for the callee address
1722       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1723       ARMConstantPoolValue *CPV =
1724         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1725                                       ARMPCLabelIndex, 0);
1726       // Get the address of the callee into a register
1727       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1728       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1729       Callee = DAG.getLoad(getPointerTy(), dl,
1730                            DAG.getEntryNode(), CPAddr,
1731                            MachinePointerInfo::getConstantPool(),
1732                            false, false, false, 0);
1733     }
1734   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1735     const GlobalValue *GV = G->getGlobal();
1736     isDirect = true;
1737     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1738     bool isStub = (isExt && Subtarget->isTargetMachO()) &&
1739                    getTargetMachine().getRelocationModel() != Reloc::Static;
1740     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1741     // ARM call to a local ARM function is predicable.
1742     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1743     // tBX takes a register source operand.
1744     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1745       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1746       Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1747                            DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
1748                                                       0, ARMII::MO_NONLAZY));
1749       Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
1750                            MachinePointerInfo::getGOT(), false, false, true, 0);
1751     } else if (Subtarget->isTargetCOFF()) {
1752       assert(Subtarget->isTargetWindows() &&
1753              "Windows is the only supported COFF target");
1754       unsigned TargetFlags = GV->hasDLLImportStorageClass()
1755                                  ? ARMII::MO_DLLIMPORT
1756                                  : ARMII::MO_NO_FLAG;
1757       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), /*Offset=*/0,
1758                                           TargetFlags);
1759       if (GV->hasDLLImportStorageClass())
1760         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
1761                              DAG.getNode(ARMISD::Wrapper, dl, getPointerTy(),
1762                                          Callee), MachinePointerInfo::getGOT(),
1763                              false, false, false, 0);
1764     } else {
1765       // On ELF targets for PIC code, direct calls should go through the PLT
1766       unsigned OpFlags = 0;
1767       if (Subtarget->isTargetELF() &&
1768           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1769         OpFlags = ARMII::MO_PLT;
1770       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1771     }
1772   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1773     isDirect = true;
1774     bool isStub = Subtarget->isTargetMachO() &&
1775                   getTargetMachine().getRelocationModel() != Reloc::Static;
1776     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1777     // tBX takes a register source operand.
1778     const char *Sym = S->getSymbol();
1779     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1780       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1781       ARMConstantPoolValue *CPV =
1782         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1783                                       ARMPCLabelIndex, 4);
1784       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1785       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1786       Callee = DAG.getLoad(getPointerTy(), dl,
1787                            DAG.getEntryNode(), CPAddr,
1788                            MachinePointerInfo::getConstantPool(),
1789                            false, false, false, 0);
1790       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
1791       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1792                            getPointerTy(), Callee, PICLabel);
1793     } else {
1794       unsigned OpFlags = 0;
1795       // On ELF targets for PIC code, direct calls should go through the PLT
1796       if (Subtarget->isTargetELF() &&
1797                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1798         OpFlags = ARMII::MO_PLT;
1799       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1800     }
1801   }
1802
1803   // FIXME: handle tail calls differently.
1804   unsigned CallOpc;
1805   bool HasMinSizeAttr = MF.getFunction()->hasFnAttribute(Attribute::MinSize);
1806   if (Subtarget->isThumb()) {
1807     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1808       CallOpc = ARMISD::CALL_NOLINK;
1809     else
1810       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1811   } else {
1812     if (!isDirect && !Subtarget->hasV5TOps())
1813       CallOpc = ARMISD::CALL_NOLINK;
1814     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1815                // Emit regular call when code size is the priority
1816                !HasMinSizeAttr)
1817       // "mov lr, pc; b _foo" to avoid confusing the RSP
1818       CallOpc = ARMISD::CALL_NOLINK;
1819     else
1820       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1821   }
1822
1823   std::vector<SDValue> Ops;
1824   Ops.push_back(Chain);
1825   Ops.push_back(Callee);
1826
1827   // Add argument registers to the end of the list so that they are known live
1828   // into the call.
1829   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1830     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1831                                   RegsToPass[i].second.getValueType()));
1832
1833   // Add a register mask operand representing the call-preserved registers.
1834   if (!isTailCall) {
1835     const uint32_t *Mask;
1836     const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
1837     if (isThisReturn) {
1838       // For 'this' returns, use the R0-preserving mask if applicable
1839       Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
1840       if (!Mask) {
1841         // Set isThisReturn to false if the calling convention is not one that
1842         // allows 'returned' to be modeled in this way, so LowerCallResult does
1843         // not try to pass 'this' straight through
1844         isThisReturn = false;
1845         Mask = ARI->getCallPreservedMask(MF, CallConv);
1846       }
1847     } else
1848       Mask = ARI->getCallPreservedMask(MF, CallConv);
1849
1850     assert(Mask && "Missing call preserved mask for calling convention");
1851     Ops.push_back(DAG.getRegisterMask(Mask));
1852   }
1853
1854   if (InFlag.getNode())
1855     Ops.push_back(InFlag);
1856
1857   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1858   if (isTailCall) {
1859     MF.getFrameInfo()->setHasTailCall();
1860     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1861   }
1862
1863   // Returns a chain and a flag for retval copy to use.
1864   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1865   InFlag = Chain.getValue(1);
1866
1867   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
1868                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
1869   if (!Ins.empty())
1870     InFlag = Chain.getValue(1);
1871
1872   // Handle result values, copying them out of physregs into vregs that we
1873   // return.
1874   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1875                          InVals, isThisReturn,
1876                          isThisReturn ? OutVals[0] : SDValue());
1877 }
1878
1879 /// HandleByVal - Every parameter *after* a byval parameter is passed
1880 /// on the stack.  Remember the next parameter register to allocate,
1881 /// and then confiscate the rest of the parameter registers to insure
1882 /// this.
1883 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
1884                                     unsigned Align) const {
1885   assert((State->getCallOrPrologue() == Prologue ||
1886           State->getCallOrPrologue() == Call) &&
1887          "unhandled ParmContext");
1888
1889   // Byval (as with any stack) slots are always at least 4 byte aligned.
1890   Align = std::max(Align, 4U);
1891
1892   unsigned Reg = State->AllocateReg(GPRArgRegs);
1893   if (!Reg)
1894     return;
1895
1896   unsigned AlignInRegs = Align / 4;
1897   unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
1898   for (unsigned i = 0; i < Waste; ++i)
1899     Reg = State->AllocateReg(GPRArgRegs);
1900
1901   if (!Reg)
1902     return;
1903
1904   unsigned Excess = 4 * (ARM::R4 - Reg);
1905
1906   // Special case when NSAA != SP and parameter size greater than size of
1907   // all remained GPR regs. In that case we can't split parameter, we must
1908   // send it to stack. We also must set NCRN to R4, so waste all
1909   // remained registers.
1910   const unsigned NSAAOffset = State->getNextStackOffset();
1911   if (NSAAOffset != 0 && Size > Excess) {
1912     while (State->AllocateReg(GPRArgRegs))
1913       ;
1914     return;
1915   }
1916
1917   // First register for byval parameter is the first register that wasn't
1918   // allocated before this method call, so it would be "reg".
1919   // If parameter is small enough to be saved in range [reg, r4), then
1920   // the end (first after last) register would be reg + param-size-in-regs,
1921   // else parameter would be splitted between registers and stack,
1922   // end register would be r4 in this case.
1923   unsigned ByValRegBegin = Reg;
1924   unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
1925   State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1926   // Note, first register is allocated in the beginning of function already,
1927   // allocate remained amount of registers we need.
1928   for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
1929     State->AllocateReg(GPRArgRegs);
1930   // A byval parameter that is split between registers and memory needs its
1931   // size truncated here.
1932   // In the case where the entire structure fits in registers, we set the
1933   // size in memory to zero.
1934   Size = std::max<int>(Size - Excess, 0);
1935 }
1936
1937 /// MatchingStackOffset - Return true if the given stack call argument is
1938 /// already available in the same position (relatively) of the caller's
1939 /// incoming argument stack.
1940 static
1941 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1942                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1943                          const TargetInstrInfo *TII) {
1944   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1945   int FI = INT_MAX;
1946   if (Arg.getOpcode() == ISD::CopyFromReg) {
1947     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1948     if (!TargetRegisterInfo::isVirtualRegister(VR))
1949       return false;
1950     MachineInstr *Def = MRI->getVRegDef(VR);
1951     if (!Def)
1952       return false;
1953     if (!Flags.isByVal()) {
1954       if (!TII->isLoadFromStackSlot(Def, FI))
1955         return false;
1956     } else {
1957       return false;
1958     }
1959   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1960     if (Flags.isByVal())
1961       // ByVal argument is passed in as a pointer but it's now being
1962       // dereferenced. e.g.
1963       // define @foo(%struct.X* %A) {
1964       //   tail call @bar(%struct.X* byval %A)
1965       // }
1966       return false;
1967     SDValue Ptr = Ld->getBasePtr();
1968     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1969     if (!FINode)
1970       return false;
1971     FI = FINode->getIndex();
1972   } else
1973     return false;
1974
1975   assert(FI != INT_MAX);
1976   if (!MFI->isFixedObjectIndex(FI))
1977     return false;
1978   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1979 }
1980
1981 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1982 /// for tail call optimization. Targets which want to do tail call
1983 /// optimization should implement this function.
1984 bool
1985 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1986                                                      CallingConv::ID CalleeCC,
1987                                                      bool isVarArg,
1988                                                      bool isCalleeStructRet,
1989                                                      bool isCallerStructRet,
1990                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1991                                     const SmallVectorImpl<SDValue> &OutVals,
1992                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1993                                                      SelectionDAG& DAG) const {
1994   const Function *CallerF = DAG.getMachineFunction().getFunction();
1995   CallingConv::ID CallerCC = CallerF->getCallingConv();
1996   bool CCMatch = CallerCC == CalleeCC;
1997
1998   // Look for obvious safe cases to perform tail call optimization that do not
1999   // require ABI changes. This is what gcc calls sibcall.
2000
2001   // Do not sibcall optimize vararg calls unless the call site is not passing
2002   // any arguments.
2003   if (isVarArg && !Outs.empty())
2004     return false;
2005
2006   // Exception-handling functions need a special set of instructions to indicate
2007   // a return to the hardware. Tail-calling another function would probably
2008   // break this.
2009   if (CallerF->hasFnAttribute("interrupt"))
2010     return false;
2011
2012   // Also avoid sibcall optimization if either caller or callee uses struct
2013   // return semantics.
2014   if (isCalleeStructRet || isCallerStructRet)
2015     return false;
2016
2017   // FIXME: Completely disable sibcall for Thumb1 since ThumbRegisterInfo::
2018   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
2019   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
2020   // support in the assembler and linker to be used. This would need to be
2021   // fixed to fully support tail calls in Thumb1.
2022   //
2023   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
2024   // LR.  This means if we need to reload LR, it takes an extra instructions,
2025   // which outweighs the value of the tail call; but here we don't know yet
2026   // whether LR is going to be used.  Probably the right approach is to
2027   // generate the tail call here and turn it back into CALL/RET in
2028   // emitEpilogue if LR is used.
2029
2030   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
2031   // but we need to make sure there are enough registers; the only valid
2032   // registers are the 4 used for parameters.  We don't currently do this
2033   // case.
2034   if (Subtarget->isThumb1Only())
2035     return false;
2036
2037   // Externally-defined functions with weak linkage should not be
2038   // tail-called on ARM when the OS does not support dynamic
2039   // pre-emption of symbols, as the AAELF spec requires normal calls
2040   // to undefined weak functions to be replaced with a NOP or jump to the
2041   // next instruction. The behaviour of branch instructions in this
2042   // situation (as used for tail calls) is implementation-defined, so we
2043   // cannot rely on the linker replacing the tail call with a return.
2044   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2045     const GlobalValue *GV = G->getGlobal();
2046     const Triple TT(getTargetMachine().getTargetTriple());
2047     if (GV->hasExternalWeakLinkage() &&
2048         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2049       return false;
2050   }
2051
2052   // If the calling conventions do not match, then we'd better make sure the
2053   // results are returned in the same way as what the caller expects.
2054   if (!CCMatch) {
2055     SmallVector<CCValAssign, 16> RVLocs1;
2056     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2057                        *DAG.getContext(), Call);
2058     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2059
2060     SmallVector<CCValAssign, 16> RVLocs2;
2061     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2062                        *DAG.getContext(), Call);
2063     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2064
2065     if (RVLocs1.size() != RVLocs2.size())
2066       return false;
2067     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2068       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2069         return false;
2070       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2071         return false;
2072       if (RVLocs1[i].isRegLoc()) {
2073         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2074           return false;
2075       } else {
2076         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2077           return false;
2078       }
2079     }
2080   }
2081
2082   // If Caller's vararg or byval argument has been split between registers and
2083   // stack, do not perform tail call, since part of the argument is in caller's
2084   // local frame.
2085   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2086                                       getInfo<ARMFunctionInfo>();
2087   if (AFI_Caller->getArgRegsSaveSize())
2088     return false;
2089
2090   // If the callee takes no arguments then go on to check the results of the
2091   // call.
2092   if (!Outs.empty()) {
2093     // Check if stack adjustment is needed. For now, do not do this if any
2094     // argument is passed on the stack.
2095     SmallVector<CCValAssign, 16> ArgLocs;
2096     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2097                       *DAG.getContext(), Call);
2098     CCInfo.AnalyzeCallOperands(Outs,
2099                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2100     if (CCInfo.getNextStackOffset()) {
2101       MachineFunction &MF = DAG.getMachineFunction();
2102
2103       // Check if the arguments are already laid out in the right way as
2104       // the caller's fixed stack objects.
2105       MachineFrameInfo *MFI = MF.getFrameInfo();
2106       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2107       const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2108       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2109            i != e;
2110            ++i, ++realArgIdx) {
2111         CCValAssign &VA = ArgLocs[i];
2112         EVT RegVT = VA.getLocVT();
2113         SDValue Arg = OutVals[realArgIdx];
2114         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2115         if (VA.getLocInfo() == CCValAssign::Indirect)
2116           return false;
2117         if (VA.needsCustom()) {
2118           // f64 and vector types are split into multiple registers or
2119           // register/stack-slot combinations.  The types will not match
2120           // the registers; give up on memory f64 refs until we figure
2121           // out what to do about this.
2122           if (!VA.isRegLoc())
2123             return false;
2124           if (!ArgLocs[++i].isRegLoc())
2125             return false;
2126           if (RegVT == MVT::v2f64) {
2127             if (!ArgLocs[++i].isRegLoc())
2128               return false;
2129             if (!ArgLocs[++i].isRegLoc())
2130               return false;
2131           }
2132         } else if (!VA.isRegLoc()) {
2133           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2134                                    MFI, MRI, TII))
2135             return false;
2136         }
2137       }
2138     }
2139   }
2140
2141   return true;
2142 }
2143
2144 bool
2145 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2146                                   MachineFunction &MF, bool isVarArg,
2147                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2148                                   LLVMContext &Context) const {
2149   SmallVector<CCValAssign, 16> RVLocs;
2150   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2151   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2152                                                     isVarArg));
2153 }
2154
2155 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2156                                     SDLoc DL, SelectionDAG &DAG) {
2157   const MachineFunction &MF = DAG.getMachineFunction();
2158   const Function *F = MF.getFunction();
2159
2160   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2161
2162   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2163   // version of the "preferred return address". These offsets affect the return
2164   // instruction if this is a return from PL1 without hypervisor extensions.
2165   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2166   //    SWI:     0      "subs pc, lr, #0"
2167   //    ABORT:   +4     "subs pc, lr, #4"
2168   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2169   // UNDEF varies depending on where the exception came from ARM or Thumb
2170   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2171
2172   int64_t LROffset;
2173   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2174       IntKind == "ABORT")
2175     LROffset = 4;
2176   else if (IntKind == "SWI" || IntKind == "UNDEF")
2177     LROffset = 0;
2178   else
2179     report_fatal_error("Unsupported interrupt attribute. If present, value "
2180                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2181
2182   RetOps.insert(RetOps.begin() + 1,
2183                 DAG.getConstant(LROffset, DL, MVT::i32, false));
2184
2185   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2186 }
2187
2188 SDValue
2189 ARMTargetLowering::LowerReturn(SDValue Chain,
2190                                CallingConv::ID CallConv, bool isVarArg,
2191                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2192                                const SmallVectorImpl<SDValue> &OutVals,
2193                                SDLoc dl, SelectionDAG &DAG) const {
2194
2195   // CCValAssign - represent the assignment of the return value to a location.
2196   SmallVector<CCValAssign, 16> RVLocs;
2197
2198   // CCState - Info about the registers and stack slots.
2199   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2200                     *DAG.getContext(), Call);
2201
2202   // Analyze outgoing return values.
2203   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2204                                                isVarArg));
2205
2206   SDValue Flag;
2207   SmallVector<SDValue, 4> RetOps;
2208   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2209   bool isLittleEndian = Subtarget->isLittle();
2210
2211   MachineFunction &MF = DAG.getMachineFunction();
2212   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2213   AFI->setReturnRegsCount(RVLocs.size());
2214
2215   // Copy the result values into the output registers.
2216   for (unsigned i = 0, realRVLocIdx = 0;
2217        i != RVLocs.size();
2218        ++i, ++realRVLocIdx) {
2219     CCValAssign &VA = RVLocs[i];
2220     assert(VA.isRegLoc() && "Can only return in registers!");
2221
2222     SDValue Arg = OutVals[realRVLocIdx];
2223
2224     switch (VA.getLocInfo()) {
2225     default: llvm_unreachable("Unknown loc info!");
2226     case CCValAssign::Full: break;
2227     case CCValAssign::BCvt:
2228       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2229       break;
2230     }
2231
2232     if (VA.needsCustom()) {
2233       if (VA.getLocVT() == MVT::v2f64) {
2234         // Extract the first half and return it in two registers.
2235         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2236                                    DAG.getConstant(0, dl, MVT::i32));
2237         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2238                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2239
2240         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2241                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2242                                  Flag);
2243         Flag = Chain.getValue(1);
2244         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2245         VA = RVLocs[++i]; // skip ahead to next loc
2246         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2247                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2248                                  Flag);
2249         Flag = Chain.getValue(1);
2250         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2251         VA = RVLocs[++i]; // skip ahead to next loc
2252
2253         // Extract the 2nd half and fall through to handle it as an f64 value.
2254         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2255                           DAG.getConstant(1, dl, MVT::i32));
2256       }
2257       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2258       // available.
2259       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2260                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2261       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2262                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2263                                Flag);
2264       Flag = Chain.getValue(1);
2265       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2266       VA = RVLocs[++i]; // skip ahead to next loc
2267       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2268                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2269                                Flag);
2270     } else
2271       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2272
2273     // Guarantee that all emitted copies are
2274     // stuck together, avoiding something bad.
2275     Flag = Chain.getValue(1);
2276     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2277   }
2278
2279   // Update chain and glue.
2280   RetOps[0] = Chain;
2281   if (Flag.getNode())
2282     RetOps.push_back(Flag);
2283
2284   // CPUs which aren't M-class use a special sequence to return from
2285   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2286   // though we use "subs pc, lr, #N").
2287   //
2288   // M-class CPUs actually use a normal return sequence with a special
2289   // (hardware-provided) value in LR, so the normal code path works.
2290   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2291       !Subtarget->isMClass()) {
2292     if (Subtarget->isThumb1Only())
2293       report_fatal_error("interrupt attribute is not supported in Thumb1");
2294     return LowerInterruptReturn(RetOps, dl, DAG);
2295   }
2296
2297   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2298 }
2299
2300 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2301   if (N->getNumValues() != 1)
2302     return false;
2303   if (!N->hasNUsesOfValue(1, 0))
2304     return false;
2305
2306   SDValue TCChain = Chain;
2307   SDNode *Copy = *N->use_begin();
2308   if (Copy->getOpcode() == ISD::CopyToReg) {
2309     // If the copy has a glue operand, we conservatively assume it isn't safe to
2310     // perform a tail call.
2311     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2312       return false;
2313     TCChain = Copy->getOperand(0);
2314   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2315     SDNode *VMov = Copy;
2316     // f64 returned in a pair of GPRs.
2317     SmallPtrSet<SDNode*, 2> Copies;
2318     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2319          UI != UE; ++UI) {
2320       if (UI->getOpcode() != ISD::CopyToReg)
2321         return false;
2322       Copies.insert(*UI);
2323     }
2324     if (Copies.size() > 2)
2325       return false;
2326
2327     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2328          UI != UE; ++UI) {
2329       SDValue UseChain = UI->getOperand(0);
2330       if (Copies.count(UseChain.getNode()))
2331         // Second CopyToReg
2332         Copy = *UI;
2333       else {
2334         // We are at the top of this chain.
2335         // If the copy has a glue operand, we conservatively assume it
2336         // isn't safe to perform a tail call.
2337         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2338           return false;
2339         // First CopyToReg
2340         TCChain = UseChain;
2341       }
2342     }
2343   } else if (Copy->getOpcode() == ISD::BITCAST) {
2344     // f32 returned in a single GPR.
2345     if (!Copy->hasOneUse())
2346       return false;
2347     Copy = *Copy->use_begin();
2348     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2349       return false;
2350     // If the copy has a glue operand, we conservatively assume it isn't safe to
2351     // perform a tail call.
2352     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2353       return false;
2354     TCChain = Copy->getOperand(0);
2355   } else {
2356     return false;
2357   }
2358
2359   bool HasRet = false;
2360   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2361        UI != UE; ++UI) {
2362     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2363         UI->getOpcode() != ARMISD::INTRET_FLAG)
2364       return false;
2365     HasRet = true;
2366   }
2367
2368   if (!HasRet)
2369     return false;
2370
2371   Chain = TCChain;
2372   return true;
2373 }
2374
2375 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2376   if (!Subtarget->supportsTailCall())
2377     return false;
2378
2379   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2380     return false;
2381
2382   return !Subtarget->isThumb1Only();
2383 }
2384
2385 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2386 // and pass the lower and high parts through.
2387 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2388   SDLoc DL(Op);
2389   SDValue WriteValue = Op->getOperand(2);
2390
2391   // This function is only supposed to be called for i64 type argument.
2392   assert(WriteValue.getValueType() == MVT::i64
2393           && "LowerWRITE_REGISTER called for non-i64 type argument.");
2394
2395   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2396                            DAG.getConstant(0, DL, MVT::i32));
2397   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2398                            DAG.getConstant(1, DL, MVT::i32));
2399   SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2400   return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2401 }
2402
2403 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2404 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2405 // one of the above mentioned nodes. It has to be wrapped because otherwise
2406 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2407 // be used to form addressing mode. These wrapped nodes will be selected
2408 // into MOVi.
2409 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2410   EVT PtrVT = Op.getValueType();
2411   // FIXME there is no actual debug info here
2412   SDLoc dl(Op);
2413   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2414   SDValue Res;
2415   if (CP->isMachineConstantPoolEntry())
2416     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2417                                     CP->getAlignment());
2418   else
2419     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2420                                     CP->getAlignment());
2421   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2422 }
2423
2424 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2425   return MachineJumpTableInfo::EK_Inline;
2426 }
2427
2428 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2429                                              SelectionDAG &DAG) const {
2430   MachineFunction &MF = DAG.getMachineFunction();
2431   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2432   unsigned ARMPCLabelIndex = 0;
2433   SDLoc DL(Op);
2434   EVT PtrVT = getPointerTy();
2435   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2436   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2437   SDValue CPAddr;
2438   if (RelocM == Reloc::Static) {
2439     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2440   } else {
2441     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2442     ARMPCLabelIndex = AFI->createPICLabelUId();
2443     ARMConstantPoolValue *CPV =
2444       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2445                                       ARMCP::CPBlockAddress, PCAdj);
2446     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2447   }
2448   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2449   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2450                                MachinePointerInfo::getConstantPool(),
2451                                false, false, false, 0);
2452   if (RelocM == Reloc::Static)
2453     return Result;
2454   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2455   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2456 }
2457
2458 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2459 SDValue
2460 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2461                                                  SelectionDAG &DAG) const {
2462   SDLoc dl(GA);
2463   EVT PtrVT = getPointerTy();
2464   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2465   MachineFunction &MF = DAG.getMachineFunction();
2466   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2467   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2468   ARMConstantPoolValue *CPV =
2469     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2470                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2471   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2472   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2473   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2474                          MachinePointerInfo::getConstantPool(),
2475                          false, false, false, 0);
2476   SDValue Chain = Argument.getValue(1);
2477
2478   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2479   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2480
2481   // call __tls_get_addr.
2482   ArgListTy Args;
2483   ArgListEntry Entry;
2484   Entry.Node = Argument;
2485   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2486   Args.push_back(Entry);
2487
2488   // FIXME: is there useful debug info available here?
2489   TargetLowering::CallLoweringInfo CLI(DAG);
2490   CLI.setDebugLoc(dl).setChain(Chain)
2491     .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2492                DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2493                0);
2494
2495   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2496   return CallResult.first;
2497 }
2498
2499 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2500 // "local exec" model.
2501 SDValue
2502 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2503                                         SelectionDAG &DAG,
2504                                         TLSModel::Model model) const {
2505   const GlobalValue *GV = GA->getGlobal();
2506   SDLoc dl(GA);
2507   SDValue Offset;
2508   SDValue Chain = DAG.getEntryNode();
2509   EVT PtrVT = getPointerTy();
2510   // Get the Thread Pointer
2511   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2512
2513   if (model == TLSModel::InitialExec) {
2514     MachineFunction &MF = DAG.getMachineFunction();
2515     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2516     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2517     // Initial exec model.
2518     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2519     ARMConstantPoolValue *CPV =
2520       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2521                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2522                                       true);
2523     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2524     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2525     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2526                          MachinePointerInfo::getConstantPool(),
2527                          false, false, false, 0);
2528     Chain = Offset.getValue(1);
2529
2530     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2531     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2532
2533     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2534                          MachinePointerInfo::getConstantPool(),
2535                          false, false, false, 0);
2536   } else {
2537     // local exec model
2538     assert(model == TLSModel::LocalExec);
2539     ARMConstantPoolValue *CPV =
2540       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2541     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2542     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2543     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2544                          MachinePointerInfo::getConstantPool(),
2545                          false, false, false, 0);
2546   }
2547
2548   // The address of the thread local variable is the add of the thread
2549   // pointer with the offset of the variable.
2550   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2551 }
2552
2553 SDValue
2554 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2555   // TODO: implement the "local dynamic" model
2556   assert(Subtarget->isTargetELF() &&
2557          "TLS not implemented for non-ELF targets");
2558   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2559
2560   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2561
2562   switch (model) {
2563     case TLSModel::GeneralDynamic:
2564     case TLSModel::LocalDynamic:
2565       return LowerToTLSGeneralDynamicModel(GA, DAG);
2566     case TLSModel::InitialExec:
2567     case TLSModel::LocalExec:
2568       return LowerToTLSExecModels(GA, DAG, model);
2569   }
2570   llvm_unreachable("bogus TLS model");
2571 }
2572
2573 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2574                                                  SelectionDAG &DAG) const {
2575   EVT PtrVT = getPointerTy();
2576   SDLoc dl(Op);
2577   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2578   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2579     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2580     ARMConstantPoolValue *CPV =
2581       ARMConstantPoolConstant::Create(GV,
2582                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2583     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2584     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2585     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2586                                  CPAddr,
2587                                  MachinePointerInfo::getConstantPool(),
2588                                  false, false, false, 0);
2589     SDValue Chain = Result.getValue(1);
2590     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2591     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2592     if (!UseGOTOFF)
2593       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2594                            MachinePointerInfo::getGOT(),
2595                            false, false, false, 0);
2596     return Result;
2597   }
2598
2599   // If we have T2 ops, we can materialize the address directly via movt/movw
2600   // pair. This is always cheaper.
2601   if (Subtarget->useMovt(DAG.getMachineFunction())) {
2602     ++NumMovwMovt;
2603     // FIXME: Once remat is capable of dealing with instructions with register
2604     // operands, expand this into two nodes.
2605     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2606                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2607   } else {
2608     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2609     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2610     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2611                        MachinePointerInfo::getConstantPool(),
2612                        false, false, false, 0);
2613   }
2614 }
2615
2616 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2617                                                     SelectionDAG &DAG) const {
2618   EVT PtrVT = getPointerTy();
2619   SDLoc dl(Op);
2620   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2621   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2622
2623   if (Subtarget->useMovt(DAG.getMachineFunction()))
2624     ++NumMovwMovt;
2625
2626   // FIXME: Once remat is capable of dealing with instructions with register
2627   // operands, expand this into multiple nodes
2628   unsigned Wrapper =
2629       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2630
2631   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2632   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2633
2634   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2635     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2636                          MachinePointerInfo::getGOT(), false, false, false, 0);
2637   return Result;
2638 }
2639
2640 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2641                                                      SelectionDAG &DAG) const {
2642   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2643   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2644          "Windows on ARM expects to use movw/movt");
2645
2646   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2647   const ARMII::TOF TargetFlags =
2648     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2649   EVT PtrVT = getPointerTy();
2650   SDValue Result;
2651   SDLoc DL(Op);
2652
2653   ++NumMovwMovt;
2654
2655   // FIXME: Once remat is capable of dealing with instructions with register
2656   // operands, expand this into two nodes.
2657   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2658                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2659                                                   TargetFlags));
2660   if (GV->hasDLLImportStorageClass())
2661     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2662                          MachinePointerInfo::getGOT(), false, false, false, 0);
2663   return Result;
2664 }
2665
2666 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2667                                                     SelectionDAG &DAG) const {
2668   assert(Subtarget->isTargetELF() &&
2669          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2670   MachineFunction &MF = DAG.getMachineFunction();
2671   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2672   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2673   EVT PtrVT = getPointerTy();
2674   SDLoc dl(Op);
2675   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2676   ARMConstantPoolValue *CPV =
2677     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2678                                   ARMPCLabelIndex, PCAdj);
2679   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2680   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2681   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2682                                MachinePointerInfo::getConstantPool(),
2683                                false, false, false, 0);
2684   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2685   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2686 }
2687
2688 SDValue
2689 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2690   SDLoc dl(Op);
2691   SDValue Val = DAG.getConstant(0, dl, MVT::i32);
2692   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2693                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2694                      Op.getOperand(1), Val);
2695 }
2696
2697 SDValue
2698 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2699   SDLoc dl(Op);
2700   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2701                      Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
2702 }
2703
2704 SDValue
2705 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2706                                           const ARMSubtarget *Subtarget) const {
2707   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2708   SDLoc dl(Op);
2709   switch (IntNo) {
2710   default: return SDValue();    // Don't custom lower most intrinsics.
2711   case Intrinsic::arm_rbit: {
2712     assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2713            "RBIT intrinsic must have i32 type!");
2714     return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1));
2715   }
2716   case Intrinsic::arm_thread_pointer: {
2717     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2718     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2719   }
2720   case Intrinsic::eh_sjlj_lsda: {
2721     MachineFunction &MF = DAG.getMachineFunction();
2722     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2723     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2724     EVT PtrVT = getPointerTy();
2725     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2726     SDValue CPAddr;
2727     unsigned PCAdj = (RelocM != Reloc::PIC_)
2728       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2729     ARMConstantPoolValue *CPV =
2730       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2731                                       ARMCP::CPLSDA, PCAdj);
2732     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2733     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2734     SDValue Result =
2735       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2736                   MachinePointerInfo::getConstantPool(),
2737                   false, false, false, 0);
2738
2739     if (RelocM == Reloc::PIC_) {
2740       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2741       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2742     }
2743     return Result;
2744   }
2745   case Intrinsic::arm_neon_vmulls:
2746   case Intrinsic::arm_neon_vmullu: {
2747     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2748       ? ARMISD::VMULLs : ARMISD::VMULLu;
2749     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2750                        Op.getOperand(1), Op.getOperand(2));
2751   }
2752   }
2753 }
2754
2755 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2756                                  const ARMSubtarget *Subtarget) {
2757   // FIXME: handle "fence singlethread" more efficiently.
2758   SDLoc dl(Op);
2759   if (!Subtarget->hasDataBarrier()) {
2760     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2761     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2762     // here.
2763     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2764            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2765     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2766                        DAG.getConstant(0, dl, MVT::i32));
2767   }
2768
2769   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2770   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2771   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
2772   if (Subtarget->isMClass()) {
2773     // Only a full system barrier exists in the M-class architectures.
2774     Domain = ARM_MB::SY;
2775   } else if (Subtarget->isSwift() && Ord == Release) {
2776     // Swift happens to implement ISHST barriers in a way that's compatible with
2777     // Release semantics but weaker than ISH so we'd be fools not to use
2778     // it. Beware: other processors probably don't!
2779     Domain = ARM_MB::ISHST;
2780   }
2781
2782   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2783                      DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
2784                      DAG.getConstant(Domain, dl, MVT::i32));
2785 }
2786
2787 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2788                              const ARMSubtarget *Subtarget) {
2789   // ARM pre v5TE and Thumb1 does not have preload instructions.
2790   if (!(Subtarget->isThumb2() ||
2791         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2792     // Just preserve the chain.
2793     return Op.getOperand(0);
2794
2795   SDLoc dl(Op);
2796   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2797   if (!isRead &&
2798       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2799     // ARMv7 with MP extension has PLDW.
2800     return Op.getOperand(0);
2801
2802   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2803   if (Subtarget->isThumb()) {
2804     // Invert the bits.
2805     isRead = ~isRead & 1;
2806     isData = ~isData & 1;
2807   }
2808
2809   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2810                      Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
2811                      DAG.getConstant(isData, dl, MVT::i32));
2812 }
2813
2814 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2815   MachineFunction &MF = DAG.getMachineFunction();
2816   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2817
2818   // vastart just stores the address of the VarArgsFrameIndex slot into the
2819   // memory location argument.
2820   SDLoc dl(Op);
2821   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2822   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2823   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2824   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2825                       MachinePointerInfo(SV), false, false, 0);
2826 }
2827
2828 SDValue
2829 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2830                                         SDValue &Root, SelectionDAG &DAG,
2831                                         SDLoc dl) const {
2832   MachineFunction &MF = DAG.getMachineFunction();
2833   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2834
2835   const TargetRegisterClass *RC;
2836   if (AFI->isThumb1OnlyFunction())
2837     RC = &ARM::tGPRRegClass;
2838   else
2839     RC = &ARM::GPRRegClass;
2840
2841   // Transform the arguments stored in physical registers into virtual ones.
2842   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2843   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2844
2845   SDValue ArgValue2;
2846   if (NextVA.isMemLoc()) {
2847     MachineFrameInfo *MFI = MF.getFrameInfo();
2848     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2849
2850     // Create load node to retrieve arguments from the stack.
2851     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2852     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2853                             MachinePointerInfo::getFixedStack(FI),
2854                             false, false, false, 0);
2855   } else {
2856     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2857     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2858   }
2859   if (!Subtarget->isLittle())
2860     std::swap (ArgValue, ArgValue2);
2861   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2862 }
2863
2864 // The remaining GPRs hold either the beginning of variable-argument
2865 // data, or the beginning of an aggregate passed by value (usually
2866 // byval).  Either way, we allocate stack slots adjacent to the data
2867 // provided by our caller, and store the unallocated registers there.
2868 // If this is a variadic function, the va_list pointer will begin with
2869 // these values; otherwise, this reassembles a (byval) structure that
2870 // was split between registers and memory.
2871 // Return: The frame index registers were stored into.
2872 int
2873 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2874                                   SDLoc dl, SDValue &Chain,
2875                                   const Value *OrigArg,
2876                                   unsigned InRegsParamRecordIdx,
2877                                   int ArgOffset,
2878                                   unsigned ArgSize) const {
2879   // Currently, two use-cases possible:
2880   // Case #1. Non-var-args function, and we meet first byval parameter.
2881   //          Setup first unallocated register as first byval register;
2882   //          eat all remained registers
2883   //          (these two actions are performed by HandleByVal method).
2884   //          Then, here, we initialize stack frame with
2885   //          "store-reg" instructions.
2886   // Case #2. Var-args function, that doesn't contain byval parameters.
2887   //          The same: eat all remained unallocated registers,
2888   //          initialize stack frame.
2889
2890   MachineFunction &MF = DAG.getMachineFunction();
2891   MachineFrameInfo *MFI = MF.getFrameInfo();
2892   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2893   unsigned RBegin, REnd;
2894   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2895     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2896   } else {
2897     unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
2898     RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
2899     REnd = ARM::R4;
2900   }
2901
2902   if (REnd != RBegin)
2903     ArgOffset = -4 * (ARM::R4 - RBegin);
2904
2905   int FrameIndex = MFI->CreateFixedObject(ArgSize, ArgOffset, false);
2906   SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2907
2908   SmallVector<SDValue, 4> MemOps;
2909   const TargetRegisterClass *RC =
2910       AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
2911
2912   for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
2913     unsigned VReg = MF.addLiveIn(Reg, RC);
2914     SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2915     SDValue Store =
2916         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2917                      MachinePointerInfo(OrigArg, 4 * i), false, false, 0);
2918     MemOps.push_back(Store);
2919     FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2920                       DAG.getConstant(4, dl, getPointerTy()));
2921   }
2922
2923   if (!MemOps.empty())
2924     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2925   return FrameIndex;
2926 }
2927
2928 // Setup stack frame, the va_list pointer will start from.
2929 void
2930 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2931                                         SDLoc dl, SDValue &Chain,
2932                                         unsigned ArgOffset,
2933                                         unsigned TotalArgRegsSaveSize,
2934                                         bool ForceMutable) const {
2935   MachineFunction &MF = DAG.getMachineFunction();
2936   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2937
2938   // Try to store any remaining integer argument regs
2939   // to their spots on the stack so that they may be loaded by deferencing
2940   // the result of va_next.
2941   // If there is no regs to be stored, just point address after last
2942   // argument passed via stack.
2943   int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
2944                                   CCInfo.getInRegsParamsCount(),
2945                                   CCInfo.getNextStackOffset(), 4);
2946   AFI->setVarArgsFrameIndex(FrameIndex);
2947 }
2948
2949 SDValue
2950 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2951                                         CallingConv::ID CallConv, bool isVarArg,
2952                                         const SmallVectorImpl<ISD::InputArg>
2953                                           &Ins,
2954                                         SDLoc dl, SelectionDAG &DAG,
2955                                         SmallVectorImpl<SDValue> &InVals)
2956                                           const {
2957   MachineFunction &MF = DAG.getMachineFunction();
2958   MachineFrameInfo *MFI = MF.getFrameInfo();
2959
2960   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2961
2962   // Assign locations to all of the incoming arguments.
2963   SmallVector<CCValAssign, 16> ArgLocs;
2964   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2965                     *DAG.getContext(), Prologue);
2966   CCInfo.AnalyzeFormalArguments(Ins,
2967                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2968                                                   isVarArg));
2969
2970   SmallVector<SDValue, 16> ArgValues;
2971   SDValue ArgValue;
2972   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2973   unsigned CurArgIdx = 0;
2974
2975   // Initially ArgRegsSaveSize is zero.
2976   // Then we increase this value each time we meet byval parameter.
2977   // We also increase this value in case of varargs function.
2978   AFI->setArgRegsSaveSize(0);
2979
2980   // Calculate the amount of stack space that we need to allocate to store
2981   // byval and variadic arguments that are passed in registers.
2982   // We need to know this before we allocate the first byval or variadic
2983   // argument, as they will be allocated a stack slot below the CFA (Canonical
2984   // Frame Address, the stack pointer at entry to the function).
2985   unsigned ArgRegBegin = ARM::R4;
2986   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2987     if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
2988       break;
2989
2990     CCValAssign &VA = ArgLocs[i];
2991     unsigned Index = VA.getValNo();
2992     ISD::ArgFlagsTy Flags = Ins[Index].Flags;
2993     if (!Flags.isByVal())
2994       continue;
2995
2996     assert(VA.isMemLoc() && "unexpected byval pointer in reg");
2997     unsigned RBegin, REnd;
2998     CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
2999     ArgRegBegin = std::min(ArgRegBegin, RBegin);
3000
3001     CCInfo.nextInRegsParam();
3002   }
3003   CCInfo.rewindByValRegsInfo();
3004
3005   int lastInsIndex = -1;
3006   if (isVarArg && MFI->hasVAStart()) {
3007     unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3008     if (RegIdx != array_lengthof(GPRArgRegs))
3009       ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3010   }
3011
3012   unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3013   AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3014
3015   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3016     CCValAssign &VA = ArgLocs[i];
3017     if (Ins[VA.getValNo()].isOrigArg()) {
3018       std::advance(CurOrigArg,
3019                    Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3020       CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3021     }
3022     // Arguments stored in registers.
3023     if (VA.isRegLoc()) {
3024       EVT RegVT = VA.getLocVT();
3025
3026       if (VA.needsCustom()) {
3027         // f64 and vector types are split up into multiple registers or
3028         // combinations of registers and stack slots.
3029         if (VA.getLocVT() == MVT::v2f64) {
3030           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3031                                                    Chain, DAG, dl);
3032           VA = ArgLocs[++i]; // skip ahead to next loc
3033           SDValue ArgValue2;
3034           if (VA.isMemLoc()) {
3035             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3036             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3037             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3038                                     MachinePointerInfo::getFixedStack(FI),
3039                                     false, false, false, 0);
3040           } else {
3041             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3042                                              Chain, DAG, dl);
3043           }
3044           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3045           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3046                                  ArgValue, ArgValue1,
3047                                  DAG.getIntPtrConstant(0, dl));
3048           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3049                                  ArgValue, ArgValue2,
3050                                  DAG.getIntPtrConstant(1, dl));
3051         } else
3052           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3053
3054       } else {
3055         const TargetRegisterClass *RC;
3056
3057         if (RegVT == MVT::f32)
3058           RC = &ARM::SPRRegClass;
3059         else if (RegVT == MVT::f64)
3060           RC = &ARM::DPRRegClass;
3061         else if (RegVT == MVT::v2f64)
3062           RC = &ARM::QPRRegClass;
3063         else if (RegVT == MVT::i32)
3064           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3065                                            : &ARM::GPRRegClass;
3066         else
3067           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3068
3069         // Transform the arguments in physical registers into virtual ones.
3070         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3071         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3072       }
3073
3074       // If this is an 8 or 16-bit value, it is really passed promoted
3075       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3076       // truncate to the right size.
3077       switch (VA.getLocInfo()) {
3078       default: llvm_unreachable("Unknown loc info!");
3079       case CCValAssign::Full: break;
3080       case CCValAssign::BCvt:
3081         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3082         break;
3083       case CCValAssign::SExt:
3084         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3085                                DAG.getValueType(VA.getValVT()));
3086         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3087         break;
3088       case CCValAssign::ZExt:
3089         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3090                                DAG.getValueType(VA.getValVT()));
3091         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3092         break;
3093       }
3094
3095       InVals.push_back(ArgValue);
3096
3097     } else { // VA.isRegLoc()
3098
3099       // sanity check
3100       assert(VA.isMemLoc());
3101       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3102
3103       int index = VA.getValNo();
3104
3105       // Some Ins[] entries become multiple ArgLoc[] entries.
3106       // Process them only once.
3107       if (index != lastInsIndex)
3108         {
3109           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3110           // FIXME: For now, all byval parameter objects are marked mutable.
3111           // This can be changed with more analysis.
3112           // In case of tail call optimization mark all arguments mutable.
3113           // Since they could be overwritten by lowering of arguments in case of
3114           // a tail call.
3115           if (Flags.isByVal()) {
3116             assert(Ins[index].isOrigArg() &&
3117                    "Byval arguments cannot be implicit");
3118             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3119
3120             int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, CurOrigArg,
3121                                             CurByValIndex, VA.getLocMemOffset(),
3122                                             Flags.getByValSize());
3123             InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3124             CCInfo.nextInRegsParam();
3125           } else {
3126             unsigned FIOffset = VA.getLocMemOffset();
3127             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3128                                             FIOffset, true);
3129
3130             // Create load nodes to retrieve arguments from the stack.
3131             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3132             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3133                                          MachinePointerInfo::getFixedStack(FI),
3134                                          false, false, false, 0));
3135           }
3136           lastInsIndex = index;
3137         }
3138     }
3139   }
3140
3141   // varargs
3142   if (isVarArg && MFI->hasVAStart())
3143     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3144                          CCInfo.getNextStackOffset(),
3145                          TotalArgRegsSaveSize);
3146
3147   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3148
3149   return Chain;
3150 }
3151
3152 /// isFloatingPointZero - Return true if this is +0.0.
3153 static bool isFloatingPointZero(SDValue Op) {
3154   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3155     return CFP->getValueAPF().isPosZero();
3156   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3157     // Maybe this has already been legalized into the constant pool?
3158     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3159       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3160       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3161         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3162           return CFP->getValueAPF().isPosZero();
3163     }
3164   } else if (Op->getOpcode() == ISD::BITCAST &&
3165              Op->getValueType(0) == MVT::f64) {
3166     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3167     // created by LowerConstantFP().
3168     SDValue BitcastOp = Op->getOperand(0);
3169     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM) {
3170       SDValue MoveOp = BitcastOp->getOperand(0);
3171       if (MoveOp->getOpcode() == ISD::TargetConstant &&
3172           cast<ConstantSDNode>(MoveOp)->getZExtValue() == 0) {
3173         return true;
3174       }
3175     }
3176   }
3177   return false;
3178 }
3179
3180 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3181 /// the given operands.
3182 SDValue
3183 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3184                              SDValue &ARMcc, SelectionDAG &DAG,
3185                              SDLoc dl) const {
3186   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3187     unsigned C = RHSC->getZExtValue();
3188     if (!isLegalICmpImmediate(C)) {
3189       // Constant does not fit, try adjusting it by one?
3190       switch (CC) {
3191       default: break;
3192       case ISD::SETLT:
3193       case ISD::SETGE:
3194         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3195           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3196           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3197         }
3198         break;
3199       case ISD::SETULT:
3200       case ISD::SETUGE:
3201         if (C != 0 && isLegalICmpImmediate(C-1)) {
3202           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3203           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3204         }
3205         break;
3206       case ISD::SETLE:
3207       case ISD::SETGT:
3208         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3209           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3210           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3211         }
3212         break;
3213       case ISD::SETULE:
3214       case ISD::SETUGT:
3215         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3216           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3217           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3218         }
3219         break;
3220       }
3221     }
3222   }
3223
3224   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3225   ARMISD::NodeType CompareType;
3226   switch (CondCode) {
3227   default:
3228     CompareType = ARMISD::CMP;
3229     break;
3230   case ARMCC::EQ:
3231   case ARMCC::NE:
3232     // Uses only Z Flag
3233     CompareType = ARMISD::CMPZ;
3234     break;
3235   }
3236   ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3237   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3238 }
3239
3240 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3241 SDValue
3242 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3243                              SDLoc dl) const {
3244   assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3245   SDValue Cmp;
3246   if (!isFloatingPointZero(RHS))
3247     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3248   else
3249     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3250   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3251 }
3252
3253 /// duplicateCmp - Glue values can have only one use, so this function
3254 /// duplicates a comparison node.
3255 SDValue
3256 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3257   unsigned Opc = Cmp.getOpcode();
3258   SDLoc DL(Cmp);
3259   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3260     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3261
3262   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3263   Cmp = Cmp.getOperand(0);
3264   Opc = Cmp.getOpcode();
3265   if (Opc == ARMISD::CMPFP)
3266     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3267   else {
3268     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3269     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3270   }
3271   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3272 }
3273
3274 std::pair<SDValue, SDValue>
3275 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3276                                  SDValue &ARMcc) const {
3277   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3278
3279   SDValue Value, OverflowCmp;
3280   SDValue LHS = Op.getOperand(0);
3281   SDValue RHS = Op.getOperand(1);
3282   SDLoc dl(Op);
3283
3284   // FIXME: We are currently always generating CMPs because we don't support
3285   // generating CMN through the backend. This is not as good as the natural
3286   // CMP case because it causes a register dependency and cannot be folded
3287   // later.
3288
3289   switch (Op.getOpcode()) {
3290   default:
3291     llvm_unreachable("Unknown overflow instruction!");
3292   case ISD::SADDO:
3293     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3294     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3295     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3296     break;
3297   case ISD::UADDO:
3298     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3299     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3300     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3301     break;
3302   case ISD::SSUBO:
3303     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3304     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3305     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3306     break;
3307   case ISD::USUBO:
3308     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3309     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3310     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3311     break;
3312   } // switch (...)
3313
3314   return std::make_pair(Value, OverflowCmp);
3315 }
3316
3317
3318 SDValue
3319 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3320   // Let legalize expand this if it isn't a legal type yet.
3321   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3322     return SDValue();
3323
3324   SDValue Value, OverflowCmp;
3325   SDValue ARMcc;
3326   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3327   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3328   SDLoc dl(Op);
3329   // We use 0 and 1 as false and true values.
3330   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3331   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3332   EVT VT = Op.getValueType();
3333
3334   SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
3335                                  ARMcc, CCR, OverflowCmp);
3336
3337   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3338   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
3339 }
3340
3341
3342 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3343   SDValue Cond = Op.getOperand(0);
3344   SDValue SelectTrue = Op.getOperand(1);
3345   SDValue SelectFalse = Op.getOperand(2);
3346   SDLoc dl(Op);
3347   unsigned Opc = Cond.getOpcode();
3348
3349   if (Cond.getResNo() == 1 &&
3350       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3351        Opc == ISD::USUBO)) {
3352     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3353       return SDValue();
3354
3355     SDValue Value, OverflowCmp;
3356     SDValue ARMcc;
3357     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3358     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3359     EVT VT = Op.getValueType();
3360
3361     return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
3362                    OverflowCmp, DAG);
3363   }
3364
3365   // Convert:
3366   //
3367   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3368   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3369   //
3370   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3371     const ConstantSDNode *CMOVTrue =
3372       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3373     const ConstantSDNode *CMOVFalse =
3374       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3375
3376     if (CMOVTrue && CMOVFalse) {
3377       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3378       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3379
3380       SDValue True;
3381       SDValue False;
3382       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3383         True = SelectTrue;
3384         False = SelectFalse;
3385       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3386         True = SelectFalse;
3387         False = SelectTrue;
3388       }
3389
3390       if (True.getNode() && False.getNode()) {
3391         EVT VT = Op.getValueType();
3392         SDValue ARMcc = Cond.getOperand(2);
3393         SDValue CCR = Cond.getOperand(3);
3394         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3395         assert(True.getValueType() == VT);
3396         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3397       }
3398     }
3399   }
3400
3401   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3402   // undefined bits before doing a full-word comparison with zero.
3403   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3404                      DAG.getConstant(1, dl, Cond.getValueType()));
3405
3406   return DAG.getSelectCC(dl, Cond,
3407                          DAG.getConstant(0, dl, Cond.getValueType()),
3408                          SelectTrue, SelectFalse, ISD::SETNE);
3409 }
3410
3411 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3412                                  bool &swpCmpOps, bool &swpVselOps) {
3413   // Start by selecting the GE condition code for opcodes that return true for
3414   // 'equality'
3415   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3416       CC == ISD::SETULE)
3417     CondCode = ARMCC::GE;
3418
3419   // and GT for opcodes that return false for 'equality'.
3420   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3421            CC == ISD::SETULT)
3422     CondCode = ARMCC::GT;
3423
3424   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3425   // to swap the compare operands.
3426   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3427       CC == ISD::SETULT)
3428     swpCmpOps = true;
3429
3430   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3431   // If we have an unordered opcode, we need to swap the operands to the VSEL
3432   // instruction (effectively negating the condition).
3433   //
3434   // This also has the effect of swapping which one of 'less' or 'greater'
3435   // returns true, so we also swap the compare operands. It also switches
3436   // whether we return true for 'equality', so we compensate by picking the
3437   // opposite condition code to our original choice.
3438   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3439       CC == ISD::SETUGT) {
3440     swpCmpOps = !swpCmpOps;
3441     swpVselOps = !swpVselOps;
3442     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3443   }
3444
3445   // 'ordered' is 'anything but unordered', so use the VS condition code and
3446   // swap the VSEL operands.
3447   if (CC == ISD::SETO) {
3448     CondCode = ARMCC::VS;
3449     swpVselOps = true;
3450   }
3451
3452   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3453   // code and swap the VSEL operands.
3454   if (CC == ISD::SETUNE) {
3455     CondCode = ARMCC::EQ;
3456     swpVselOps = true;
3457   }
3458 }
3459
3460 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3461                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3462                                    SDValue Cmp, SelectionDAG &DAG) const {
3463   if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3464     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3465                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3466     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3467                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3468
3469     SDValue TrueLow = TrueVal.getValue(0);
3470     SDValue TrueHigh = TrueVal.getValue(1);
3471     SDValue FalseLow = FalseVal.getValue(0);
3472     SDValue FalseHigh = FalseVal.getValue(1);
3473
3474     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3475                               ARMcc, CCR, Cmp);
3476     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3477                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
3478
3479     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3480   } else {
3481     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3482                        Cmp);
3483   }
3484 }
3485
3486 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3487   EVT VT = Op.getValueType();
3488   SDValue LHS = Op.getOperand(0);
3489   SDValue RHS = Op.getOperand(1);
3490   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3491   SDValue TrueVal = Op.getOperand(2);
3492   SDValue FalseVal = Op.getOperand(3);
3493   SDLoc dl(Op);
3494
3495   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3496     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3497                                                     dl);
3498
3499     // If softenSetCCOperands only returned one value, we should compare it to
3500     // zero.
3501     if (!RHS.getNode()) {
3502       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3503       CC = ISD::SETNE;
3504     }
3505   }
3506
3507   if (LHS.getValueType() == MVT::i32) {
3508     // Try to generate VSEL on ARMv8.
3509     // The VSEL instruction can't use all the usual ARM condition
3510     // codes: it only has two bits to select the condition code, so it's
3511     // constrained to use only GE, GT, VS and EQ.
3512     //
3513     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3514     // swap the operands of the previous compare instruction (effectively
3515     // inverting the compare condition, swapping 'less' and 'greater') and
3516     // sometimes need to swap the operands to the VSEL (which inverts the
3517     // condition in the sense of firing whenever the previous condition didn't)
3518     if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3519                                     TrueVal.getValueType() == MVT::f64)) {
3520       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3521       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3522           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3523         CC = ISD::getSetCCInverse(CC, true);
3524         std::swap(TrueVal, FalseVal);
3525       }
3526     }
3527
3528     SDValue ARMcc;
3529     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3530     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3531     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3532   }
3533
3534   ARMCC::CondCodes CondCode, CondCode2;
3535   FPCCToARMCC(CC, CondCode, CondCode2);
3536
3537   // Try to generate VMAXNM/VMINNM on ARMv8.
3538   if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3539                                   TrueVal.getValueType() == MVT::f64)) {
3540     // We can use VMAXNM/VMINNM for a compare followed by a select with the
3541     // same operands, as follows:
3542     //   c = fcmp [?gt, ?ge, ?lt, ?le] a, b
3543     //   select c, a, b
3544     // In NoNaNsFPMath the CC will have been changed from, e.g., 'ogt' to 'gt'.
3545     bool swapSides = false;
3546     if (!getTargetMachine().Options.NoNaNsFPMath) {
3547       // transformability may depend on which way around we compare
3548       switch (CC) {
3549       default:
3550         break;
3551       case ISD::SETOGT:
3552       case ISD::SETOGE:
3553       case ISD::SETOLT:
3554       case ISD::SETOLE:
3555         // the non-NaN should be RHS
3556         swapSides = DAG.isKnownNeverNaN(LHS) && !DAG.isKnownNeverNaN(RHS);
3557         break;
3558       case ISD::SETUGT:
3559       case ISD::SETUGE:
3560       case ISD::SETULT:
3561       case ISD::SETULE:
3562         // the non-NaN should be LHS
3563         swapSides = DAG.isKnownNeverNaN(RHS) && !DAG.isKnownNeverNaN(LHS);
3564         break;
3565       }
3566     }
3567     swapSides = swapSides || (LHS == FalseVal && RHS == TrueVal);
3568     if (swapSides) {
3569       CC = ISD::getSetCCSwappedOperands(CC);
3570       std::swap(LHS, RHS);
3571     }
3572     if (LHS == TrueVal && RHS == FalseVal) {
3573       bool canTransform = true;
3574       // FIXME: FastMathFlags::noSignedZeros() doesn't appear reachable from here
3575       if (!getTargetMachine().Options.UnsafeFPMath &&
3576           !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
3577         const ConstantFPSDNode *Zero;
3578         switch (CC) {
3579         default:
3580           break;
3581         case ISD::SETOGT:
3582         case ISD::SETUGT:
3583         case ISD::SETGT:
3584           // RHS must not be -0
3585           canTransform = (Zero = dyn_cast<ConstantFPSDNode>(RHS)) &&
3586                          !Zero->isNegative();
3587           break;
3588         case ISD::SETOGE:
3589         case ISD::SETUGE:
3590         case ISD::SETGE:
3591           // LHS must not be -0
3592           canTransform = (Zero = dyn_cast<ConstantFPSDNode>(LHS)) &&
3593                          !Zero->isNegative();
3594           break;
3595         case ISD::SETOLT:
3596         case ISD::SETULT:
3597         case ISD::SETLT:
3598           // RHS must not be +0
3599           canTransform = (Zero = dyn_cast<ConstantFPSDNode>(RHS)) &&
3600                           Zero->isNegative();
3601           break;
3602         case ISD::SETOLE:
3603         case ISD::SETULE:
3604         case ISD::SETLE:
3605           // LHS must not be +0
3606           canTransform = (Zero = dyn_cast<ConstantFPSDNode>(LHS)) &&
3607                           Zero->isNegative();
3608           break;
3609         }
3610       }
3611       if (canTransform) {
3612         // Note: If one of the elements in a pair is a number and the other
3613         // element is NaN, the corresponding result element is the number.
3614         // This is consistent with the IEEE 754-2008 standard.
3615         // Therefore, a > b ? a : b <=> vmax(a,b), if b is constant and a is NaN
3616         switch (CC) {
3617         default:
3618           break;
3619         case ISD::SETOGT:
3620         case ISD::SETOGE:
3621           if (!DAG.isKnownNeverNaN(RHS))
3622             break;
3623           return DAG.getNode(ARMISD::VMAXNM, dl, VT, LHS, RHS);
3624         case ISD::SETUGT:
3625         case ISD::SETUGE:
3626           if (!DAG.isKnownNeverNaN(LHS))
3627             break;
3628         case ISD::SETGT:
3629         case ISD::SETGE:
3630           return DAG.getNode(ARMISD::VMAXNM, dl, VT, LHS, RHS);
3631         case ISD::SETOLT:
3632         case ISD::SETOLE:
3633           if (!DAG.isKnownNeverNaN(RHS))
3634             break;
3635           return DAG.getNode(ARMISD::VMINNM, dl, VT, LHS, RHS);
3636         case ISD::SETULT:
3637         case ISD::SETULE:
3638           if (!DAG.isKnownNeverNaN(LHS))
3639             break;
3640         case ISD::SETLT:
3641         case ISD::SETLE:
3642           return DAG.getNode(ARMISD::VMINNM, dl, VT, LHS, RHS);
3643         }
3644       }
3645     }
3646
3647     bool swpCmpOps = false;
3648     bool swpVselOps = false;
3649     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3650
3651     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3652         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3653       if (swpCmpOps)
3654         std::swap(LHS, RHS);
3655       if (swpVselOps)
3656         std::swap(TrueVal, FalseVal);
3657     }
3658   }
3659
3660   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3661   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3662   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3663   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3664   if (CondCode2 != ARMCC::AL) {
3665     SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
3666     // FIXME: Needs another CMP because flag can have but one use.
3667     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3668     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3669   }
3670   return Result;
3671 }
3672
3673 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3674 /// to morph to an integer compare sequence.
3675 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3676                            const ARMSubtarget *Subtarget) {
3677   SDNode *N = Op.getNode();
3678   if (!N->hasOneUse())
3679     // Otherwise it requires moving the value from fp to integer registers.
3680     return false;
3681   if (!N->getNumValues())
3682     return false;
3683   EVT VT = Op.getValueType();
3684   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3685     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3686     // vmrs are very slow, e.g. cortex-a8.
3687     return false;
3688
3689   if (isFloatingPointZero(Op)) {
3690     SeenZero = true;
3691     return true;
3692   }
3693   return ISD::isNormalLoad(N);
3694 }
3695
3696 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3697   if (isFloatingPointZero(Op))
3698     return DAG.getConstant(0, SDLoc(Op), MVT::i32);
3699
3700   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3701     return DAG.getLoad(MVT::i32, SDLoc(Op),
3702                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3703                        Ld->isVolatile(), Ld->isNonTemporal(),
3704                        Ld->isInvariant(), Ld->getAlignment());
3705
3706   llvm_unreachable("Unknown VFP cmp argument!");
3707 }
3708
3709 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3710                            SDValue &RetVal1, SDValue &RetVal2) {
3711   SDLoc dl(Op);
3712
3713   if (isFloatingPointZero(Op)) {
3714     RetVal1 = DAG.getConstant(0, dl, MVT::i32);
3715     RetVal2 = DAG.getConstant(0, dl, MVT::i32);
3716     return;
3717   }
3718
3719   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3720     SDValue Ptr = Ld->getBasePtr();
3721     RetVal1 = DAG.getLoad(MVT::i32, dl,
3722                           Ld->getChain(), Ptr,
3723                           Ld->getPointerInfo(),
3724                           Ld->isVolatile(), Ld->isNonTemporal(),
3725                           Ld->isInvariant(), Ld->getAlignment());
3726
3727     EVT PtrType = Ptr.getValueType();
3728     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3729     SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
3730                                  PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
3731     RetVal2 = DAG.getLoad(MVT::i32, dl,
3732                           Ld->getChain(), NewPtr,
3733                           Ld->getPointerInfo().getWithOffset(4),
3734                           Ld->isVolatile(), Ld->isNonTemporal(),
3735                           Ld->isInvariant(), NewAlign);
3736     return;
3737   }
3738
3739   llvm_unreachable("Unknown VFP cmp argument!");
3740 }
3741
3742 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3743 /// f32 and even f64 comparisons to integer ones.
3744 SDValue
3745 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3746   SDValue Chain = Op.getOperand(0);
3747   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3748   SDValue LHS = Op.getOperand(2);
3749   SDValue RHS = Op.getOperand(3);
3750   SDValue Dest = Op.getOperand(4);
3751   SDLoc dl(Op);
3752
3753   bool LHSSeenZero = false;
3754   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3755   bool RHSSeenZero = false;
3756   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3757   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3758     // If unsafe fp math optimization is enabled and there are no other uses of
3759     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3760     // to an integer comparison.
3761     if (CC == ISD::SETOEQ)
3762       CC = ISD::SETEQ;
3763     else if (CC == ISD::SETUNE)
3764       CC = ISD::SETNE;
3765
3766     SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
3767     SDValue ARMcc;
3768     if (LHS.getValueType() == MVT::f32) {
3769       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3770                         bitcastf32Toi32(LHS, DAG), Mask);
3771       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3772                         bitcastf32Toi32(RHS, DAG), Mask);
3773       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3774       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3775       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3776                          Chain, Dest, ARMcc, CCR, Cmp);
3777     }
3778
3779     SDValue LHS1, LHS2;
3780     SDValue RHS1, RHS2;
3781     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3782     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3783     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3784     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3785     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3786     ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3787     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3788     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3789     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3790   }
3791
3792   return SDValue();
3793 }
3794
3795 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3796   SDValue Chain = Op.getOperand(0);
3797   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3798   SDValue LHS = Op.getOperand(2);
3799   SDValue RHS = Op.getOperand(3);
3800   SDValue Dest = Op.getOperand(4);
3801   SDLoc dl(Op);
3802
3803   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3804     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3805                                                     dl);
3806
3807     // If softenSetCCOperands only returned one value, we should compare it to
3808     // zero.
3809     if (!RHS.getNode()) {
3810       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3811       CC = ISD::SETNE;
3812     }
3813   }
3814
3815   if (LHS.getValueType() == MVT::i32) {
3816     SDValue ARMcc;
3817     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3818     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3819     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3820                        Chain, Dest, ARMcc, CCR, Cmp);
3821   }
3822
3823   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3824
3825   if (getTargetMachine().Options.UnsafeFPMath &&
3826       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3827        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3828     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3829     if (Result.getNode())
3830       return Result;
3831   }
3832
3833   ARMCC::CondCodes CondCode, CondCode2;
3834   FPCCToARMCC(CC, CondCode, CondCode2);
3835
3836   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3837   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3838   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3839   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3840   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3841   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3842   if (CondCode2 != ARMCC::AL) {
3843     ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
3844     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3845     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3846   }
3847   return Res;
3848 }
3849
3850 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3851   SDValue Chain = Op.getOperand(0);
3852   SDValue Table = Op.getOperand(1);
3853   SDValue Index = Op.getOperand(2);
3854   SDLoc dl(Op);
3855
3856   EVT PTy = getPointerTy();
3857   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3858   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3859   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
3860   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
3861   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3862   if (Subtarget->isThumb2()) {
3863     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3864     // which does another jump to the destination. This also makes it easier
3865     // to translate it to TBB / TBH later.
3866     // FIXME: This might not work if the function is extremely large.
3867     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3868                        Addr, Op.getOperand(2), JTI);
3869   }
3870   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3871     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3872                        MachinePointerInfo::getJumpTable(),
3873                        false, false, false, 0);
3874     Chain = Addr.getValue(1);
3875     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3876     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3877   } else {
3878     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3879                        MachinePointerInfo::getJumpTable(),
3880                        false, false, false, 0);
3881     Chain = Addr.getValue(1);
3882     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3883   }
3884 }
3885
3886 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3887   EVT VT = Op.getValueType();
3888   SDLoc dl(Op);
3889
3890   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3891     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3892       return Op;
3893     return DAG.UnrollVectorOp(Op.getNode());
3894   }
3895
3896   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3897          "Invalid type for custom lowering!");
3898   if (VT != MVT::v4i16)
3899     return DAG.UnrollVectorOp(Op.getNode());
3900
3901   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3902   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3903 }
3904
3905 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3906   EVT VT = Op.getValueType();
3907   if (VT.isVector())
3908     return LowerVectorFP_TO_INT(Op, DAG);
3909   if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3910     RTLIB::Libcall LC;
3911     if (Op.getOpcode() == ISD::FP_TO_SINT)
3912       LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
3913                               Op.getValueType());
3914     else
3915       LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
3916                               Op.getValueType());
3917     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3918                        /*isSigned*/ false, SDLoc(Op)).first;
3919   }
3920
3921   return Op;
3922 }
3923
3924 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3925   EVT VT = Op.getValueType();
3926   SDLoc dl(Op);
3927
3928   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3929     if (VT.getVectorElementType() == MVT::f32)
3930       return Op;
3931     return DAG.UnrollVectorOp(Op.getNode());
3932   }
3933
3934   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3935          "Invalid type for custom lowering!");
3936   if (VT != MVT::v4f32)
3937     return DAG.UnrollVectorOp(Op.getNode());
3938
3939   unsigned CastOpc;
3940   unsigned Opc;
3941   switch (Op.getOpcode()) {
3942   default: llvm_unreachable("Invalid opcode!");
3943   case ISD::SINT_TO_FP:
3944     CastOpc = ISD::SIGN_EXTEND;
3945     Opc = ISD::SINT_TO_FP;
3946     break;
3947   case ISD::UINT_TO_FP:
3948     CastOpc = ISD::ZERO_EXTEND;
3949     Opc = ISD::UINT_TO_FP;
3950     break;
3951   }
3952
3953   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3954   return DAG.getNode(Opc, dl, VT, Op);
3955 }
3956
3957 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
3958   EVT VT = Op.getValueType();
3959   if (VT.isVector())
3960     return LowerVectorINT_TO_FP(Op, DAG);
3961   if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
3962     RTLIB::Libcall LC;
3963     if (Op.getOpcode() == ISD::SINT_TO_FP)
3964       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
3965                               Op.getValueType());
3966     else
3967       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
3968                               Op.getValueType());
3969     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3970                        /*isSigned*/ false, SDLoc(Op)).first;
3971   }
3972
3973   return Op;
3974 }
3975
3976 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3977   // Implement fcopysign with a fabs and a conditional fneg.
3978   SDValue Tmp0 = Op.getOperand(0);
3979   SDValue Tmp1 = Op.getOperand(1);
3980   SDLoc dl(Op);
3981   EVT VT = Op.getValueType();
3982   EVT SrcVT = Tmp1.getValueType();
3983   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3984     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3985   bool UseNEON = !InGPR && Subtarget->hasNEON();
3986
3987   if (UseNEON) {
3988     // Use VBSL to copy the sign bit.
3989     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3990     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3991                                DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
3992     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3993     if (VT == MVT::f64)
3994       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3995                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3996                          DAG.getConstant(32, dl, MVT::i32));
3997     else /*if (VT == MVT::f32)*/
3998       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3999     if (SrcVT == MVT::f32) {
4000       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4001       if (VT == MVT::f64)
4002         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4003                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4004                            DAG.getConstant(32, dl, MVT::i32));
4005     } else if (VT == MVT::f32)
4006       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4007                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4008                          DAG.getConstant(32, dl, MVT::i32));
4009     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4010     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4011
4012     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4013                                             dl, MVT::i32);
4014     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4015     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4016                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4017
4018     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4019                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4020                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4021     if (VT == MVT::f32) {
4022       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4023       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4024                         DAG.getConstant(0, dl, MVT::i32));
4025     } else {
4026       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4027     }
4028
4029     return Res;
4030   }
4031
4032   // Bitcast operand 1 to i32.
4033   if (SrcVT == MVT::f64)
4034     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4035                        Tmp1).getValue(1);
4036   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4037
4038   // Or in the signbit with integer operations.
4039   SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
4040   SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4041   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4042   if (VT == MVT::f32) {
4043     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4044                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4045     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4046                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4047   }
4048
4049   // f64: Or the high part with signbit and then combine two parts.
4050   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4051                      Tmp0);
4052   SDValue Lo = Tmp0.getValue(0);
4053   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4054   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4055   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4056 }
4057
4058 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4059   MachineFunction &MF = DAG.getMachineFunction();
4060   MachineFrameInfo *MFI = MF.getFrameInfo();
4061   MFI->setReturnAddressIsTaken(true);
4062
4063   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4064     return SDValue();
4065
4066   EVT VT = Op.getValueType();
4067   SDLoc dl(Op);
4068   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4069   if (Depth) {
4070     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4071     SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
4072     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4073                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4074                        MachinePointerInfo(), false, false, false, 0);
4075   }
4076
4077   // Return LR, which contains the return address. Mark it an implicit live-in.
4078   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4079   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4080 }
4081
4082 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4083   const ARMBaseRegisterInfo &ARI =
4084     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4085   MachineFunction &MF = DAG.getMachineFunction();
4086   MachineFrameInfo *MFI = MF.getFrameInfo();
4087   MFI->setFrameAddressIsTaken(true);
4088
4089   EVT VT = Op.getValueType();
4090   SDLoc dl(Op);  // FIXME probably not meaningful
4091   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4092   unsigned FrameReg = ARI.getFrameRegister(MF);
4093   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4094   while (Depth--)
4095     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4096                             MachinePointerInfo(),
4097                             false, false, false, 0);
4098   return FrameAddr;
4099 }
4100
4101 // FIXME? Maybe this could be a TableGen attribute on some registers and
4102 // this table could be generated automatically from RegInfo.
4103 unsigned ARMTargetLowering::getRegisterByName(const char* RegName,
4104                                               EVT VT) const {
4105   unsigned Reg = StringSwitch<unsigned>(RegName)
4106                        .Case("sp", ARM::SP)
4107                        .Default(0);
4108   if (Reg)
4109     return Reg;
4110   report_fatal_error(Twine("Invalid register name \""
4111                               + StringRef(RegName)  + "\"."));
4112 }
4113
4114 // Result is 64 bit value so split into two 32 bit values and return as a
4115 // pair of values.
4116 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
4117                                 SelectionDAG &DAG) {
4118   SDLoc DL(N);
4119
4120   // This function is only supposed to be called for i64 type destination.
4121   assert(N->getValueType(0) == MVT::i64
4122           && "ExpandREAD_REGISTER called for non-i64 type result.");
4123
4124   SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
4125                              DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
4126                              N->getOperand(0),
4127                              N->getOperand(1));
4128
4129   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
4130                     Read.getValue(1)));
4131   Results.push_back(Read.getOperand(0));
4132 }
4133
4134 /// ExpandBITCAST - If the target supports VFP, this function is called to
4135 /// expand a bit convert where either the source or destination type is i64 to
4136 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
4137 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4138 /// vectors), since the legalizer won't know what to do with that.
4139 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4140   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4141   SDLoc dl(N);
4142   SDValue Op = N->getOperand(0);
4143
4144   // This function is only supposed to be called for i64 types, either as the
4145   // source or destination of the bit convert.
4146   EVT SrcVT = Op.getValueType();
4147   EVT DstVT = N->getValueType(0);
4148   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4149          "ExpandBITCAST called for non-i64 type");
4150
4151   // Turn i64->f64 into VMOVDRR.
4152   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4153     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4154                              DAG.getConstant(0, dl, MVT::i32));
4155     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4156                              DAG.getConstant(1, dl, MVT::i32));
4157     return DAG.getNode(ISD::BITCAST, dl, DstVT,
4158                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4159   }
4160
4161   // Turn f64->i64 into VMOVRRD.
4162   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4163     SDValue Cvt;
4164     if (TLI.isBigEndian() && SrcVT.isVector() &&
4165         SrcVT.getVectorNumElements() > 1)
4166       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4167                         DAG.getVTList(MVT::i32, MVT::i32),
4168                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4169     else
4170       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4171                         DAG.getVTList(MVT::i32, MVT::i32), Op);
4172     // Merge the pieces into a single i64 value.
4173     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4174   }
4175
4176   return SDValue();
4177 }
4178
4179 /// getZeroVector - Returns a vector of specified type with all zero elements.
4180 /// Zero vectors are used to represent vector negation and in those cases
4181 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
4182 /// not support i64 elements, so sometimes the zero vectors will need to be
4183 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
4184 /// zero vector.
4185 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4186   assert(VT.isVector() && "Expected a vector type");
4187   // The canonical modified immediate encoding of a zero vector is....0!
4188   SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
4189   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4190   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4191   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4192 }
4193
4194 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4195 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4196 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4197                                                 SelectionDAG &DAG) const {
4198   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4199   EVT VT = Op.getValueType();
4200   unsigned VTBits = VT.getSizeInBits();
4201   SDLoc dl(Op);
4202   SDValue ShOpLo = Op.getOperand(0);
4203   SDValue ShOpHi = Op.getOperand(1);
4204   SDValue ShAmt  = Op.getOperand(2);
4205   SDValue ARMcc;
4206   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4207
4208   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4209
4210   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4211                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4212   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4213   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4214                                    DAG.getConstant(VTBits, dl, MVT::i32));
4215   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4216   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4217   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4218
4219   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4220   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4221                           ISD::SETGE, ARMcc, DAG, dl);
4222   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4223   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4224                            CCR, Cmp);
4225
4226   SDValue Ops[2] = { Lo, Hi };
4227   return DAG.getMergeValues(Ops, dl);
4228 }
4229
4230 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4231 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4232 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4233                                                SelectionDAG &DAG) const {
4234   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4235   EVT VT = Op.getValueType();
4236   unsigned VTBits = VT.getSizeInBits();
4237   SDLoc dl(Op);
4238   SDValue ShOpLo = Op.getOperand(0);
4239   SDValue ShOpHi = Op.getOperand(1);
4240   SDValue ShAmt  = Op.getOperand(2);
4241   SDValue ARMcc;
4242
4243   assert(Op.getOpcode() == ISD::SHL_PARTS);
4244   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4245                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4246   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4247   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4248                                    DAG.getConstant(VTBits, dl, MVT::i32));
4249   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4250   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4251
4252   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4253   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4254   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4255                           ISD::SETGE, ARMcc, DAG, dl);
4256   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4257   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4258                            CCR, Cmp);
4259
4260   SDValue Ops[2] = { Lo, Hi };
4261   return DAG.getMergeValues(Ops, dl);
4262 }
4263
4264 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4265                                             SelectionDAG &DAG) const {
4266   // The rounding mode is in bits 23:22 of the FPSCR.
4267   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4268   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4269   // so that the shift + and get folded into a bitfield extract.
4270   SDLoc dl(Op);
4271   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4272                               DAG.getConstant(Intrinsic::arm_get_fpscr, dl,
4273                                               MVT::i32));
4274   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4275                                   DAG.getConstant(1U << 22, dl, MVT::i32));
4276   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4277                               DAG.getConstant(22, dl, MVT::i32));
4278   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4279                      DAG.getConstant(3, dl, MVT::i32));
4280 }
4281
4282 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4283                          const ARMSubtarget *ST) {
4284   EVT VT = N->getValueType(0);
4285   SDLoc dl(N);
4286
4287   if (!ST->hasV6T2Ops())
4288     return SDValue();
4289
4290   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4291   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4292 }
4293
4294 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4295 /// for each 16-bit element from operand, repeated.  The basic idea is to
4296 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4297 ///
4298 /// Trace for v4i16:
4299 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
4300 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4301 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4302 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4303 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
4304 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
4305 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4306 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
4307 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4308   EVT VT = N->getValueType(0);
4309   SDLoc DL(N);
4310
4311   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4312   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4313   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4314   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4315   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4316   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4317 }
4318
4319 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4320 /// bit-count for each 16-bit element from the operand.  We need slightly
4321 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4322 /// 64/128-bit registers.
4323 ///
4324 /// Trace for v4i16:
4325 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
4326 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4327 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
4328 /// v4i16:Extracted = [k0    k1    k2    k3    ]
4329 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4330   EVT VT = N->getValueType(0);
4331   SDLoc DL(N);
4332
4333   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4334   if (VT.is64BitVector()) {
4335     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4336     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4337                        DAG.getIntPtrConstant(0, DL));
4338   } else {
4339     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4340                                     BitCounts, DAG.getIntPtrConstant(0, DL));
4341     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4342   }
4343 }
4344
4345 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4346 /// bit-count for each 32-bit element from the operand.  The idea here is
4347 /// to split the vector into 16-bit elements, leverage the 16-bit count
4348 /// routine, and then combine the results.
4349 ///
4350 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4351 /// input    = [v0    v1    ] (vi: 32-bit elements)
4352 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4353 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4354 /// vrev: N0 = [k1 k0 k3 k2 ]
4355 ///            [k0 k1 k2 k3 ]
4356 ///       N1 =+[k1 k0 k3 k2 ]
4357 ///            [k0 k2 k1 k3 ]
4358 ///       N2 =+[k1 k3 k0 k2 ]
4359 ///            [k0    k2    k1    k3    ]
4360 /// Extended =+[k1    k3    k0    k2    ]
4361 ///            [k0    k2    ]
4362 /// Extracted=+[k1    k3    ]
4363 ///
4364 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4365   EVT VT = N->getValueType(0);
4366   SDLoc DL(N);
4367
4368   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4369
4370   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4371   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4372   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4373   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4374   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4375
4376   if (VT.is64BitVector()) {
4377     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4378     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4379                        DAG.getIntPtrConstant(0, DL));
4380   } else {
4381     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4382                                     DAG.getIntPtrConstant(0, DL));
4383     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4384   }
4385 }
4386
4387 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4388                           const ARMSubtarget *ST) {
4389   EVT VT = N->getValueType(0);
4390
4391   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4392   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4393           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4394          "Unexpected type for custom ctpop lowering");
4395
4396   if (VT.getVectorElementType() == MVT::i32)
4397     return lowerCTPOP32BitElements(N, DAG);
4398   else
4399     return lowerCTPOP16BitElements(N, DAG);
4400 }
4401
4402 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4403                           const ARMSubtarget *ST) {
4404   EVT VT = N->getValueType(0);
4405   SDLoc dl(N);
4406
4407   if (!VT.isVector())
4408     return SDValue();
4409
4410   // Lower vector shifts on NEON to use VSHL.
4411   assert(ST->hasNEON() && "unexpected vector shift");
4412
4413   // Left shifts translate directly to the vshiftu intrinsic.
4414   if (N->getOpcode() == ISD::SHL)
4415     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4416                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
4417                                        MVT::i32),
4418                        N->getOperand(0), N->getOperand(1));
4419
4420   assert((N->getOpcode() == ISD::SRA ||
4421           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4422
4423   // NEON uses the same intrinsics for both left and right shifts.  For
4424   // right shifts, the shift amounts are negative, so negate the vector of
4425   // shift amounts.
4426   EVT ShiftVT = N->getOperand(1).getValueType();
4427   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4428                                      getZeroVector(ShiftVT, DAG, dl),
4429                                      N->getOperand(1));
4430   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4431                              Intrinsic::arm_neon_vshifts :
4432                              Intrinsic::arm_neon_vshiftu);
4433   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4434                      DAG.getConstant(vshiftInt, dl, MVT::i32),
4435                      N->getOperand(0), NegatedCount);
4436 }
4437
4438 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4439                                 const ARMSubtarget *ST) {
4440   EVT VT = N->getValueType(0);
4441   SDLoc dl(N);
4442
4443   // We can get here for a node like i32 = ISD::SHL i32, i64
4444   if (VT != MVT::i64)
4445     return SDValue();
4446
4447   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4448          "Unknown shift to lower!");
4449
4450   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4451   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4452       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4453     return SDValue();
4454
4455   // If we are in thumb mode, we don't have RRX.
4456   if (ST->isThumb1Only()) return SDValue();
4457
4458   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4459   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4460                            DAG.getConstant(0, dl, MVT::i32));
4461   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4462                            DAG.getConstant(1, dl, MVT::i32));
4463
4464   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4465   // captures the result into a carry flag.
4466   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4467   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4468
4469   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4470   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4471
4472   // Merge the pieces into a single i64 value.
4473  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4474 }
4475
4476 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4477   SDValue TmpOp0, TmpOp1;
4478   bool Invert = false;
4479   bool Swap = false;
4480   unsigned Opc = 0;
4481
4482   SDValue Op0 = Op.getOperand(0);
4483   SDValue Op1 = Op.getOperand(1);
4484   SDValue CC = Op.getOperand(2);
4485   EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
4486   EVT VT = Op.getValueType();
4487   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4488   SDLoc dl(Op);
4489
4490   if (Op1.getValueType().isFloatingPoint()) {
4491     switch (SetCCOpcode) {
4492     default: llvm_unreachable("Illegal FP comparison");
4493     case ISD::SETUNE:
4494     case ISD::SETNE:  Invert = true; // Fallthrough
4495     case ISD::SETOEQ:
4496     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4497     case ISD::SETOLT:
4498     case ISD::SETLT: Swap = true; // Fallthrough
4499     case ISD::SETOGT:
4500     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4501     case ISD::SETOLE:
4502     case ISD::SETLE:  Swap = true; // Fallthrough
4503     case ISD::SETOGE:
4504     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4505     case ISD::SETUGE: Swap = true; // Fallthrough
4506     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4507     case ISD::SETUGT: Swap = true; // Fallthrough
4508     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4509     case ISD::SETUEQ: Invert = true; // Fallthrough
4510     case ISD::SETONE:
4511       // Expand this to (OLT | OGT).
4512       TmpOp0 = Op0;
4513       TmpOp1 = Op1;
4514       Opc = ISD::OR;
4515       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4516       Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
4517       break;
4518     case ISD::SETUO: Invert = true; // Fallthrough
4519     case ISD::SETO:
4520       // Expand this to (OLT | OGE).
4521       TmpOp0 = Op0;
4522       TmpOp1 = Op1;
4523       Opc = ISD::OR;
4524       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4525       Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
4526       break;
4527     }
4528   } else {
4529     // Integer comparisons.
4530     switch (SetCCOpcode) {
4531     default: llvm_unreachable("Illegal integer comparison");
4532     case ISD::SETNE:  Invert = true;
4533     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4534     case ISD::SETLT:  Swap = true;
4535     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4536     case ISD::SETLE:  Swap = true;
4537     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4538     case ISD::SETULT: Swap = true;
4539     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4540     case ISD::SETULE: Swap = true;
4541     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4542     }
4543
4544     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4545     if (Opc == ARMISD::VCEQ) {
4546
4547       SDValue AndOp;
4548       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4549         AndOp = Op0;
4550       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4551         AndOp = Op1;
4552
4553       // Ignore bitconvert.
4554       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4555         AndOp = AndOp.getOperand(0);
4556
4557       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4558         Opc = ARMISD::VTST;
4559         Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
4560         Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
4561         Invert = !Invert;
4562       }
4563     }
4564   }
4565
4566   if (Swap)
4567     std::swap(Op0, Op1);
4568
4569   // If one of the operands is a constant vector zero, attempt to fold the
4570   // comparison to a specialized compare-against-zero form.
4571   SDValue SingleOp;
4572   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4573     SingleOp = Op0;
4574   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4575     if (Opc == ARMISD::VCGE)
4576       Opc = ARMISD::VCLEZ;
4577     else if (Opc == ARMISD::VCGT)
4578       Opc = ARMISD::VCLTZ;
4579     SingleOp = Op1;
4580   }
4581
4582   SDValue Result;
4583   if (SingleOp.getNode()) {
4584     switch (Opc) {
4585     case ARMISD::VCEQ:
4586       Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
4587     case ARMISD::VCGE:
4588       Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
4589     case ARMISD::VCLEZ:
4590       Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
4591     case ARMISD::VCGT:
4592       Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
4593     case ARMISD::VCLTZ:
4594       Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
4595     default:
4596       Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4597     }
4598   } else {
4599      Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4600   }
4601
4602   Result = DAG.getSExtOrTrunc(Result, dl, VT);
4603
4604   if (Invert)
4605     Result = DAG.getNOT(dl, Result, VT);
4606
4607   return Result;
4608 }
4609
4610 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4611 /// valid vector constant for a NEON instruction with a "modified immediate"
4612 /// operand (e.g., VMOV).  If so, return the encoded value.
4613 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4614                                  unsigned SplatBitSize, SelectionDAG &DAG,
4615                                  SDLoc dl, EVT &VT, bool is128Bits,
4616                                  NEONModImmType type) {
4617   unsigned OpCmode, Imm;
4618
4619   // SplatBitSize is set to the smallest size that splats the vector, so a
4620   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4621   // immediate instructions others than VMOV do not support the 8-bit encoding
4622   // of a zero vector, and the default encoding of zero is supposed to be the
4623   // 32-bit version.
4624   if (SplatBits == 0)
4625     SplatBitSize = 32;
4626
4627   switch (SplatBitSize) {
4628   case 8:
4629     if (type != VMOVModImm)
4630       return SDValue();
4631     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4632     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4633     OpCmode = 0xe;
4634     Imm = SplatBits;
4635     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4636     break;
4637
4638   case 16:
4639     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4640     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4641     if ((SplatBits & ~0xff) == 0) {
4642       // Value = 0x00nn: Op=x, Cmode=100x.
4643       OpCmode = 0x8;
4644       Imm = SplatBits;
4645       break;
4646     }
4647     if ((SplatBits & ~0xff00) == 0) {
4648       // Value = 0xnn00: Op=x, Cmode=101x.
4649       OpCmode = 0xa;
4650       Imm = SplatBits >> 8;
4651       break;
4652     }
4653     return SDValue();
4654
4655   case 32:
4656     // NEON's 32-bit VMOV supports splat values where:
4657     // * only one byte is nonzero, or
4658     // * the least significant byte is 0xff and the second byte is nonzero, or
4659     // * the least significant 2 bytes are 0xff and the third is nonzero.
4660     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4661     if ((SplatBits & ~0xff) == 0) {
4662       // Value = 0x000000nn: Op=x, Cmode=000x.
4663       OpCmode = 0;
4664       Imm = SplatBits;
4665       break;
4666     }
4667     if ((SplatBits & ~0xff00) == 0) {
4668       // Value = 0x0000nn00: Op=x, Cmode=001x.
4669       OpCmode = 0x2;
4670       Imm = SplatBits >> 8;
4671       break;
4672     }
4673     if ((SplatBits & ~0xff0000) == 0) {
4674       // Value = 0x00nn0000: Op=x, Cmode=010x.
4675       OpCmode = 0x4;
4676       Imm = SplatBits >> 16;
4677       break;
4678     }
4679     if ((SplatBits & ~0xff000000) == 0) {
4680       // Value = 0xnn000000: Op=x, Cmode=011x.
4681       OpCmode = 0x6;
4682       Imm = SplatBits >> 24;
4683       break;
4684     }
4685
4686     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4687     if (type == OtherModImm) return SDValue();
4688
4689     if ((SplatBits & ~0xffff) == 0 &&
4690         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4691       // Value = 0x0000nnff: Op=x, Cmode=1100.
4692       OpCmode = 0xc;
4693       Imm = SplatBits >> 8;
4694       break;
4695     }
4696
4697     if ((SplatBits & ~0xffffff) == 0 &&
4698         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4699       // Value = 0x00nnffff: Op=x, Cmode=1101.
4700       OpCmode = 0xd;
4701       Imm = SplatBits >> 16;
4702       break;
4703     }
4704
4705     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4706     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4707     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4708     // and fall through here to test for a valid 64-bit splat.  But, then the
4709     // caller would also need to check and handle the change in size.
4710     return SDValue();
4711
4712   case 64: {
4713     if (type != VMOVModImm)
4714       return SDValue();
4715     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4716     uint64_t BitMask = 0xff;
4717     uint64_t Val = 0;
4718     unsigned ImmMask = 1;
4719     Imm = 0;
4720     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4721       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4722         Val |= BitMask;
4723         Imm |= ImmMask;
4724       } else if ((SplatBits & BitMask) != 0) {
4725         return SDValue();
4726       }
4727       BitMask <<= 8;
4728       ImmMask <<= 1;
4729     }
4730
4731     if (DAG.getTargetLoweringInfo().isBigEndian())
4732       // swap higher and lower 32 bit word
4733       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4734
4735     // Op=1, Cmode=1110.
4736     OpCmode = 0x1e;
4737     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4738     break;
4739   }
4740
4741   default:
4742     llvm_unreachable("unexpected size for isNEONModifiedImm");
4743   }
4744
4745   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4746   return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
4747 }
4748
4749 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4750                                            const ARMSubtarget *ST) const {
4751   if (!ST->hasVFP3())
4752     return SDValue();
4753
4754   bool IsDouble = Op.getValueType() == MVT::f64;
4755   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4756
4757   // Use the default (constant pool) lowering for double constants when we have
4758   // an SP-only FPU
4759   if (IsDouble && Subtarget->isFPOnlySP())
4760     return SDValue();
4761
4762   // Try splatting with a VMOV.f32...
4763   APFloat FPVal = CFP->getValueAPF();
4764   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4765
4766   if (ImmVal != -1) {
4767     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4768       // We have code in place to select a valid ConstantFP already, no need to
4769       // do any mangling.
4770       return Op;
4771     }
4772
4773     // It's a float and we are trying to use NEON operations where
4774     // possible. Lower it to a splat followed by an extract.
4775     SDLoc DL(Op);
4776     SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
4777     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4778                                       NewVal);
4779     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4780                        DAG.getConstant(0, DL, MVT::i32));
4781   }
4782
4783   // The rest of our options are NEON only, make sure that's allowed before
4784   // proceeding..
4785   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4786     return SDValue();
4787
4788   EVT VMovVT;
4789   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4790
4791   // It wouldn't really be worth bothering for doubles except for one very
4792   // important value, which does happen to match: 0.0. So make sure we don't do
4793   // anything stupid.
4794   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4795     return SDValue();
4796
4797   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4798   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
4799                                      VMovVT, false, VMOVModImm);
4800   if (NewVal != SDValue()) {
4801     SDLoc DL(Op);
4802     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4803                                       NewVal);
4804     if (IsDouble)
4805       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4806
4807     // It's a float: cast and extract a vector element.
4808     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4809                                        VecConstant);
4810     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4811                        DAG.getConstant(0, DL, MVT::i32));
4812   }
4813
4814   // Finally, try a VMVN.i32
4815   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
4816                              false, VMVNModImm);
4817   if (NewVal != SDValue()) {
4818     SDLoc DL(Op);
4819     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4820
4821     if (IsDouble)
4822       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4823
4824     // It's a float: cast and extract a vector element.
4825     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4826                                        VecConstant);
4827     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4828                        DAG.getConstant(0, DL, MVT::i32));
4829   }
4830
4831   return SDValue();
4832 }
4833
4834 // check if an VEXT instruction can handle the shuffle mask when the
4835 // vector sources of the shuffle are the same.
4836 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4837   unsigned NumElts = VT.getVectorNumElements();
4838
4839   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4840   if (M[0] < 0)
4841     return false;
4842
4843   Imm = M[0];
4844
4845   // If this is a VEXT shuffle, the immediate value is the index of the first
4846   // element.  The other shuffle indices must be the successive elements after
4847   // the first one.
4848   unsigned ExpectedElt = Imm;
4849   for (unsigned i = 1; i < NumElts; ++i) {
4850     // Increment the expected index.  If it wraps around, just follow it
4851     // back to index zero and keep going.
4852     ++ExpectedElt;
4853     if (ExpectedElt == NumElts)
4854       ExpectedElt = 0;
4855
4856     if (M[i] < 0) continue; // ignore UNDEF indices
4857     if (ExpectedElt != static_cast<unsigned>(M[i]))
4858       return false;
4859   }
4860
4861   return true;
4862 }
4863
4864
4865 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4866                        bool &ReverseVEXT, unsigned &Imm) {
4867   unsigned NumElts = VT.getVectorNumElements();
4868   ReverseVEXT = false;
4869
4870   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4871   if (M[0] < 0)
4872     return false;
4873
4874   Imm = M[0];
4875
4876   // If this is a VEXT shuffle, the immediate value is the index of the first
4877   // element.  The other shuffle indices must be the successive elements after
4878   // the first one.
4879   unsigned ExpectedElt = Imm;
4880   for (unsigned i = 1; i < NumElts; ++i) {
4881     // Increment the expected index.  If it wraps around, it may still be
4882     // a VEXT but the source vectors must be swapped.
4883     ExpectedElt += 1;
4884     if (ExpectedElt == NumElts * 2) {
4885       ExpectedElt = 0;
4886       ReverseVEXT = true;
4887     }
4888
4889     if (M[i] < 0) continue; // ignore UNDEF indices
4890     if (ExpectedElt != static_cast<unsigned>(M[i]))
4891       return false;
4892   }
4893
4894   // Adjust the index value if the source operands will be swapped.
4895   if (ReverseVEXT)
4896     Imm -= NumElts;
4897
4898   return true;
4899 }
4900
4901 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4902 /// instruction with the specified blocksize.  (The order of the elements
4903 /// within each block of the vector is reversed.)
4904 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4905   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4906          "Only possible block sizes for VREV are: 16, 32, 64");
4907
4908   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4909   if (EltSz == 64)
4910     return false;
4911
4912   unsigned NumElts = VT.getVectorNumElements();
4913   unsigned BlockElts = M[0] + 1;
4914   // If the first shuffle index is UNDEF, be optimistic.
4915   if (M[0] < 0)
4916     BlockElts = BlockSize / EltSz;
4917
4918   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4919     return false;
4920
4921   for (unsigned i = 0; i < NumElts; ++i) {
4922     if (M[i] < 0) continue; // ignore UNDEF indices
4923     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4924       return false;
4925   }
4926
4927   return true;
4928 }
4929
4930 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4931   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4932   // range, then 0 is placed into the resulting vector. So pretty much any mask
4933   // of 8 elements can work here.
4934   return VT == MVT::v8i8 && M.size() == 8;
4935 }
4936
4937 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4938   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4939   if (EltSz == 64)
4940     return false;
4941
4942   unsigned NumElts = VT.getVectorNumElements();
4943   WhichResult = (M[0] == 0 ? 0 : 1);
4944   for (unsigned i = 0; i < NumElts; i += 2) {
4945     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4946         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4947       return false;
4948   }
4949   return true;
4950 }
4951
4952 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4953 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4954 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4955 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4956   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4957   if (EltSz == 64)
4958     return false;
4959
4960   unsigned NumElts = VT.getVectorNumElements();
4961   WhichResult = (M[0] == 0 ? 0 : 1);
4962   for (unsigned i = 0; i < NumElts; i += 2) {
4963     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4964         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4965       return false;
4966   }
4967   return true;
4968 }
4969
4970 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4971   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4972   if (EltSz == 64)
4973     return false;
4974
4975   unsigned NumElts = VT.getVectorNumElements();
4976   WhichResult = (M[0] == 0 ? 0 : 1);
4977   for (unsigned i = 0; i != NumElts; ++i) {
4978     if (M[i] < 0) continue; // ignore UNDEF indices
4979     if ((unsigned) M[i] != 2 * i + WhichResult)
4980       return false;
4981   }
4982
4983   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4984   if (VT.is64BitVector() && EltSz == 32)
4985     return false;
4986
4987   return true;
4988 }
4989
4990 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4991 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4992 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4993 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4994   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4995   if (EltSz == 64)
4996     return false;
4997
4998   unsigned Half = VT.getVectorNumElements() / 2;
4999   WhichResult = (M[0] == 0 ? 0 : 1);
5000   for (unsigned j = 0; j != 2; ++j) {
5001     unsigned Idx = WhichResult;
5002     for (unsigned i = 0; i != Half; ++i) {
5003       int MIdx = M[i + j * Half];
5004       if (MIdx >= 0 && (unsigned) MIdx != Idx)
5005         return false;
5006       Idx += 2;
5007     }
5008   }
5009
5010   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5011   if (VT.is64BitVector() && EltSz == 32)
5012     return false;
5013
5014   return true;
5015 }
5016
5017 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5018   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5019   if (EltSz == 64)
5020     return false;
5021
5022   unsigned NumElts = VT.getVectorNumElements();
5023   WhichResult = (M[0] == 0 ? 0 : 1);
5024   unsigned Idx = WhichResult * NumElts / 2;
5025   for (unsigned i = 0; i != NumElts; i += 2) {
5026     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
5027         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
5028       return false;
5029     Idx += 1;
5030   }
5031
5032   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5033   if (VT.is64BitVector() && EltSz == 32)
5034     return false;
5035
5036   return true;
5037 }
5038
5039 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5040 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5041 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5042 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5043   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5044   if (EltSz == 64)
5045     return false;
5046
5047   unsigned NumElts = VT.getVectorNumElements();
5048   WhichResult = (M[0] == 0 ? 0 : 1);
5049   unsigned Idx = WhichResult * NumElts / 2;
5050   for (unsigned i = 0; i != NumElts; i += 2) {
5051     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
5052         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
5053       return false;
5054     Idx += 1;
5055   }
5056
5057   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5058   if (VT.is64BitVector() && EltSz == 32)
5059     return false;
5060
5061   return true;
5062 }
5063
5064 /// \return true if this is a reverse operation on an vector.
5065 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5066   unsigned NumElts = VT.getVectorNumElements();
5067   // Make sure the mask has the right size.
5068   if (NumElts != M.size())
5069       return false;
5070
5071   // Look for <15, ..., 3, -1, 1, 0>.
5072   for (unsigned i = 0; i != NumElts; ++i)
5073     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5074       return false;
5075
5076   return true;
5077 }
5078
5079 // If N is an integer constant that can be moved into a register in one
5080 // instruction, return an SDValue of such a constant (will become a MOV
5081 // instruction).  Otherwise return null.
5082 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5083                                      const ARMSubtarget *ST, SDLoc dl) {
5084   uint64_t Val;
5085   if (!isa<ConstantSDNode>(N))
5086     return SDValue();
5087   Val = cast<ConstantSDNode>(N)->getZExtValue();
5088
5089   if (ST->isThumb1Only()) {
5090     if (Val <= 255 || ~Val <= 255)
5091       return DAG.getConstant(Val, dl, MVT::i32);
5092   } else {
5093     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5094       return DAG.getConstant(Val, dl, MVT::i32);
5095   }
5096   return SDValue();
5097 }
5098
5099 // If this is a case we can't handle, return null and let the default
5100 // expansion code take care of it.
5101 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5102                                              const ARMSubtarget *ST) const {
5103   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5104   SDLoc dl(Op);
5105   EVT VT = Op.getValueType();
5106
5107   APInt SplatBits, SplatUndef;
5108   unsigned SplatBitSize;
5109   bool HasAnyUndefs;
5110   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5111     if (SplatBitSize <= 64) {
5112       // Check if an immediate VMOV works.
5113       EVT VmovVT;
5114       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5115                                       SplatUndef.getZExtValue(), SplatBitSize,
5116                                       DAG, dl, VmovVT, VT.is128BitVector(),
5117                                       VMOVModImm);
5118       if (Val.getNode()) {
5119         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5120         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5121       }
5122
5123       // Try an immediate VMVN.
5124       uint64_t NegatedImm = (~SplatBits).getZExtValue();
5125       Val = isNEONModifiedImm(NegatedImm,
5126                                       SplatUndef.getZExtValue(), SplatBitSize,
5127                                       DAG, dl, VmovVT, VT.is128BitVector(),
5128                                       VMVNModImm);
5129       if (Val.getNode()) {
5130         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5131         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5132       }
5133
5134       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5135       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5136         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5137         if (ImmVal != -1) {
5138           SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
5139           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5140         }
5141       }
5142     }
5143   }
5144
5145   // Scan through the operands to see if only one value is used.
5146   //
5147   // As an optimisation, even if more than one value is used it may be more
5148   // profitable to splat with one value then change some lanes.
5149   //
5150   // Heuristically we decide to do this if the vector has a "dominant" value,
5151   // defined as splatted to more than half of the lanes.
5152   unsigned NumElts = VT.getVectorNumElements();
5153   bool isOnlyLowElement = true;
5154   bool usesOnlyOneValue = true;
5155   bool hasDominantValue = false;
5156   bool isConstant = true;
5157
5158   // Map of the number of times a particular SDValue appears in the
5159   // element list.
5160   DenseMap<SDValue, unsigned> ValueCounts;
5161   SDValue Value;
5162   for (unsigned i = 0; i < NumElts; ++i) {
5163     SDValue V = Op.getOperand(i);
5164     if (V.getOpcode() == ISD::UNDEF)
5165       continue;
5166     if (i > 0)
5167       isOnlyLowElement = false;
5168     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5169       isConstant = false;
5170
5171     ValueCounts.insert(std::make_pair(V, 0));
5172     unsigned &Count = ValueCounts[V];
5173
5174     // Is this value dominant? (takes up more than half of the lanes)
5175     if (++Count > (NumElts / 2)) {
5176       hasDominantValue = true;
5177       Value = V;
5178     }
5179   }
5180   if (ValueCounts.size() != 1)
5181     usesOnlyOneValue = false;
5182   if (!Value.getNode() && ValueCounts.size() > 0)
5183     Value = ValueCounts.begin()->first;
5184
5185   if (ValueCounts.size() == 0)
5186     return DAG.getUNDEF(VT);
5187
5188   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5189   // Keep going if we are hitting this case.
5190   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5191     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5192
5193   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5194
5195   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
5196   // i32 and try again.
5197   if (hasDominantValue && EltSize <= 32) {
5198     if (!isConstant) {
5199       SDValue N;
5200
5201       // If we are VDUPing a value that comes directly from a vector, that will
5202       // cause an unnecessary move to and from a GPR, where instead we could
5203       // just use VDUPLANE. We can only do this if the lane being extracted
5204       // is at a constant index, as the VDUP from lane instructions only have
5205       // constant-index forms.
5206       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5207           isa<ConstantSDNode>(Value->getOperand(1))) {
5208         // We need to create a new undef vector to use for the VDUPLANE if the
5209         // size of the vector from which we get the value is different than the
5210         // size of the vector that we need to create. We will insert the element
5211         // such that the register coalescer will remove unnecessary copies.
5212         if (VT != Value->getOperand(0).getValueType()) {
5213           ConstantSDNode *constIndex;
5214           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5215           assert(constIndex && "The index is not a constant!");
5216           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5217                              VT.getVectorNumElements();
5218           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5219                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5220                         Value, DAG.getConstant(index, dl, MVT::i32)),
5221                            DAG.getConstant(index, dl, MVT::i32));
5222         } else
5223           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5224                         Value->getOperand(0), Value->getOperand(1));
5225       } else
5226         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5227
5228       if (!usesOnlyOneValue) {
5229         // The dominant value was splatted as 'N', but we now have to insert
5230         // all differing elements.
5231         for (unsigned I = 0; I < NumElts; ++I) {
5232           if (Op.getOperand(I) == Value)
5233             continue;
5234           SmallVector<SDValue, 3> Ops;
5235           Ops.push_back(N);
5236           Ops.push_back(Op.getOperand(I));
5237           Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
5238           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5239         }
5240       }
5241       return N;
5242     }
5243     if (VT.getVectorElementType().isFloatingPoint()) {
5244       SmallVector<SDValue, 8> Ops;
5245       for (unsigned i = 0; i < NumElts; ++i)
5246         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5247                                   Op.getOperand(i)));
5248       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5249       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5250       Val = LowerBUILD_VECTOR(Val, DAG, ST);
5251       if (Val.getNode())
5252         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5253     }
5254     if (usesOnlyOneValue) {
5255       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5256       if (isConstant && Val.getNode())
5257         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5258     }
5259   }
5260
5261   // If all elements are constants and the case above didn't get hit, fall back
5262   // to the default expansion, which will generate a load from the constant
5263   // pool.
5264   if (isConstant)
5265     return SDValue();
5266
5267   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5268   if (NumElts >= 4) {
5269     SDValue shuffle = ReconstructShuffle(Op, DAG);
5270     if (shuffle != SDValue())
5271       return shuffle;
5272   }
5273
5274   // Vectors with 32- or 64-bit elements can be built by directly assigning
5275   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
5276   // will be legalized.
5277   if (EltSize >= 32) {
5278     // Do the expansion with floating-point types, since that is what the VFP
5279     // registers are defined to use, and since i64 is not legal.
5280     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5281     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5282     SmallVector<SDValue, 8> Ops;
5283     for (unsigned i = 0; i < NumElts; ++i)
5284       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5285     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5286     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5287   }
5288
5289   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5290   // know the default expansion would otherwise fall back on something even
5291   // worse. For a vector with one or two non-undef values, that's
5292   // scalar_to_vector for the elements followed by a shuffle (provided the
5293   // shuffle is valid for the target) and materialization element by element
5294   // on the stack followed by a load for everything else.
5295   if (!isConstant && !usesOnlyOneValue) {
5296     SDValue Vec = DAG.getUNDEF(VT);
5297     for (unsigned i = 0 ; i < NumElts; ++i) {
5298       SDValue V = Op.getOperand(i);
5299       if (V.getOpcode() == ISD::UNDEF)
5300         continue;
5301       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
5302       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5303     }
5304     return Vec;
5305   }
5306
5307   return SDValue();
5308 }
5309
5310 // Gather data to see if the operation can be modelled as a
5311 // shuffle in combination with VEXTs.
5312 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5313                                               SelectionDAG &DAG) const {
5314   SDLoc dl(Op);
5315   EVT VT = Op.getValueType();
5316   unsigned NumElts = VT.getVectorNumElements();
5317
5318   SmallVector<SDValue, 2> SourceVecs;
5319   SmallVector<unsigned, 2> MinElts;
5320   SmallVector<unsigned, 2> MaxElts;
5321
5322   for (unsigned i = 0; i < NumElts; ++i) {
5323     SDValue V = Op.getOperand(i);
5324     if (V.getOpcode() == ISD::UNDEF)
5325       continue;
5326     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5327       // A shuffle can only come from building a vector from various
5328       // elements of other vectors.
5329       return SDValue();
5330     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5331                VT.getVectorElementType()) {
5332       // This code doesn't know how to handle shuffles where the vector
5333       // element types do not match (this happens because type legalization
5334       // promotes the return type of EXTRACT_VECTOR_ELT).
5335       // FIXME: It might be appropriate to extend this code to handle
5336       // mismatched types.
5337       return SDValue();
5338     }
5339
5340     // Record this extraction against the appropriate vector if possible...
5341     SDValue SourceVec = V.getOperand(0);
5342     // If the element number isn't a constant, we can't effectively
5343     // analyze what's going on.
5344     if (!isa<ConstantSDNode>(V.getOperand(1)))
5345       return SDValue();
5346     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5347     bool FoundSource = false;
5348     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5349       if (SourceVecs[j] == SourceVec) {
5350         if (MinElts[j] > EltNo)
5351           MinElts[j] = EltNo;
5352         if (MaxElts[j] < EltNo)
5353           MaxElts[j] = EltNo;
5354         FoundSource = true;
5355         break;
5356       }
5357     }
5358
5359     // Or record a new source if not...
5360     if (!FoundSource) {
5361       SourceVecs.push_back(SourceVec);
5362       MinElts.push_back(EltNo);
5363       MaxElts.push_back(EltNo);
5364     }
5365   }
5366
5367   // Currently only do something sane when at most two source vectors
5368   // involved.
5369   if (SourceVecs.size() > 2)
5370     return SDValue();
5371
5372   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5373   int VEXTOffsets[2] = {0, 0};
5374
5375   // This loop extracts the usage patterns of the source vectors
5376   // and prepares appropriate SDValues for a shuffle if possible.
5377   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5378     if (SourceVecs[i].getValueType() == VT) {
5379       // No VEXT necessary
5380       ShuffleSrcs[i] = SourceVecs[i];
5381       VEXTOffsets[i] = 0;
5382       continue;
5383     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5384       // It probably isn't worth padding out a smaller vector just to
5385       // break it down again in a shuffle.
5386       return SDValue();
5387     }
5388
5389     // Since only 64-bit and 128-bit vectors are legal on ARM and
5390     // we've eliminated the other cases...
5391     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5392            "unexpected vector sizes in ReconstructShuffle");
5393
5394     if (MaxElts[i] - MinElts[i] >= NumElts) {
5395       // Span too large for a VEXT to cope
5396       return SDValue();
5397     }
5398
5399     if (MinElts[i] >= NumElts) {
5400       // The extraction can just take the second half
5401       VEXTOffsets[i] = NumElts;
5402       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5403                                    SourceVecs[i],
5404                                    DAG.getIntPtrConstant(NumElts, dl));
5405     } else if (MaxElts[i] < NumElts) {
5406       // The extraction can just take the first half
5407       VEXTOffsets[i] = 0;
5408       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5409                                    SourceVecs[i],
5410                                    DAG.getIntPtrConstant(0, dl));
5411     } else {
5412       // An actual VEXT is needed
5413       VEXTOffsets[i] = MinElts[i];
5414       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5415                                      SourceVecs[i],
5416                                      DAG.getIntPtrConstant(0, dl));
5417       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5418                                      SourceVecs[i],
5419                                      DAG.getIntPtrConstant(NumElts, dl));
5420       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5421                                    DAG.getConstant(VEXTOffsets[i], dl,
5422                                                    MVT::i32));
5423     }
5424   }
5425
5426   SmallVector<int, 8> Mask;
5427
5428   for (unsigned i = 0; i < NumElts; ++i) {
5429     SDValue Entry = Op.getOperand(i);
5430     if (Entry.getOpcode() == ISD::UNDEF) {
5431       Mask.push_back(-1);
5432       continue;
5433     }
5434
5435     SDValue ExtractVec = Entry.getOperand(0);
5436     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5437                                           .getOperand(1))->getSExtValue();
5438     if (ExtractVec == SourceVecs[0]) {
5439       Mask.push_back(ExtractElt - VEXTOffsets[0]);
5440     } else {
5441       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5442     }
5443   }
5444
5445   // Final check before we try to produce nonsense...
5446   if (isShuffleMaskLegal(Mask, VT))
5447     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5448                                 &Mask[0]);
5449
5450   return SDValue();
5451 }
5452
5453 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5454 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5455 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5456 /// are assumed to be legal.
5457 bool
5458 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5459                                       EVT VT) const {
5460   if (VT.getVectorNumElements() == 4 &&
5461       (VT.is128BitVector() || VT.is64BitVector())) {
5462     unsigned PFIndexes[4];
5463     for (unsigned i = 0; i != 4; ++i) {
5464       if (M[i] < 0)
5465         PFIndexes[i] = 8;
5466       else
5467         PFIndexes[i] = M[i];
5468     }
5469
5470     // Compute the index in the perfect shuffle table.
5471     unsigned PFTableIndex =
5472       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5473     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5474     unsigned Cost = (PFEntry >> 30);
5475
5476     if (Cost <= 4)
5477       return true;
5478   }
5479
5480   bool ReverseVEXT;
5481   unsigned Imm, WhichResult;
5482
5483   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5484   return (EltSize >= 32 ||
5485           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5486           isVREVMask(M, VT, 64) ||
5487           isVREVMask(M, VT, 32) ||
5488           isVREVMask(M, VT, 16) ||
5489           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5490           isVTBLMask(M, VT) ||
5491           isVTRNMask(M, VT, WhichResult) ||
5492           isVUZPMask(M, VT, WhichResult) ||
5493           isVZIPMask(M, VT, WhichResult) ||
5494           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5495           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5496           isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5497           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5498 }
5499
5500 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5501 /// the specified operations to build the shuffle.
5502 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5503                                       SDValue RHS, SelectionDAG &DAG,
5504                                       SDLoc dl) {
5505   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5506   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5507   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5508
5509   enum {
5510     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5511     OP_VREV,
5512     OP_VDUP0,
5513     OP_VDUP1,
5514     OP_VDUP2,
5515     OP_VDUP3,
5516     OP_VEXT1,
5517     OP_VEXT2,
5518     OP_VEXT3,
5519     OP_VUZPL, // VUZP, left result
5520     OP_VUZPR, // VUZP, right result
5521     OP_VZIPL, // VZIP, left result
5522     OP_VZIPR, // VZIP, right result
5523     OP_VTRNL, // VTRN, left result
5524     OP_VTRNR  // VTRN, right result
5525   };
5526
5527   if (OpNum == OP_COPY) {
5528     if (LHSID == (1*9+2)*9+3) return LHS;
5529     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5530     return RHS;
5531   }
5532
5533   SDValue OpLHS, OpRHS;
5534   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5535   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5536   EVT VT = OpLHS.getValueType();
5537
5538   switch (OpNum) {
5539   default: llvm_unreachable("Unknown shuffle opcode!");
5540   case OP_VREV:
5541     // VREV divides the vector in half and swaps within the half.
5542     if (VT.getVectorElementType() == MVT::i32 ||
5543         VT.getVectorElementType() == MVT::f32)
5544       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5545     // vrev <4 x i16> -> VREV32
5546     if (VT.getVectorElementType() == MVT::i16)
5547       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5548     // vrev <4 x i8> -> VREV16
5549     assert(VT.getVectorElementType() == MVT::i8);
5550     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5551   case OP_VDUP0:
5552   case OP_VDUP1:
5553   case OP_VDUP2:
5554   case OP_VDUP3:
5555     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5556                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
5557   case OP_VEXT1:
5558   case OP_VEXT2:
5559   case OP_VEXT3:
5560     return DAG.getNode(ARMISD::VEXT, dl, VT,
5561                        OpLHS, OpRHS,
5562                        DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
5563   case OP_VUZPL:
5564   case OP_VUZPR:
5565     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5566                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5567   case OP_VZIPL:
5568   case OP_VZIPR:
5569     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5570                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5571   case OP_VTRNL:
5572   case OP_VTRNR:
5573     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5574                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5575   }
5576 }
5577
5578 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5579                                        ArrayRef<int> ShuffleMask,
5580                                        SelectionDAG &DAG) {
5581   // Check to see if we can use the VTBL instruction.
5582   SDValue V1 = Op.getOperand(0);
5583   SDValue V2 = Op.getOperand(1);
5584   SDLoc DL(Op);
5585
5586   SmallVector<SDValue, 8> VTBLMask;
5587   for (ArrayRef<int>::iterator
5588          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5589     VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
5590
5591   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5592     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5593                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5594
5595   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5596                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5597 }
5598
5599 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5600                                                       SelectionDAG &DAG) {
5601   SDLoc DL(Op);
5602   SDValue OpLHS = Op.getOperand(0);
5603   EVT VT = OpLHS.getValueType();
5604
5605   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5606          "Expect an v8i16/v16i8 type");
5607   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5608   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5609   // extract the first 8 bytes into the top double word and the last 8 bytes
5610   // into the bottom double word. The v8i16 case is similar.
5611   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5612   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5613                      DAG.getConstant(ExtractNum, DL, MVT::i32));
5614 }
5615
5616 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5617   SDValue V1 = Op.getOperand(0);
5618   SDValue V2 = Op.getOperand(1);
5619   SDLoc dl(Op);
5620   EVT VT = Op.getValueType();
5621   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5622
5623   // Convert shuffles that are directly supported on NEON to target-specific
5624   // DAG nodes, instead of keeping them as shuffles and matching them again
5625   // during code selection.  This is more efficient and avoids the possibility
5626   // of inconsistencies between legalization and selection.
5627   // FIXME: floating-point vectors should be canonicalized to integer vectors
5628   // of the same time so that they get CSEd properly.
5629   ArrayRef<int> ShuffleMask = SVN->getMask();
5630
5631   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5632   if (EltSize <= 32) {
5633     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5634       int Lane = SVN->getSplatIndex();
5635       // If this is undef splat, generate it via "just" vdup, if possible.
5636       if (Lane == -1) Lane = 0;
5637
5638       // Test if V1 is a SCALAR_TO_VECTOR.
5639       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5640         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5641       }
5642       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5643       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5644       // reaches it).
5645       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5646           !isa<ConstantSDNode>(V1.getOperand(0))) {
5647         bool IsScalarToVector = true;
5648         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5649           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5650             IsScalarToVector = false;
5651             break;
5652           }
5653         if (IsScalarToVector)
5654           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5655       }
5656       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5657                          DAG.getConstant(Lane, dl, MVT::i32));
5658     }
5659
5660     bool ReverseVEXT;
5661     unsigned Imm;
5662     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5663       if (ReverseVEXT)
5664         std::swap(V1, V2);
5665       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5666                          DAG.getConstant(Imm, dl, MVT::i32));
5667     }
5668
5669     if (isVREVMask(ShuffleMask, VT, 64))
5670       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5671     if (isVREVMask(ShuffleMask, VT, 32))
5672       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5673     if (isVREVMask(ShuffleMask, VT, 16))
5674       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5675
5676     if (V2->getOpcode() == ISD::UNDEF &&
5677         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5678       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5679                          DAG.getConstant(Imm, dl, MVT::i32));
5680     }
5681
5682     // Check for Neon shuffles that modify both input vectors in place.
5683     // If both results are used, i.e., if there are two shuffles with the same
5684     // source operands and with masks corresponding to both results of one of
5685     // these operations, DAG memoization will ensure that a single node is
5686     // used for both shuffles.
5687     unsigned WhichResult;
5688     if (isVTRNMask(ShuffleMask, VT, WhichResult))
5689       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5690                          V1, V2).getValue(WhichResult);
5691     if (isVUZPMask(ShuffleMask, VT, WhichResult))
5692       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5693                          V1, V2).getValue(WhichResult);
5694     if (isVZIPMask(ShuffleMask, VT, WhichResult))
5695       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5696                          V1, V2).getValue(WhichResult);
5697
5698     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5699       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5700                          V1, V1).getValue(WhichResult);
5701     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5702       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5703                          V1, V1).getValue(WhichResult);
5704     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5705       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5706                          V1, V1).getValue(WhichResult);
5707   }
5708
5709   // If the shuffle is not directly supported and it has 4 elements, use
5710   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5711   unsigned NumElts = VT.getVectorNumElements();
5712   if (NumElts == 4) {
5713     unsigned PFIndexes[4];
5714     for (unsigned i = 0; i != 4; ++i) {
5715       if (ShuffleMask[i] < 0)
5716         PFIndexes[i] = 8;
5717       else
5718         PFIndexes[i] = ShuffleMask[i];
5719     }
5720
5721     // Compute the index in the perfect shuffle table.
5722     unsigned PFTableIndex =
5723       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5724     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5725     unsigned Cost = (PFEntry >> 30);
5726
5727     if (Cost <= 4)
5728       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5729   }
5730
5731   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5732   if (EltSize >= 32) {
5733     // Do the expansion with floating-point types, since that is what the VFP
5734     // registers are defined to use, and since i64 is not legal.
5735     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5736     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5737     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5738     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5739     SmallVector<SDValue, 8> Ops;
5740     for (unsigned i = 0; i < NumElts; ++i) {
5741       if (ShuffleMask[i] < 0)
5742         Ops.push_back(DAG.getUNDEF(EltVT));
5743       else
5744         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5745                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
5746                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5747                                                   dl, MVT::i32)));
5748     }
5749     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5750     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5751   }
5752
5753   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5754     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5755
5756   if (VT == MVT::v8i8) {
5757     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5758     if (NewOp.getNode())
5759       return NewOp;
5760   }
5761
5762   return SDValue();
5763 }
5764
5765 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5766   // INSERT_VECTOR_ELT is legal only for immediate indexes.
5767   SDValue Lane = Op.getOperand(2);
5768   if (!isa<ConstantSDNode>(Lane))
5769     return SDValue();
5770
5771   return Op;
5772 }
5773
5774 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5775   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5776   SDValue Lane = Op.getOperand(1);
5777   if (!isa<ConstantSDNode>(Lane))
5778     return SDValue();
5779
5780   SDValue Vec = Op.getOperand(0);
5781   if (Op.getValueType() == MVT::i32 &&
5782       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5783     SDLoc dl(Op);
5784     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5785   }
5786
5787   return Op;
5788 }
5789
5790 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5791   // The only time a CONCAT_VECTORS operation can have legal types is when
5792   // two 64-bit vectors are concatenated to a 128-bit vector.
5793   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5794          "unexpected CONCAT_VECTORS");
5795   SDLoc dl(Op);
5796   SDValue Val = DAG.getUNDEF(MVT::v2f64);
5797   SDValue Op0 = Op.getOperand(0);
5798   SDValue Op1 = Op.getOperand(1);
5799   if (Op0.getOpcode() != ISD::UNDEF)
5800     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5801                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5802                       DAG.getIntPtrConstant(0, dl));
5803   if (Op1.getOpcode() != ISD::UNDEF)
5804     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5805                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5806                       DAG.getIntPtrConstant(1, dl));
5807   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5808 }
5809
5810 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5811 /// element has been zero/sign-extended, depending on the isSigned parameter,
5812 /// from an integer type half its size.
5813 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5814                                    bool isSigned) {
5815   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5816   EVT VT = N->getValueType(0);
5817   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5818     SDNode *BVN = N->getOperand(0).getNode();
5819     if (BVN->getValueType(0) != MVT::v4i32 ||
5820         BVN->getOpcode() != ISD::BUILD_VECTOR)
5821       return false;
5822     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5823     unsigned HiElt = 1 - LoElt;
5824     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5825     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5826     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5827     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5828     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5829       return false;
5830     if (isSigned) {
5831       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5832           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5833         return true;
5834     } else {
5835       if (Hi0->isNullValue() && Hi1->isNullValue())
5836         return true;
5837     }
5838     return false;
5839   }
5840
5841   if (N->getOpcode() != ISD::BUILD_VECTOR)
5842     return false;
5843
5844   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5845     SDNode *Elt = N->getOperand(i).getNode();
5846     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5847       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5848       unsigned HalfSize = EltSize / 2;
5849       if (isSigned) {
5850         if (!isIntN(HalfSize, C->getSExtValue()))
5851           return false;
5852       } else {
5853         if (!isUIntN(HalfSize, C->getZExtValue()))
5854           return false;
5855       }
5856       continue;
5857     }
5858     return false;
5859   }
5860
5861   return true;
5862 }
5863
5864 /// isSignExtended - Check if a node is a vector value that is sign-extended
5865 /// or a constant BUILD_VECTOR with sign-extended elements.
5866 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5867   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5868     return true;
5869   if (isExtendedBUILD_VECTOR(N, DAG, true))
5870     return true;
5871   return false;
5872 }
5873
5874 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5875 /// or a constant BUILD_VECTOR with zero-extended elements.
5876 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5877   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5878     return true;
5879   if (isExtendedBUILD_VECTOR(N, DAG, false))
5880     return true;
5881   return false;
5882 }
5883
5884 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5885   if (OrigVT.getSizeInBits() >= 64)
5886     return OrigVT;
5887
5888   assert(OrigVT.isSimple() && "Expecting a simple value type");
5889
5890   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5891   switch (OrigSimpleTy) {
5892   default: llvm_unreachable("Unexpected Vector Type");
5893   case MVT::v2i8:
5894   case MVT::v2i16:
5895      return MVT::v2i32;
5896   case MVT::v4i8:
5897     return  MVT::v4i16;
5898   }
5899 }
5900
5901 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5902 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5903 /// We insert the required extension here to get the vector to fill a D register.
5904 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5905                                             const EVT &OrigTy,
5906                                             const EVT &ExtTy,
5907                                             unsigned ExtOpcode) {
5908   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5909   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5910   // 64-bits we need to insert a new extension so that it will be 64-bits.
5911   assert(ExtTy.is128BitVector() && "Unexpected extension size");
5912   if (OrigTy.getSizeInBits() >= 64)
5913     return N;
5914
5915   // Must extend size to at least 64 bits to be used as an operand for VMULL.
5916   EVT NewVT = getExtensionTo64Bits(OrigTy);
5917
5918   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5919 }
5920
5921 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5922 /// does not do any sign/zero extension. If the original vector is less
5923 /// than 64 bits, an appropriate extension will be added after the load to
5924 /// reach a total size of 64 bits. We have to add the extension separately
5925 /// because ARM does not have a sign/zero extending load for vectors.
5926 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5927   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5928
5929   // The load already has the right type.
5930   if (ExtendedTy == LD->getMemoryVT())
5931     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5932                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5933                 LD->isNonTemporal(), LD->isInvariant(),
5934                 LD->getAlignment());
5935
5936   // We need to create a zextload/sextload. We cannot just create a load
5937   // followed by a zext/zext node because LowerMUL is also run during normal
5938   // operation legalization where we can't create illegal types.
5939   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5940                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5941                         LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
5942                         LD->isNonTemporal(), LD->getAlignment());
5943 }
5944
5945 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5946 /// extending load, or BUILD_VECTOR with extended elements, return the
5947 /// unextended value. The unextended vector should be 64 bits so that it can
5948 /// be used as an operand to a VMULL instruction. If the original vector size
5949 /// before extension is less than 64 bits we add a an extension to resize
5950 /// the vector to 64 bits.
5951 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5952   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5953     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5954                                         N->getOperand(0)->getValueType(0),
5955                                         N->getValueType(0),
5956                                         N->getOpcode());
5957
5958   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5959     return SkipLoadExtensionForVMULL(LD, DAG);
5960
5961   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
5962   // have been legalized as a BITCAST from v4i32.
5963   if (N->getOpcode() == ISD::BITCAST) {
5964     SDNode *BVN = N->getOperand(0).getNode();
5965     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5966            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5967     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5968     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5969                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5970   }
5971   // Construct a new BUILD_VECTOR with elements truncated to half the size.
5972   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5973   EVT VT = N->getValueType(0);
5974   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5975   unsigned NumElts = VT.getVectorNumElements();
5976   MVT TruncVT = MVT::getIntegerVT(EltSize);
5977   SmallVector<SDValue, 8> Ops;
5978   SDLoc dl(N);
5979   for (unsigned i = 0; i != NumElts; ++i) {
5980     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5981     const APInt &CInt = C->getAPIntValue();
5982     // Element types smaller than 32 bits are not legal, so use i32 elements.
5983     // The values are implicitly truncated so sext vs. zext doesn't matter.
5984     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
5985   }
5986   return DAG.getNode(ISD::BUILD_VECTOR, dl,
5987                      MVT::getVectorVT(TruncVT, NumElts), Ops);
5988 }
5989
5990 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5991   unsigned Opcode = N->getOpcode();
5992   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5993     SDNode *N0 = N->getOperand(0).getNode();
5994     SDNode *N1 = N->getOperand(1).getNode();
5995     return N0->hasOneUse() && N1->hasOneUse() &&
5996       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5997   }
5998   return false;
5999 }
6000
6001 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
6002   unsigned Opcode = N->getOpcode();
6003   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6004     SDNode *N0 = N->getOperand(0).getNode();
6005     SDNode *N1 = N->getOperand(1).getNode();
6006     return N0->hasOneUse() && N1->hasOneUse() &&
6007       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
6008   }
6009   return false;
6010 }
6011
6012 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
6013   // Multiplications are only custom-lowered for 128-bit vectors so that
6014   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
6015   EVT VT = Op.getValueType();
6016   assert(VT.is128BitVector() && VT.isInteger() &&
6017          "unexpected type for custom-lowering ISD::MUL");
6018   SDNode *N0 = Op.getOperand(0).getNode();
6019   SDNode *N1 = Op.getOperand(1).getNode();
6020   unsigned NewOpc = 0;
6021   bool isMLA = false;
6022   bool isN0SExt = isSignExtended(N0, DAG);
6023   bool isN1SExt = isSignExtended(N1, DAG);
6024   if (isN0SExt && isN1SExt)
6025     NewOpc = ARMISD::VMULLs;
6026   else {
6027     bool isN0ZExt = isZeroExtended(N0, DAG);
6028     bool isN1ZExt = isZeroExtended(N1, DAG);
6029     if (isN0ZExt && isN1ZExt)
6030       NewOpc = ARMISD::VMULLu;
6031     else if (isN1SExt || isN1ZExt) {
6032       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
6033       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
6034       if (isN1SExt && isAddSubSExt(N0, DAG)) {
6035         NewOpc = ARMISD::VMULLs;
6036         isMLA = true;
6037       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
6038         NewOpc = ARMISD::VMULLu;
6039         isMLA = true;
6040       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
6041         std::swap(N0, N1);
6042         NewOpc = ARMISD::VMULLu;
6043         isMLA = true;
6044       }
6045     }
6046
6047     if (!NewOpc) {
6048       if (VT == MVT::v2i64)
6049         // Fall through to expand this.  It is not legal.
6050         return SDValue();
6051       else
6052         // Other vector multiplications are legal.
6053         return Op;
6054     }
6055   }
6056
6057   // Legalize to a VMULL instruction.
6058   SDLoc DL(Op);
6059   SDValue Op0;
6060   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
6061   if (!isMLA) {
6062     Op0 = SkipExtensionForVMULL(N0, DAG);
6063     assert(Op0.getValueType().is64BitVector() &&
6064            Op1.getValueType().is64BitVector() &&
6065            "unexpected types for extended operands to VMULL");
6066     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
6067   }
6068
6069   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
6070   // isel lowering to take advantage of no-stall back to back vmul + vmla.
6071   //   vmull q0, d4, d6
6072   //   vmlal q0, d5, d6
6073   // is faster than
6074   //   vaddl q0, d4, d5
6075   //   vmovl q1, d6
6076   //   vmul  q0, q0, q1
6077   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
6078   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
6079   EVT Op1VT = Op1.getValueType();
6080   return DAG.getNode(N0->getOpcode(), DL, VT,
6081                      DAG.getNode(NewOpc, DL, VT,
6082                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
6083                      DAG.getNode(NewOpc, DL, VT,
6084                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
6085 }
6086
6087 static SDValue
6088 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
6089   // Convert to float
6090   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
6091   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
6092   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
6093   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
6094   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
6095   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
6096   // Get reciprocal estimate.
6097   // float4 recip = vrecpeq_f32(yf);
6098   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6099                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6100                    Y);
6101   // Because char has a smaller range than uchar, we can actually get away
6102   // without any newton steps.  This requires that we use a weird bias
6103   // of 0xb000, however (again, this has been exhaustively tested).
6104   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
6105   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
6106   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
6107   Y = DAG.getConstant(0xb000, dl, MVT::i32);
6108   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
6109   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6110   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6111   // Convert back to short.
6112   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6113   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6114   return X;
6115 }
6116
6117 static SDValue
6118 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
6119   SDValue N2;
6120   // Convert to float.
6121   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6122   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6123   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6124   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6125   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6126   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6127
6128   // Use reciprocal estimate and one refinement step.
6129   // float4 recip = vrecpeq_f32(yf);
6130   // recip *= vrecpsq_f32(yf, recip);
6131   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6132                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6133                    N1);
6134   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6135                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6136                    N1, N2);
6137   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6138   // Because short has a smaller range than ushort, we can actually get away
6139   // with only a single newton step.  This requires that we use a weird bias
6140   // of 89, however (again, this has been exhaustively tested).
6141   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6142   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6143   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6144   N1 = DAG.getConstant(0x89, dl, MVT::i32);
6145   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6146   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6147   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6148   // Convert back to integer and return.
6149   // return vmovn_s32(vcvt_s32_f32(result));
6150   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6151   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6152   return N0;
6153 }
6154
6155 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6156   EVT VT = Op.getValueType();
6157   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6158          "unexpected type for custom-lowering ISD::SDIV");
6159
6160   SDLoc dl(Op);
6161   SDValue N0 = Op.getOperand(0);
6162   SDValue N1 = Op.getOperand(1);
6163   SDValue N2, N3;
6164
6165   if (VT == MVT::v8i8) {
6166     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6167     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6168
6169     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6170                      DAG.getIntPtrConstant(4, dl));
6171     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6172                      DAG.getIntPtrConstant(4, dl));
6173     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6174                      DAG.getIntPtrConstant(0, dl));
6175     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6176                      DAG.getIntPtrConstant(0, dl));
6177
6178     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6179     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6180
6181     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6182     N0 = LowerCONCAT_VECTORS(N0, DAG);
6183
6184     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6185     return N0;
6186   }
6187   return LowerSDIV_v4i16(N0, N1, dl, DAG);
6188 }
6189
6190 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6191   EVT VT = Op.getValueType();
6192   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6193          "unexpected type for custom-lowering ISD::UDIV");
6194
6195   SDLoc dl(Op);
6196   SDValue N0 = Op.getOperand(0);
6197   SDValue N1 = Op.getOperand(1);
6198   SDValue N2, N3;
6199
6200   if (VT == MVT::v8i8) {
6201     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6202     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6203
6204     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6205                      DAG.getIntPtrConstant(4, dl));
6206     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6207                      DAG.getIntPtrConstant(4, dl));
6208     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6209                      DAG.getIntPtrConstant(0, dl));
6210     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6211                      DAG.getIntPtrConstant(0, dl));
6212
6213     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6214     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6215
6216     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6217     N0 = LowerCONCAT_VECTORS(N0, DAG);
6218
6219     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6220                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
6221                                      MVT::i32),
6222                      N0);
6223     return N0;
6224   }
6225
6226   // v4i16 sdiv ... Convert to float.
6227   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6228   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6229   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6230   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6231   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6232   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6233
6234   // Use reciprocal estimate and two refinement steps.
6235   // float4 recip = vrecpeq_f32(yf);
6236   // recip *= vrecpsq_f32(yf, recip);
6237   // recip *= vrecpsq_f32(yf, recip);
6238   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6239                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6240                    BN1);
6241   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6242                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6243                    BN1, N2);
6244   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6245   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6246                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6247                    BN1, N2);
6248   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6249   // Simply multiplying by the reciprocal estimate can leave us a few ulps
6250   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6251   // and that it will never cause us to return an answer too large).
6252   // float4 result = as_float4(as_int4(xf*recip) + 2);
6253   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6254   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6255   N1 = DAG.getConstant(2, dl, MVT::i32);
6256   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6257   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6258   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6259   // Convert back to integer and return.
6260   // return vmovn_u32(vcvt_s32_f32(result));
6261   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6262   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6263   return N0;
6264 }
6265
6266 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6267   EVT VT = Op.getNode()->getValueType(0);
6268   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6269
6270   unsigned Opc;
6271   bool ExtraOp = false;
6272   switch (Op.getOpcode()) {
6273   default: llvm_unreachable("Invalid code");
6274   case ISD::ADDC: Opc = ARMISD::ADDC; break;
6275   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6276   case ISD::SUBC: Opc = ARMISD::SUBC; break;
6277   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6278   }
6279
6280   if (!ExtraOp)
6281     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6282                        Op.getOperand(1));
6283   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6284                      Op.getOperand(1), Op.getOperand(2));
6285 }
6286
6287 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6288   assert(Subtarget->isTargetDarwin());
6289
6290   // For iOS, we want to call an alternative entry point: __sincos_stret,
6291   // return values are passed via sret.
6292   SDLoc dl(Op);
6293   SDValue Arg = Op.getOperand(0);
6294   EVT ArgVT = Arg.getValueType();
6295   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6296
6297   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6298   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6299
6300   // Pair of floats / doubles used to pass the result.
6301   StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
6302
6303   // Create stack object for sret.
6304   const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
6305   const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
6306   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6307   SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
6308
6309   ArgListTy Args;
6310   ArgListEntry Entry;
6311
6312   Entry.Node = SRet;
6313   Entry.Ty = RetTy->getPointerTo();
6314   Entry.isSExt = false;
6315   Entry.isZExt = false;
6316   Entry.isSRet = true;
6317   Args.push_back(Entry);
6318
6319   Entry.Node = Arg;
6320   Entry.Ty = ArgTy;
6321   Entry.isSExt = false;
6322   Entry.isZExt = false;
6323   Args.push_back(Entry);
6324
6325   const char *LibcallName  = (ArgVT == MVT::f64)
6326   ? "__sincos_stret" : "__sincosf_stret";
6327   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
6328
6329   TargetLowering::CallLoweringInfo CLI(DAG);
6330   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6331     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6332                std::move(Args), 0)
6333     .setDiscardResult();
6334
6335   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6336
6337   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6338                                 MachinePointerInfo(), false, false, false, 0);
6339
6340   // Address of cos field.
6341   SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
6342                             DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
6343   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6344                                 MachinePointerInfo(), false, false, false, 0);
6345
6346   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6347   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6348                      LoadSin.getValue(0), LoadCos.getValue(0));
6349 }
6350
6351 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6352   // Monotonic load/store is legal for all targets
6353   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6354     return Op;
6355
6356   // Acquire/Release load/store is not legal for targets without a
6357   // dmb or equivalent available.
6358   return SDValue();
6359 }
6360
6361 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6362                                     SmallVectorImpl<SDValue> &Results,
6363                                     SelectionDAG &DAG,
6364                                     const ARMSubtarget *Subtarget) {
6365   SDLoc DL(N);
6366   SDValue Cycles32, OutChain;
6367
6368   if (Subtarget->hasPerfMon()) {
6369     // Under Power Management extensions, the cycle-count is:
6370     //    mrc p15, #0, <Rt>, c9, c13, #0
6371     SDValue Ops[] = { N->getOperand(0), // Chain
6372                       DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
6373                       DAG.getConstant(15, DL, MVT::i32),
6374                       DAG.getConstant(0, DL, MVT::i32),
6375                       DAG.getConstant(9, DL, MVT::i32),
6376                       DAG.getConstant(13, DL, MVT::i32),
6377                       DAG.getConstant(0, DL, MVT::i32)
6378     };
6379
6380     Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6381                            DAG.getVTList(MVT::i32, MVT::Other), Ops);
6382     OutChain = Cycles32.getValue(1);
6383   } else {
6384     // Intrinsic is defined to return 0 on unsupported platforms. Technically
6385     // there are older ARM CPUs that have implementation-specific ways of
6386     // obtaining this information (FIXME!).
6387     Cycles32 = DAG.getConstant(0, DL, MVT::i32);
6388     OutChain = DAG.getEntryNode();
6389   }
6390
6391
6392   SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6393                                  Cycles32, DAG.getConstant(0, DL, MVT::i32));
6394   Results.push_back(Cycles64);
6395   Results.push_back(OutChain);
6396 }
6397
6398 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6399   switch (Op.getOpcode()) {
6400   default: llvm_unreachable("Don't know how to custom lower this!");
6401   case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
6402   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6403   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6404   case ISD::GlobalAddress:
6405     switch (Subtarget->getTargetTriple().getObjectFormat()) {
6406     default: llvm_unreachable("unknown object format");
6407     case Triple::COFF:
6408       return LowerGlobalAddressWindows(Op, DAG);
6409     case Triple::ELF:
6410       return LowerGlobalAddressELF(Op, DAG);
6411     case Triple::MachO:
6412       return LowerGlobalAddressDarwin(Op, DAG);
6413     }
6414   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6415   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6416   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6417   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6418   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6419   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6420   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6421   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6422   case ISD::SINT_TO_FP:
6423   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6424   case ISD::FP_TO_SINT:
6425   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6426   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6427   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6428   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6429   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6430   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6431   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6432   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6433                                                                Subtarget);
6434   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6435   case ISD::SHL:
6436   case ISD::SRL:
6437   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6438   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6439   case ISD::SRL_PARTS:
6440   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6441   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6442   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6443   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6444   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6445   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6446   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6447   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6448   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6449   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6450   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6451   case ISD::MUL:           return LowerMUL(Op, DAG);
6452   case ISD::SDIV:          return LowerSDIV(Op, DAG);
6453   case ISD::UDIV:          return LowerUDIV(Op, DAG);
6454   case ISD::ADDC:
6455   case ISD::ADDE:
6456   case ISD::SUBC:
6457   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6458   case ISD::SADDO:
6459   case ISD::UADDO:
6460   case ISD::SSUBO:
6461   case ISD::USUBO:
6462     return LowerXALUO(Op, DAG);
6463   case ISD::ATOMIC_LOAD:
6464   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6465   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6466   case ISD::SDIVREM:
6467   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6468   case ISD::DYNAMIC_STACKALLOC:
6469     if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6470       return LowerDYNAMIC_STACKALLOC(Op, DAG);
6471     llvm_unreachable("Don't know how to custom lower this!");
6472   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6473   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6474   }
6475 }
6476
6477 /// ReplaceNodeResults - Replace the results of node with an illegal result
6478 /// type with new values built out of custom code.
6479 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6480                                            SmallVectorImpl<SDValue>&Results,
6481                                            SelectionDAG &DAG) const {
6482   SDValue Res;
6483   switch (N->getOpcode()) {
6484   default:
6485     llvm_unreachable("Don't know how to custom expand this!");
6486   case ISD::READ_REGISTER:
6487     ExpandREAD_REGISTER(N, Results, DAG);
6488     break;
6489   case ISD::BITCAST:
6490     Res = ExpandBITCAST(N, DAG);
6491     break;
6492   case ISD::SRL:
6493   case ISD::SRA:
6494     Res = Expand64BitShift(N, DAG, Subtarget);
6495     break;
6496   case ISD::READCYCLECOUNTER:
6497     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6498     return;
6499   }
6500   if (Res.getNode())
6501     Results.push_back(Res);
6502 }
6503
6504 //===----------------------------------------------------------------------===//
6505 //                           ARM Scheduler Hooks
6506 //===----------------------------------------------------------------------===//
6507
6508 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6509 /// registers the function context.
6510 void ARMTargetLowering::
6511 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6512                        MachineBasicBlock *DispatchBB, int FI) const {
6513   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6514   DebugLoc dl = MI->getDebugLoc();
6515   MachineFunction *MF = MBB->getParent();
6516   MachineRegisterInfo *MRI = &MF->getRegInfo();
6517   MachineConstantPool *MCP = MF->getConstantPool();
6518   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6519   const Function *F = MF->getFunction();
6520
6521   bool isThumb = Subtarget->isThumb();
6522   bool isThumb2 = Subtarget->isThumb2();
6523
6524   unsigned PCLabelId = AFI->createPICLabelUId();
6525   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6526   ARMConstantPoolValue *CPV =
6527     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6528   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6529
6530   const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
6531                                            : &ARM::GPRRegClass;
6532
6533   // Grab constant pool and fixed stack memory operands.
6534   MachineMemOperand *CPMMO =
6535     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6536                              MachineMemOperand::MOLoad, 4, 4);
6537
6538   MachineMemOperand *FIMMOSt =
6539     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6540                              MachineMemOperand::MOStore, 4, 4);
6541
6542   // Load the address of the dispatch MBB into the jump buffer.
6543   if (isThumb2) {
6544     // Incoming value: jbuf
6545     //   ldr.n  r5, LCPI1_1
6546     //   orr    r5, r5, #1
6547     //   add    r5, pc
6548     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6549     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6550     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6551                    .addConstantPoolIndex(CPI)
6552                    .addMemOperand(CPMMO));
6553     // Set the low bit because of thumb mode.
6554     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6555     AddDefaultCC(
6556       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6557                      .addReg(NewVReg1, RegState::Kill)
6558                      .addImm(0x01)));
6559     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6560     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6561       .addReg(NewVReg2, RegState::Kill)
6562       .addImm(PCLabelId);
6563     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6564                    .addReg(NewVReg3, RegState::Kill)
6565                    .addFrameIndex(FI)
6566                    .addImm(36)  // &jbuf[1] :: pc
6567                    .addMemOperand(FIMMOSt));
6568   } else if (isThumb) {
6569     // Incoming value: jbuf
6570     //   ldr.n  r1, LCPI1_4
6571     //   add    r1, pc
6572     //   mov    r2, #1
6573     //   orrs   r1, r2
6574     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6575     //   str    r1, [r2]
6576     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6577     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6578                    .addConstantPoolIndex(CPI)
6579                    .addMemOperand(CPMMO));
6580     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6581     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6582       .addReg(NewVReg1, RegState::Kill)
6583       .addImm(PCLabelId);
6584     // Set the low bit because of thumb mode.
6585     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6586     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6587                    .addReg(ARM::CPSR, RegState::Define)
6588                    .addImm(1));
6589     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6590     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6591                    .addReg(ARM::CPSR, RegState::Define)
6592                    .addReg(NewVReg2, RegState::Kill)
6593                    .addReg(NewVReg3, RegState::Kill));
6594     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6595     BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
6596             .addFrameIndex(FI)
6597             .addImm(36); // &jbuf[1] :: pc
6598     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6599                    .addReg(NewVReg4, RegState::Kill)
6600                    .addReg(NewVReg5, RegState::Kill)
6601                    .addImm(0)
6602                    .addMemOperand(FIMMOSt));
6603   } else {
6604     // Incoming value: jbuf
6605     //   ldr  r1, LCPI1_1
6606     //   add  r1, pc, r1
6607     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6608     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6609     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6610                    .addConstantPoolIndex(CPI)
6611                    .addImm(0)
6612                    .addMemOperand(CPMMO));
6613     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6614     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6615                    .addReg(NewVReg1, RegState::Kill)
6616                    .addImm(PCLabelId));
6617     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6618                    .addReg(NewVReg2, RegState::Kill)
6619                    .addFrameIndex(FI)
6620                    .addImm(36)  // &jbuf[1] :: pc
6621                    .addMemOperand(FIMMOSt));
6622   }
6623 }
6624
6625 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr *MI,
6626                                               MachineBasicBlock *MBB) const {
6627   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6628   DebugLoc dl = MI->getDebugLoc();
6629   MachineFunction *MF = MBB->getParent();
6630   MachineRegisterInfo *MRI = &MF->getRegInfo();
6631   MachineFrameInfo *MFI = MF->getFrameInfo();
6632   int FI = MFI->getFunctionContextIndex();
6633
6634   const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
6635                                                         : &ARM::GPRnopcRegClass;
6636
6637   // Get a mapping of the call site numbers to all of the landing pads they're
6638   // associated with.
6639   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6640   unsigned MaxCSNum = 0;
6641   MachineModuleInfo &MMI = MF->getMMI();
6642   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6643        ++BB) {
6644     if (!BB->isLandingPad()) continue;
6645
6646     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6647     // pad.
6648     for (MachineBasicBlock::iterator
6649            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6650       if (!II->isEHLabel()) continue;
6651
6652       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6653       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6654
6655       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6656       for (SmallVectorImpl<unsigned>::iterator
6657              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6658            CSI != CSE; ++CSI) {
6659         CallSiteNumToLPad[*CSI].push_back(BB);
6660         MaxCSNum = std::max(MaxCSNum, *CSI);
6661       }
6662       break;
6663     }
6664   }
6665
6666   // Get an ordered list of the machine basic blocks for the jump table.
6667   std::vector<MachineBasicBlock*> LPadList;
6668   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6669   LPadList.reserve(CallSiteNumToLPad.size());
6670   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6671     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6672     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6673            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6674       LPadList.push_back(*II);
6675       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6676     }
6677   }
6678
6679   assert(!LPadList.empty() &&
6680          "No landing pad destinations for the dispatch jump table!");
6681
6682   // Create the jump table and associated information.
6683   MachineJumpTableInfo *JTI =
6684     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6685   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6686   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6687
6688   // Create the MBBs for the dispatch code.
6689
6690   // Shove the dispatch's address into the return slot in the function context.
6691   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6692   DispatchBB->setIsLandingPad();
6693
6694   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6695   unsigned trap_opcode;
6696   if (Subtarget->isThumb())
6697     trap_opcode = ARM::tTRAP;
6698   else
6699     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6700
6701   BuildMI(TrapBB, dl, TII->get(trap_opcode));
6702   DispatchBB->addSuccessor(TrapBB);
6703
6704   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6705   DispatchBB->addSuccessor(DispContBB);
6706
6707   // Insert and MBBs.
6708   MF->insert(MF->end(), DispatchBB);
6709   MF->insert(MF->end(), DispContBB);
6710   MF->insert(MF->end(), TrapBB);
6711
6712   // Insert code into the entry block that creates and registers the function
6713   // context.
6714   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6715
6716   MachineMemOperand *FIMMOLd =
6717     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6718                              MachineMemOperand::MOLoad |
6719                              MachineMemOperand::MOVolatile, 4, 4);
6720
6721   MachineInstrBuilder MIB;
6722   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6723
6724   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6725   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6726
6727   // Add a register mask with no preserved registers.  This results in all
6728   // registers being marked as clobbered.
6729   MIB.addRegMask(RI.getNoPreservedMask());
6730
6731   unsigned NumLPads = LPadList.size();
6732   if (Subtarget->isThumb2()) {
6733     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6734     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6735                    .addFrameIndex(FI)
6736                    .addImm(4)
6737                    .addMemOperand(FIMMOLd));
6738
6739     if (NumLPads < 256) {
6740       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6741                      .addReg(NewVReg1)
6742                      .addImm(LPadList.size()));
6743     } else {
6744       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6745       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6746                      .addImm(NumLPads & 0xFFFF));
6747
6748       unsigned VReg2 = VReg1;
6749       if ((NumLPads & 0xFFFF0000) != 0) {
6750         VReg2 = MRI->createVirtualRegister(TRC);
6751         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6752                        .addReg(VReg1)
6753                        .addImm(NumLPads >> 16));
6754       }
6755
6756       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6757                      .addReg(NewVReg1)
6758                      .addReg(VReg2));
6759     }
6760
6761     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6762       .addMBB(TrapBB)
6763       .addImm(ARMCC::HI)
6764       .addReg(ARM::CPSR);
6765
6766     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6767     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6768                    .addJumpTableIndex(MJTI));
6769
6770     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6771     AddDefaultCC(
6772       AddDefaultPred(
6773         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6774         .addReg(NewVReg3, RegState::Kill)
6775         .addReg(NewVReg1)
6776         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6777
6778     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6779       .addReg(NewVReg4, RegState::Kill)
6780       .addReg(NewVReg1)
6781       .addJumpTableIndex(MJTI);
6782   } else if (Subtarget->isThumb()) {
6783     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6784     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6785                    .addFrameIndex(FI)
6786                    .addImm(1)
6787                    .addMemOperand(FIMMOLd));
6788
6789     if (NumLPads < 256) {
6790       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6791                      .addReg(NewVReg1)
6792                      .addImm(NumLPads));
6793     } else {
6794       MachineConstantPool *ConstantPool = MF->getConstantPool();
6795       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6796       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6797
6798       // MachineConstantPool wants an explicit alignment.
6799       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6800       if (Align == 0)
6801         Align = getDataLayout()->getTypeAllocSize(C->getType());
6802       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6803
6804       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6805       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6806                      .addReg(VReg1, RegState::Define)
6807                      .addConstantPoolIndex(Idx));
6808       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6809                      .addReg(NewVReg1)
6810                      .addReg(VReg1));
6811     }
6812
6813     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6814       .addMBB(TrapBB)
6815       .addImm(ARMCC::HI)
6816       .addReg(ARM::CPSR);
6817
6818     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6819     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6820                    .addReg(ARM::CPSR, RegState::Define)
6821                    .addReg(NewVReg1)
6822                    .addImm(2));
6823
6824     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6825     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6826                    .addJumpTableIndex(MJTI));
6827
6828     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6829     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6830                    .addReg(ARM::CPSR, RegState::Define)
6831                    .addReg(NewVReg2, RegState::Kill)
6832                    .addReg(NewVReg3));
6833
6834     MachineMemOperand *JTMMOLd =
6835       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6836                                MachineMemOperand::MOLoad, 4, 4);
6837
6838     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6839     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6840                    .addReg(NewVReg4, RegState::Kill)
6841                    .addImm(0)
6842                    .addMemOperand(JTMMOLd));
6843
6844     unsigned NewVReg6 = NewVReg5;
6845     if (RelocM == Reloc::PIC_) {
6846       NewVReg6 = MRI->createVirtualRegister(TRC);
6847       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6848                      .addReg(ARM::CPSR, RegState::Define)
6849                      .addReg(NewVReg5, RegState::Kill)
6850                      .addReg(NewVReg3));
6851     }
6852
6853     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6854       .addReg(NewVReg6, RegState::Kill)
6855       .addJumpTableIndex(MJTI);
6856   } else {
6857     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6858     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6859                    .addFrameIndex(FI)
6860                    .addImm(4)
6861                    .addMemOperand(FIMMOLd));
6862
6863     if (NumLPads < 256) {
6864       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6865                      .addReg(NewVReg1)
6866                      .addImm(NumLPads));
6867     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6868       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6869       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6870                      .addImm(NumLPads & 0xFFFF));
6871
6872       unsigned VReg2 = VReg1;
6873       if ((NumLPads & 0xFFFF0000) != 0) {
6874         VReg2 = MRI->createVirtualRegister(TRC);
6875         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6876                        .addReg(VReg1)
6877                        .addImm(NumLPads >> 16));
6878       }
6879
6880       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6881                      .addReg(NewVReg1)
6882                      .addReg(VReg2));
6883     } else {
6884       MachineConstantPool *ConstantPool = MF->getConstantPool();
6885       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6886       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6887
6888       // MachineConstantPool wants an explicit alignment.
6889       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6890       if (Align == 0)
6891         Align = getDataLayout()->getTypeAllocSize(C->getType());
6892       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6893
6894       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6895       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6896                      .addReg(VReg1, RegState::Define)
6897                      .addConstantPoolIndex(Idx)
6898                      .addImm(0));
6899       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6900                      .addReg(NewVReg1)
6901                      .addReg(VReg1, RegState::Kill));
6902     }
6903
6904     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6905       .addMBB(TrapBB)
6906       .addImm(ARMCC::HI)
6907       .addReg(ARM::CPSR);
6908
6909     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6910     AddDefaultCC(
6911       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6912                      .addReg(NewVReg1)
6913                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6914     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6915     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6916                    .addJumpTableIndex(MJTI));
6917
6918     MachineMemOperand *JTMMOLd =
6919       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6920                                MachineMemOperand::MOLoad, 4, 4);
6921     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6922     AddDefaultPred(
6923       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6924       .addReg(NewVReg3, RegState::Kill)
6925       .addReg(NewVReg4)
6926       .addImm(0)
6927       .addMemOperand(JTMMOLd));
6928
6929     if (RelocM == Reloc::PIC_) {
6930       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6931         .addReg(NewVReg5, RegState::Kill)
6932         .addReg(NewVReg4)
6933         .addJumpTableIndex(MJTI);
6934     } else {
6935       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6936         .addReg(NewVReg5, RegState::Kill)
6937         .addJumpTableIndex(MJTI);
6938     }
6939   }
6940
6941   // Add the jump table entries as successors to the MBB.
6942   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6943   for (std::vector<MachineBasicBlock*>::iterator
6944          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6945     MachineBasicBlock *CurMBB = *I;
6946     if (SeenMBBs.insert(CurMBB).second)
6947       DispContBB->addSuccessor(CurMBB);
6948   }
6949
6950   // N.B. the order the invoke BBs are processed in doesn't matter here.
6951   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
6952   SmallVector<MachineBasicBlock*, 64> MBBLPads;
6953   for (MachineBasicBlock *BB : InvokeBBs) {
6954
6955     // Remove the landing pad successor from the invoke block and replace it
6956     // with the new dispatch block.
6957     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6958                                                   BB->succ_end());
6959     while (!Successors.empty()) {
6960       MachineBasicBlock *SMBB = Successors.pop_back_val();
6961       if (SMBB->isLandingPad()) {
6962         BB->removeSuccessor(SMBB);
6963         MBBLPads.push_back(SMBB);
6964       }
6965     }
6966
6967     BB->addSuccessor(DispatchBB);
6968
6969     // Find the invoke call and mark all of the callee-saved registers as
6970     // 'implicit defined' so that they're spilled. This prevents code from
6971     // moving instructions to before the EH block, where they will never be
6972     // executed.
6973     for (MachineBasicBlock::reverse_iterator
6974            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6975       if (!II->isCall()) continue;
6976
6977       DenseMap<unsigned, bool> DefRegs;
6978       for (MachineInstr::mop_iterator
6979              OI = II->operands_begin(), OE = II->operands_end();
6980            OI != OE; ++OI) {
6981         if (!OI->isReg()) continue;
6982         DefRegs[OI->getReg()] = true;
6983       }
6984
6985       MachineInstrBuilder MIB(*MF, &*II);
6986
6987       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6988         unsigned Reg = SavedRegs[i];
6989         if (Subtarget->isThumb2() &&
6990             !ARM::tGPRRegClass.contains(Reg) &&
6991             !ARM::hGPRRegClass.contains(Reg))
6992           continue;
6993         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6994           continue;
6995         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6996           continue;
6997         if (!DefRegs[Reg])
6998           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6999       }
7000
7001       break;
7002     }
7003   }
7004
7005   // Mark all former landing pads as non-landing pads. The dispatch is the only
7006   // landing pad now.
7007   for (SmallVectorImpl<MachineBasicBlock*>::iterator
7008          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7009     (*I)->setIsLandingPad(false);
7010
7011   // The instruction is gone now.
7012   MI->eraseFromParent();
7013 }
7014
7015 static
7016 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7017   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7018        E = MBB->succ_end(); I != E; ++I)
7019     if (*I != Succ)
7020       return *I;
7021   llvm_unreachable("Expecting a BB with two successors!");
7022 }
7023
7024 /// Return the load opcode for a given load size. If load size >= 8,
7025 /// neon opcode will be returned.
7026 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7027   if (LdSize >= 8)
7028     return LdSize == 16 ? ARM::VLD1q32wb_fixed
7029                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7030   if (IsThumb1)
7031     return LdSize == 4 ? ARM::tLDRi
7032                        : LdSize == 2 ? ARM::tLDRHi
7033                                      : LdSize == 1 ? ARM::tLDRBi : 0;
7034   if (IsThumb2)
7035     return LdSize == 4 ? ARM::t2LDR_POST
7036                        : LdSize == 2 ? ARM::t2LDRH_POST
7037                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7038   return LdSize == 4 ? ARM::LDR_POST_IMM
7039                      : LdSize == 2 ? ARM::LDRH_POST
7040                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7041 }
7042
7043 /// Return the store opcode for a given store size. If store size >= 8,
7044 /// neon opcode will be returned.
7045 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7046   if (StSize >= 8)
7047     return StSize == 16 ? ARM::VST1q32wb_fixed
7048                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7049   if (IsThumb1)
7050     return StSize == 4 ? ARM::tSTRi
7051                        : StSize == 2 ? ARM::tSTRHi
7052                                      : StSize == 1 ? ARM::tSTRBi : 0;
7053   if (IsThumb2)
7054     return StSize == 4 ? ARM::t2STR_POST
7055                        : StSize == 2 ? ARM::t2STRH_POST
7056                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
7057   return StSize == 4 ? ARM::STR_POST_IMM
7058                      : StSize == 2 ? ARM::STRH_POST
7059                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7060 }
7061
7062 /// Emit a post-increment load operation with given size. The instructions
7063 /// will be added to BB at Pos.
7064 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7065                        const TargetInstrInfo *TII, DebugLoc dl,
7066                        unsigned LdSize, unsigned Data, unsigned AddrIn,
7067                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7068   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7069   assert(LdOpc != 0 && "Should have a load opcode");
7070   if (LdSize >= 8) {
7071     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7072                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7073                        .addImm(0));
7074   } else if (IsThumb1) {
7075     // load + update AddrIn
7076     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7077                        .addReg(AddrIn).addImm(0));
7078     MachineInstrBuilder MIB =
7079         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7080     MIB = AddDefaultT1CC(MIB);
7081     MIB.addReg(AddrIn).addImm(LdSize);
7082     AddDefaultPred(MIB);
7083   } else if (IsThumb2) {
7084     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7085                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7086                        .addImm(LdSize));
7087   } else { // arm
7088     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7089                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7090                        .addReg(0).addImm(LdSize));
7091   }
7092 }
7093
7094 /// Emit a post-increment store operation with given size. The instructions
7095 /// will be added to BB at Pos.
7096 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7097                        const TargetInstrInfo *TII, DebugLoc dl,
7098                        unsigned StSize, unsigned Data, unsigned AddrIn,
7099                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7100   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7101   assert(StOpc != 0 && "Should have a store opcode");
7102   if (StSize >= 8) {
7103     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7104                        .addReg(AddrIn).addImm(0).addReg(Data));
7105   } else if (IsThumb1) {
7106     // store + update AddrIn
7107     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7108                        .addReg(AddrIn).addImm(0));
7109     MachineInstrBuilder MIB =
7110         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7111     MIB = AddDefaultT1CC(MIB);
7112     MIB.addReg(AddrIn).addImm(StSize);
7113     AddDefaultPred(MIB);
7114   } else if (IsThumb2) {
7115     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7116                        .addReg(Data).addReg(AddrIn).addImm(StSize));
7117   } else { // arm
7118     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7119                        .addReg(Data).addReg(AddrIn).addReg(0)
7120                        .addImm(StSize));
7121   }
7122 }
7123
7124 MachineBasicBlock *
7125 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7126                                    MachineBasicBlock *BB) const {
7127   // This pseudo instruction has 3 operands: dst, src, size
7128   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7129   // Otherwise, we will generate unrolled scalar copies.
7130   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7131   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7132   MachineFunction::iterator It = BB;
7133   ++It;
7134
7135   unsigned dest = MI->getOperand(0).getReg();
7136   unsigned src = MI->getOperand(1).getReg();
7137   unsigned SizeVal = MI->getOperand(2).getImm();
7138   unsigned Align = MI->getOperand(3).getImm();
7139   DebugLoc dl = MI->getDebugLoc();
7140
7141   MachineFunction *MF = BB->getParent();
7142   MachineRegisterInfo &MRI = MF->getRegInfo();
7143   unsigned UnitSize = 0;
7144   const TargetRegisterClass *TRC = nullptr;
7145   const TargetRegisterClass *VecTRC = nullptr;
7146
7147   bool IsThumb1 = Subtarget->isThumb1Only();
7148   bool IsThumb2 = Subtarget->isThumb2();
7149
7150   if (Align & 1) {
7151     UnitSize = 1;
7152   } else if (Align & 2) {
7153     UnitSize = 2;
7154   } else {
7155     // Check whether we can use NEON instructions.
7156     if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
7157         Subtarget->hasNEON()) {
7158       if ((Align % 16 == 0) && SizeVal >= 16)
7159         UnitSize = 16;
7160       else if ((Align % 8 == 0) && SizeVal >= 8)
7161         UnitSize = 8;
7162     }
7163     // Can't use NEON instructions.
7164     if (UnitSize == 0)
7165       UnitSize = 4;
7166   }
7167
7168   // Select the correct opcode and register class for unit size load/store
7169   bool IsNeon = UnitSize >= 8;
7170   TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
7171   if (IsNeon)
7172     VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
7173                             : UnitSize == 8 ? &ARM::DPRRegClass
7174                                             : nullptr;
7175
7176   unsigned BytesLeft = SizeVal % UnitSize;
7177   unsigned LoopSize = SizeVal - BytesLeft;
7178
7179   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7180     // Use LDR and STR to copy.
7181     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7182     // [destOut] = STR_POST(scratch, destIn, UnitSize)
7183     unsigned srcIn = src;
7184     unsigned destIn = dest;
7185     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7186       unsigned srcOut = MRI.createVirtualRegister(TRC);
7187       unsigned destOut = MRI.createVirtualRegister(TRC);
7188       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7189       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7190                  IsThumb1, IsThumb2);
7191       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7192                  IsThumb1, IsThumb2);
7193       srcIn = srcOut;
7194       destIn = destOut;
7195     }
7196
7197     // Handle the leftover bytes with LDRB and STRB.
7198     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7199     // [destOut] = STRB_POST(scratch, destIn, 1)
7200     for (unsigned i = 0; i < BytesLeft; i++) {
7201       unsigned srcOut = MRI.createVirtualRegister(TRC);
7202       unsigned destOut = MRI.createVirtualRegister(TRC);
7203       unsigned scratch = MRI.createVirtualRegister(TRC);
7204       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7205                  IsThumb1, IsThumb2);
7206       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7207                  IsThumb1, IsThumb2);
7208       srcIn = srcOut;
7209       destIn = destOut;
7210     }
7211     MI->eraseFromParent();   // The instruction is gone now.
7212     return BB;
7213   }
7214
7215   // Expand the pseudo op to a loop.
7216   // thisMBB:
7217   //   ...
7218   //   movw varEnd, # --> with thumb2
7219   //   movt varEnd, #
7220   //   ldrcp varEnd, idx --> without thumb2
7221   //   fallthrough --> loopMBB
7222   // loopMBB:
7223   //   PHI varPhi, varEnd, varLoop
7224   //   PHI srcPhi, src, srcLoop
7225   //   PHI destPhi, dst, destLoop
7226   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7227   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7228   //   subs varLoop, varPhi, #UnitSize
7229   //   bne loopMBB
7230   //   fallthrough --> exitMBB
7231   // exitMBB:
7232   //   epilogue to handle left-over bytes
7233   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7234   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7235   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7236   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7237   MF->insert(It, loopMBB);
7238   MF->insert(It, exitMBB);
7239
7240   // Transfer the remainder of BB and its successor edges to exitMBB.
7241   exitMBB->splice(exitMBB->begin(), BB,
7242                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7243   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7244
7245   // Load an immediate to varEnd.
7246   unsigned varEnd = MRI.createVirtualRegister(TRC);
7247   if (Subtarget->useMovt(*MF)) {
7248     unsigned Vtmp = varEnd;
7249     if ((LoopSize & 0xFFFF0000) != 0)
7250       Vtmp = MRI.createVirtualRegister(TRC);
7251     AddDefaultPred(BuildMI(BB, dl,
7252                            TII->get(IsThumb2 ? ARM::t2MOVi16 : ARM::MOVi16),
7253                            Vtmp).addImm(LoopSize & 0xFFFF));
7254
7255     if ((LoopSize & 0xFFFF0000) != 0)
7256       AddDefaultPred(BuildMI(BB, dl,
7257                              TII->get(IsThumb2 ? ARM::t2MOVTi16 : ARM::MOVTi16),
7258                              varEnd)
7259                          .addReg(Vtmp)
7260                          .addImm(LoopSize >> 16));
7261   } else {
7262     MachineConstantPool *ConstantPool = MF->getConstantPool();
7263     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7264     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7265
7266     // MachineConstantPool wants an explicit alignment.
7267     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7268     if (Align == 0)
7269       Align = getDataLayout()->getTypeAllocSize(C->getType());
7270     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7271
7272     if (IsThumb1)
7273       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7274           varEnd, RegState::Define).addConstantPoolIndex(Idx));
7275     else
7276       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7277           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7278   }
7279   BB->addSuccessor(loopMBB);
7280
7281   // Generate the loop body:
7282   //   varPhi = PHI(varLoop, varEnd)
7283   //   srcPhi = PHI(srcLoop, src)
7284   //   destPhi = PHI(destLoop, dst)
7285   MachineBasicBlock *entryBB = BB;
7286   BB = loopMBB;
7287   unsigned varLoop = MRI.createVirtualRegister(TRC);
7288   unsigned varPhi = MRI.createVirtualRegister(TRC);
7289   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7290   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7291   unsigned destLoop = MRI.createVirtualRegister(TRC);
7292   unsigned destPhi = MRI.createVirtualRegister(TRC);
7293
7294   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7295     .addReg(varLoop).addMBB(loopMBB)
7296     .addReg(varEnd).addMBB(entryBB);
7297   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7298     .addReg(srcLoop).addMBB(loopMBB)
7299     .addReg(src).addMBB(entryBB);
7300   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7301     .addReg(destLoop).addMBB(loopMBB)
7302     .addReg(dest).addMBB(entryBB);
7303
7304   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7305   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7306   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7307   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7308              IsThumb1, IsThumb2);
7309   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7310              IsThumb1, IsThumb2);
7311
7312   // Decrement loop variable by UnitSize.
7313   if (IsThumb1) {
7314     MachineInstrBuilder MIB =
7315         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7316     MIB = AddDefaultT1CC(MIB);
7317     MIB.addReg(varPhi).addImm(UnitSize);
7318     AddDefaultPred(MIB);
7319   } else {
7320     MachineInstrBuilder MIB =
7321         BuildMI(*BB, BB->end(), dl,
7322                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7323     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7324     MIB->getOperand(5).setReg(ARM::CPSR);
7325     MIB->getOperand(5).setIsDef(true);
7326   }
7327   BuildMI(*BB, BB->end(), dl,
7328           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7329       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7330
7331   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7332   BB->addSuccessor(loopMBB);
7333   BB->addSuccessor(exitMBB);
7334
7335   // Add epilogue to handle BytesLeft.
7336   BB = exitMBB;
7337   MachineInstr *StartOfExit = exitMBB->begin();
7338
7339   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7340   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7341   unsigned srcIn = srcLoop;
7342   unsigned destIn = destLoop;
7343   for (unsigned i = 0; i < BytesLeft; i++) {
7344     unsigned srcOut = MRI.createVirtualRegister(TRC);
7345     unsigned destOut = MRI.createVirtualRegister(TRC);
7346     unsigned scratch = MRI.createVirtualRegister(TRC);
7347     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7348                IsThumb1, IsThumb2);
7349     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7350                IsThumb1, IsThumb2);
7351     srcIn = srcOut;
7352     destIn = destOut;
7353   }
7354
7355   MI->eraseFromParent();   // The instruction is gone now.
7356   return BB;
7357 }
7358
7359 MachineBasicBlock *
7360 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7361                                        MachineBasicBlock *MBB) const {
7362   const TargetMachine &TM = getTargetMachine();
7363   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
7364   DebugLoc DL = MI->getDebugLoc();
7365
7366   assert(Subtarget->isTargetWindows() &&
7367          "__chkstk is only supported on Windows");
7368   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7369
7370   // __chkstk takes the number of words to allocate on the stack in R4, and
7371   // returns the stack adjustment in number of bytes in R4.  This will not
7372   // clober any other registers (other than the obvious lr).
7373   //
7374   // Although, technically, IP should be considered a register which may be
7375   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
7376   // thumb-2 environment, so there is no interworking required.  As a result, we
7377   // do not expect a veneer to be emitted by the linker, clobbering IP.
7378   //
7379   // Each module receives its own copy of __chkstk, so no import thunk is
7380   // required, again, ensuring that IP is not clobbered.
7381   //
7382   // Finally, although some linkers may theoretically provide a trampoline for
7383   // out of range calls (which is quite common due to a 32M range limitation of
7384   // branches for Thumb), we can generate the long-call version via
7385   // -mcmodel=large, alleviating the need for the trampoline which may clobber
7386   // IP.
7387
7388   switch (TM.getCodeModel()) {
7389   case CodeModel::Small:
7390   case CodeModel::Medium:
7391   case CodeModel::Default:
7392   case CodeModel::Kernel:
7393     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7394       .addImm((unsigned)ARMCC::AL).addReg(0)
7395       .addExternalSymbol("__chkstk")
7396       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7397       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7398       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7399     break;
7400   case CodeModel::Large:
7401   case CodeModel::JITDefault: {
7402     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7403     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7404
7405     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7406       .addExternalSymbol("__chkstk");
7407     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7408       .addImm((unsigned)ARMCC::AL).addReg(0)
7409       .addReg(Reg, RegState::Kill)
7410       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7411       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7412       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7413     break;
7414   }
7415   }
7416
7417   AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7418                                       ARM::SP)
7419                               .addReg(ARM::SP).addReg(ARM::R4)));
7420
7421   MI->eraseFromParent();
7422   return MBB;
7423 }
7424
7425 MachineBasicBlock *
7426 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7427                                                MachineBasicBlock *BB) const {
7428   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7429   DebugLoc dl = MI->getDebugLoc();
7430   bool isThumb2 = Subtarget->isThumb2();
7431   switch (MI->getOpcode()) {
7432   default: {
7433     MI->dump();
7434     llvm_unreachable("Unexpected instr type to insert");
7435   }
7436   // The Thumb2 pre-indexed stores have the same MI operands, they just
7437   // define them differently in the .td files from the isel patterns, so
7438   // they need pseudos.
7439   case ARM::t2STR_preidx:
7440     MI->setDesc(TII->get(ARM::t2STR_PRE));
7441     return BB;
7442   case ARM::t2STRB_preidx:
7443     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7444     return BB;
7445   case ARM::t2STRH_preidx:
7446     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7447     return BB;
7448
7449   case ARM::STRi_preidx:
7450   case ARM::STRBi_preidx: {
7451     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7452       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7453     // Decode the offset.
7454     unsigned Offset = MI->getOperand(4).getImm();
7455     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7456     Offset = ARM_AM::getAM2Offset(Offset);
7457     if (isSub)
7458       Offset = -Offset;
7459
7460     MachineMemOperand *MMO = *MI->memoperands_begin();
7461     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7462       .addOperand(MI->getOperand(0))  // Rn_wb
7463       .addOperand(MI->getOperand(1))  // Rt
7464       .addOperand(MI->getOperand(2))  // Rn
7465       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7466       .addOperand(MI->getOperand(5))  // pred
7467       .addOperand(MI->getOperand(6))
7468       .addMemOperand(MMO);
7469     MI->eraseFromParent();
7470     return BB;
7471   }
7472   case ARM::STRr_preidx:
7473   case ARM::STRBr_preidx:
7474   case ARM::STRH_preidx: {
7475     unsigned NewOpc;
7476     switch (MI->getOpcode()) {
7477     default: llvm_unreachable("unexpected opcode!");
7478     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7479     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7480     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7481     }
7482     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7483     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7484       MIB.addOperand(MI->getOperand(i));
7485     MI->eraseFromParent();
7486     return BB;
7487   }
7488
7489   case ARM::tMOVCCr_pseudo: {
7490     // To "insert" a SELECT_CC instruction, we actually have to insert the
7491     // diamond control-flow pattern.  The incoming instruction knows the
7492     // destination vreg to set, the condition code register to branch on, the
7493     // true/false values to select between, and a branch opcode to use.
7494     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7495     MachineFunction::iterator It = BB;
7496     ++It;
7497
7498     //  thisMBB:
7499     //  ...
7500     //   TrueVal = ...
7501     //   cmpTY ccX, r1, r2
7502     //   bCC copy1MBB
7503     //   fallthrough --> copy0MBB
7504     MachineBasicBlock *thisMBB  = BB;
7505     MachineFunction *F = BB->getParent();
7506     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7507     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7508     F->insert(It, copy0MBB);
7509     F->insert(It, sinkMBB);
7510
7511     // Transfer the remainder of BB and its successor edges to sinkMBB.
7512     sinkMBB->splice(sinkMBB->begin(), BB,
7513                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7514     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7515
7516     BB->addSuccessor(copy0MBB);
7517     BB->addSuccessor(sinkMBB);
7518
7519     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7520       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7521
7522     //  copy0MBB:
7523     //   %FalseValue = ...
7524     //   # fallthrough to sinkMBB
7525     BB = copy0MBB;
7526
7527     // Update machine-CFG edges
7528     BB->addSuccessor(sinkMBB);
7529
7530     //  sinkMBB:
7531     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7532     //  ...
7533     BB = sinkMBB;
7534     BuildMI(*BB, BB->begin(), dl,
7535             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7536       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7537       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7538
7539     MI->eraseFromParent();   // The pseudo instruction is gone now.
7540     return BB;
7541   }
7542
7543   case ARM::BCCi64:
7544   case ARM::BCCZi64: {
7545     // If there is an unconditional branch to the other successor, remove it.
7546     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7547
7548     // Compare both parts that make up the double comparison separately for
7549     // equality.
7550     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7551
7552     unsigned LHS1 = MI->getOperand(1).getReg();
7553     unsigned LHS2 = MI->getOperand(2).getReg();
7554     if (RHSisZero) {
7555       AddDefaultPred(BuildMI(BB, dl,
7556                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7557                      .addReg(LHS1).addImm(0));
7558       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7559         .addReg(LHS2).addImm(0)
7560         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7561     } else {
7562       unsigned RHS1 = MI->getOperand(3).getReg();
7563       unsigned RHS2 = MI->getOperand(4).getReg();
7564       AddDefaultPred(BuildMI(BB, dl,
7565                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7566                      .addReg(LHS1).addReg(RHS1));
7567       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7568         .addReg(LHS2).addReg(RHS2)
7569         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7570     }
7571
7572     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7573     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7574     if (MI->getOperand(0).getImm() == ARMCC::NE)
7575       std::swap(destMBB, exitMBB);
7576
7577     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7578       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7579     if (isThumb2)
7580       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7581     else
7582       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7583
7584     MI->eraseFromParent();   // The pseudo instruction is gone now.
7585     return BB;
7586   }
7587
7588   case ARM::Int_eh_sjlj_setjmp:
7589   case ARM::Int_eh_sjlj_setjmp_nofp:
7590   case ARM::tInt_eh_sjlj_setjmp:
7591   case ARM::t2Int_eh_sjlj_setjmp:
7592   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7593     EmitSjLjDispatchBlock(MI, BB);
7594     return BB;
7595
7596   case ARM::ABS:
7597   case ARM::t2ABS: {
7598     // To insert an ABS instruction, we have to insert the
7599     // diamond control-flow pattern.  The incoming instruction knows the
7600     // source vreg to test against 0, the destination vreg to set,
7601     // the condition code register to branch on, the
7602     // true/false values to select between, and a branch opcode to use.
7603     // It transforms
7604     //     V1 = ABS V0
7605     // into
7606     //     V2 = MOVS V0
7607     //     BCC                      (branch to SinkBB if V0 >= 0)
7608     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7609     //     SinkBB: V1 = PHI(V2, V3)
7610     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7611     MachineFunction::iterator BBI = BB;
7612     ++BBI;
7613     MachineFunction *Fn = BB->getParent();
7614     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7615     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7616     Fn->insert(BBI, RSBBB);
7617     Fn->insert(BBI, SinkBB);
7618
7619     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7620     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7621     bool ABSSrcKIll = MI->getOperand(1).isKill();
7622     bool isThumb2 = Subtarget->isThumb2();
7623     MachineRegisterInfo &MRI = Fn->getRegInfo();
7624     // In Thumb mode S must not be specified if source register is the SP or
7625     // PC and if destination register is the SP, so restrict register class
7626     unsigned NewRsbDstReg =
7627       MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
7628
7629     // Transfer the remainder of BB and its successor edges to sinkMBB.
7630     SinkBB->splice(SinkBB->begin(), BB,
7631                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
7632     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7633
7634     BB->addSuccessor(RSBBB);
7635     BB->addSuccessor(SinkBB);
7636
7637     // fall through to SinkMBB
7638     RSBBB->addSuccessor(SinkBB);
7639
7640     // insert a cmp at the end of BB
7641     AddDefaultPred(BuildMI(BB, dl,
7642                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7643                    .addReg(ABSSrcReg).addImm(0));
7644
7645     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7646     BuildMI(BB, dl,
7647       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7648       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7649
7650     // insert rsbri in RSBBB
7651     // Note: BCC and rsbri will be converted into predicated rsbmi
7652     // by if-conversion pass
7653     BuildMI(*RSBBB, RSBBB->begin(), dl,
7654       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7655       .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
7656       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7657
7658     // insert PHI in SinkBB,
7659     // reuse ABSDstReg to not change uses of ABS instruction
7660     BuildMI(*SinkBB, SinkBB->begin(), dl,
7661       TII->get(ARM::PHI), ABSDstReg)
7662       .addReg(NewRsbDstReg).addMBB(RSBBB)
7663       .addReg(ABSSrcReg).addMBB(BB);
7664
7665     // remove ABS instruction
7666     MI->eraseFromParent();
7667
7668     // return last added BB
7669     return SinkBB;
7670   }
7671   case ARM::COPY_STRUCT_BYVAL_I32:
7672     ++NumLoopByVals;
7673     return EmitStructByval(MI, BB);
7674   case ARM::WIN__CHKSTK:
7675     return EmitLowered__chkstk(MI, BB);
7676   }
7677 }
7678
7679 /// \brief Lowers MCOPY to either LDMIA/STMIA or LDMIA_UPD/STMID_UPD depending
7680 /// on whether the result is used. This is done as a post-isel lowering instead
7681 /// of as a custom inserter because we need the use list from the SDNode.
7682 static void LowerMCOPY(const ARMSubtarget *Subtarget, MachineInstr *MI,
7683                        SDNode *Node) {
7684   bool isThumb1 = Subtarget->isThumb1Only();
7685   bool isThumb2 = Subtarget->isThumb2();
7686   const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
7687
7688   DebugLoc dl = MI->getDebugLoc();
7689   MachineBasicBlock *BB = MI->getParent();
7690   MachineFunction *MF = BB->getParent();
7691   MachineRegisterInfo &MRI = MF->getRegInfo();
7692
7693   MachineInstrBuilder LD, ST;
7694   if (isThumb1 || Node->hasAnyUseOfValue(1)) {
7695     LD = BuildMI(*BB, MI, dl, TII->get(isThumb2 ? ARM::t2LDMIA_UPD
7696                                                 : isThumb1 ? ARM::tLDMIA_UPD
7697                                                            : ARM::LDMIA_UPD))
7698              .addOperand(MI->getOperand(1));
7699   } else {
7700     LD = BuildMI(*BB, MI, dl, TII->get(isThumb2 ? ARM::t2LDMIA : ARM::LDMIA));
7701   }
7702
7703   if (isThumb1 || Node->hasAnyUseOfValue(0)) {
7704     ST = BuildMI(*BB, MI, dl, TII->get(isThumb2 ? ARM::t2STMIA_UPD
7705                                                 : isThumb1 ? ARM::tSTMIA_UPD
7706                                                            : ARM::STMIA_UPD))
7707              .addOperand(MI->getOperand(0));
7708   } else {
7709     ST = BuildMI(*BB, MI, dl, TII->get(isThumb2 ? ARM::t2STMIA : ARM::STMIA));
7710   }
7711
7712   LD.addOperand(MI->getOperand(3)).addImm(ARMCC::AL).addReg(0);
7713   ST.addOperand(MI->getOperand(2)).addImm(ARMCC::AL).addReg(0);
7714
7715   for (unsigned I = 0; I != MI->getOperand(4).getImm(); ++I) {
7716     unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass
7717                                                          : &ARM::GPRRegClass);
7718     LD.addReg(TmpReg, RegState::Define);
7719     ST.addReg(TmpReg, RegState::Kill);
7720   }
7721
7722   MI->eraseFromParent();
7723 }
7724
7725 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7726                                                       SDNode *Node) const {
7727   if (MI->getOpcode() == ARM::MCOPY) {
7728     LowerMCOPY(Subtarget, MI, Node);
7729     return;
7730   }
7731
7732   const MCInstrDesc *MCID = &MI->getDesc();
7733   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7734   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7735   // operand is still set to noreg. If needed, set the optional operand's
7736   // register to CPSR, and remove the redundant implicit def.
7737   //
7738   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7739
7740   // Rename pseudo opcodes.
7741   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7742   if (NewOpc) {
7743     const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
7744     MCID = &TII->get(NewOpc);
7745
7746     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7747            "converted opcode should be the same except for cc_out");
7748
7749     MI->setDesc(*MCID);
7750
7751     // Add the optional cc_out operand
7752     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7753   }
7754   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7755
7756   // Any ARM instruction that sets the 's' bit should specify an optional
7757   // "cc_out" operand in the last operand position.
7758   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7759     assert(!NewOpc && "Optional cc_out operand required");
7760     return;
7761   }
7762   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7763   // since we already have an optional CPSR def.
7764   bool definesCPSR = false;
7765   bool deadCPSR = false;
7766   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7767        i != e; ++i) {
7768     const MachineOperand &MO = MI->getOperand(i);
7769     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7770       definesCPSR = true;
7771       if (MO.isDead())
7772         deadCPSR = true;
7773       MI->RemoveOperand(i);
7774       break;
7775     }
7776   }
7777   if (!definesCPSR) {
7778     assert(!NewOpc && "Optional cc_out operand required");
7779     return;
7780   }
7781   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7782   if (deadCPSR) {
7783     assert(!MI->getOperand(ccOutIdx).getReg() &&
7784            "expect uninitialized optional cc_out operand");
7785     return;
7786   }
7787
7788   // If this instruction was defined with an optional CPSR def and its dag node
7789   // had a live implicit CPSR def, then activate the optional CPSR def.
7790   MachineOperand &MO = MI->getOperand(ccOutIdx);
7791   MO.setReg(ARM::CPSR);
7792   MO.setIsDef(true);
7793 }
7794
7795 //===----------------------------------------------------------------------===//
7796 //                           ARM Optimization Hooks
7797 //===----------------------------------------------------------------------===//
7798
7799 // Helper function that checks if N is a null or all ones constant.
7800 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7801   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7802   if (!C)
7803     return false;
7804   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7805 }
7806
7807 // Return true if N is conditionally 0 or all ones.
7808 // Detects these expressions where cc is an i1 value:
7809 //
7810 //   (select cc 0, y)   [AllOnes=0]
7811 //   (select cc y, 0)   [AllOnes=0]
7812 //   (zext cc)          [AllOnes=0]
7813 //   (sext cc)          [AllOnes=0/1]
7814 //   (select cc -1, y)  [AllOnes=1]
7815 //   (select cc y, -1)  [AllOnes=1]
7816 //
7817 // Invert is set when N is the null/all ones constant when CC is false.
7818 // OtherOp is set to the alternative value of N.
7819 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7820                                        SDValue &CC, bool &Invert,
7821                                        SDValue &OtherOp,
7822                                        SelectionDAG &DAG) {
7823   switch (N->getOpcode()) {
7824   default: return false;
7825   case ISD::SELECT: {
7826     CC = N->getOperand(0);
7827     SDValue N1 = N->getOperand(1);
7828     SDValue N2 = N->getOperand(2);
7829     if (isZeroOrAllOnes(N1, AllOnes)) {
7830       Invert = false;
7831       OtherOp = N2;
7832       return true;
7833     }
7834     if (isZeroOrAllOnes(N2, AllOnes)) {
7835       Invert = true;
7836       OtherOp = N1;
7837       return true;
7838     }
7839     return false;
7840   }
7841   case ISD::ZERO_EXTEND:
7842     // (zext cc) can never be the all ones value.
7843     if (AllOnes)
7844       return false;
7845     // Fall through.
7846   case ISD::SIGN_EXTEND: {
7847     SDLoc dl(N);
7848     EVT VT = N->getValueType(0);
7849     CC = N->getOperand(0);
7850     if (CC.getValueType() != MVT::i1)
7851       return false;
7852     Invert = !AllOnes;
7853     if (AllOnes)
7854       // When looking for an AllOnes constant, N is an sext, and the 'other'
7855       // value is 0.
7856       OtherOp = DAG.getConstant(0, dl, VT);
7857     else if (N->getOpcode() == ISD::ZERO_EXTEND)
7858       // When looking for a 0 constant, N can be zext or sext.
7859       OtherOp = DAG.getConstant(1, dl, VT);
7860     else
7861       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
7862                                 VT);
7863     return true;
7864   }
7865   }
7866 }
7867
7868 // Combine a constant select operand into its use:
7869 //
7870 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
7871 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
7872 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
7873 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
7874 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
7875 //
7876 // The transform is rejected if the select doesn't have a constant operand that
7877 // is null, or all ones when AllOnes is set.
7878 //
7879 // Also recognize sext/zext from i1:
7880 //
7881 //   (add (zext cc), x) -> (select cc (add x, 1), x)
7882 //   (add (sext cc), x) -> (select cc (add x, -1), x)
7883 //
7884 // These transformations eventually create predicated instructions.
7885 //
7886 // @param N       The node to transform.
7887 // @param Slct    The N operand that is a select.
7888 // @param OtherOp The other N operand (x above).
7889 // @param DCI     Context.
7890 // @param AllOnes Require the select constant to be all ones instead of null.
7891 // @returns The new node, or SDValue() on failure.
7892 static
7893 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7894                             TargetLowering::DAGCombinerInfo &DCI,
7895                             bool AllOnes = false) {
7896   SelectionDAG &DAG = DCI.DAG;
7897   EVT VT = N->getValueType(0);
7898   SDValue NonConstantVal;
7899   SDValue CCOp;
7900   bool SwapSelectOps;
7901   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7902                                   NonConstantVal, DAG))
7903     return SDValue();
7904
7905   // Slct is now know to be the desired identity constant when CC is true.
7906   SDValue TrueVal = OtherOp;
7907   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7908                                  OtherOp, NonConstantVal);
7909   // Unless SwapSelectOps says CC should be false.
7910   if (SwapSelectOps)
7911     std::swap(TrueVal, FalseVal);
7912
7913   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7914                      CCOp, TrueVal, FalseVal);
7915 }
7916
7917 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7918 static
7919 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7920                                        TargetLowering::DAGCombinerInfo &DCI) {
7921   SDValue N0 = N->getOperand(0);
7922   SDValue N1 = N->getOperand(1);
7923   if (N0.getNode()->hasOneUse()) {
7924     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7925     if (Result.getNode())
7926       return Result;
7927   }
7928   if (N1.getNode()->hasOneUse()) {
7929     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7930     if (Result.getNode())
7931       return Result;
7932   }
7933   return SDValue();
7934 }
7935
7936 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7937 // (only after legalization).
7938 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7939                                  TargetLowering::DAGCombinerInfo &DCI,
7940                                  const ARMSubtarget *Subtarget) {
7941
7942   // Only perform optimization if after legalize, and if NEON is available. We
7943   // also expected both operands to be BUILD_VECTORs.
7944   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7945       || N0.getOpcode() != ISD::BUILD_VECTOR
7946       || N1.getOpcode() != ISD::BUILD_VECTOR)
7947     return SDValue();
7948
7949   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7950   EVT VT = N->getValueType(0);
7951   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7952     return SDValue();
7953
7954   // Check that the vector operands are of the right form.
7955   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7956   // operands, where N is the size of the formed vector.
7957   // Each EXTRACT_VECTOR should have the same input vector and odd or even
7958   // index such that we have a pair wise add pattern.
7959
7960   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7961   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7962     return SDValue();
7963   SDValue Vec = N0->getOperand(0)->getOperand(0);
7964   SDNode *V = Vec.getNode();
7965   unsigned nextIndex = 0;
7966
7967   // For each operands to the ADD which are BUILD_VECTORs,
7968   // check to see if each of their operands are an EXTRACT_VECTOR with
7969   // the same vector and appropriate index.
7970   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7971     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7972         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7973
7974       SDValue ExtVec0 = N0->getOperand(i);
7975       SDValue ExtVec1 = N1->getOperand(i);
7976
7977       // First operand is the vector, verify its the same.
7978       if (V != ExtVec0->getOperand(0).getNode() ||
7979           V != ExtVec1->getOperand(0).getNode())
7980         return SDValue();
7981
7982       // Second is the constant, verify its correct.
7983       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7984       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7985
7986       // For the constant, we want to see all the even or all the odd.
7987       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7988           || C1->getZExtValue() != nextIndex+1)
7989         return SDValue();
7990
7991       // Increment index.
7992       nextIndex+=2;
7993     } else
7994       return SDValue();
7995   }
7996
7997   // Create VPADDL node.
7998   SelectionDAG &DAG = DCI.DAG;
7999   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8000
8001   SDLoc dl(N);
8002
8003   // Build operand list.
8004   SmallVector<SDValue, 8> Ops;
8005   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
8006                                 TLI.getPointerTy()));
8007
8008   // Input is the vector.
8009   Ops.push_back(Vec);
8010
8011   // Get widened type and narrowed type.
8012   MVT widenType;
8013   unsigned numElem = VT.getVectorNumElements();
8014   
8015   EVT inputLaneType = Vec.getValueType().getVectorElementType();
8016   switch (inputLaneType.getSimpleVT().SimpleTy) {
8017     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
8018     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
8019     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
8020     default:
8021       llvm_unreachable("Invalid vector element type for padd optimization.");
8022   }
8023
8024   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
8025   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
8026   return DAG.getNode(ExtOp, dl, VT, tmp);
8027 }
8028
8029 static SDValue findMUL_LOHI(SDValue V) {
8030   if (V->getOpcode() == ISD::UMUL_LOHI ||
8031       V->getOpcode() == ISD::SMUL_LOHI)
8032     return V;
8033   return SDValue();
8034 }
8035
8036 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
8037                                      TargetLowering::DAGCombinerInfo &DCI,
8038                                      const ARMSubtarget *Subtarget) {
8039
8040   if (Subtarget->isThumb1Only()) return SDValue();
8041
8042   // Only perform the checks after legalize when the pattern is available.
8043   if (DCI.isBeforeLegalize()) return SDValue();
8044
8045   // Look for multiply add opportunities.
8046   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8047   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8048   // a glue link from the first add to the second add.
8049   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8050   // a S/UMLAL instruction.
8051   //                  UMUL_LOHI
8052   //                 / :lo    \ :hi
8053   //                /          \          [no multiline comment]
8054   //    loAdd ->  ADDE         |
8055   //                 \ :glue  /
8056   //                  \      /
8057   //                    ADDC   <- hiAdd
8058   //
8059   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8060   SDValue AddcOp0 = AddcNode->getOperand(0);
8061   SDValue AddcOp1 = AddcNode->getOperand(1);
8062
8063   // Check if the two operands are from the same mul_lohi node.
8064   if (AddcOp0.getNode() == AddcOp1.getNode())
8065     return SDValue();
8066
8067   assert(AddcNode->getNumValues() == 2 &&
8068          AddcNode->getValueType(0) == MVT::i32 &&
8069          "Expect ADDC with two result values. First: i32");
8070
8071   // Check that we have a glued ADDC node.
8072   if (AddcNode->getValueType(1) != MVT::Glue)
8073     return SDValue();
8074
8075   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8076   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8077       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8078       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8079       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8080     return SDValue();
8081
8082   // Look for the glued ADDE.
8083   SDNode* AddeNode = AddcNode->getGluedUser();
8084   if (!AddeNode)
8085     return SDValue();
8086
8087   // Make sure it is really an ADDE.
8088   if (AddeNode->getOpcode() != ISD::ADDE)
8089     return SDValue();
8090
8091   assert(AddeNode->getNumOperands() == 3 &&
8092          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8093          "ADDE node has the wrong inputs");
8094
8095   // Check for the triangle shape.
8096   SDValue AddeOp0 = AddeNode->getOperand(0);
8097   SDValue AddeOp1 = AddeNode->getOperand(1);
8098
8099   // Make sure that the ADDE operands are not coming from the same node.
8100   if (AddeOp0.getNode() == AddeOp1.getNode())
8101     return SDValue();
8102
8103   // Find the MUL_LOHI node walking up ADDE's operands.
8104   bool IsLeftOperandMUL = false;
8105   SDValue MULOp = findMUL_LOHI(AddeOp0);
8106   if (MULOp == SDValue())
8107    MULOp = findMUL_LOHI(AddeOp1);
8108   else
8109     IsLeftOperandMUL = true;
8110   if (MULOp == SDValue())
8111     return SDValue();
8112
8113   // Figure out the right opcode.
8114   unsigned Opc = MULOp->getOpcode();
8115   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8116
8117   // Figure out the high and low input values to the MLAL node.
8118   SDValue* HiAdd = nullptr;
8119   SDValue* LoMul = nullptr;
8120   SDValue* LowAdd = nullptr;
8121
8122   // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
8123   if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
8124     return SDValue();
8125
8126   if (IsLeftOperandMUL)
8127     HiAdd = &AddeOp1;
8128   else
8129     HiAdd = &AddeOp0;
8130
8131
8132   // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
8133   // whose low result is fed to the ADDC we are checking.
8134
8135   if (AddcOp0 == MULOp.getValue(0)) {
8136     LoMul = &AddcOp0;
8137     LowAdd = &AddcOp1;
8138   }
8139   if (AddcOp1 == MULOp.getValue(0)) {
8140     LoMul = &AddcOp1;
8141     LowAdd = &AddcOp0;
8142   }
8143
8144   if (!LoMul)
8145     return SDValue();
8146
8147   // Create the merged node.
8148   SelectionDAG &DAG = DCI.DAG;
8149
8150   // Build operand list.
8151   SmallVector<SDValue, 8> Ops;
8152   Ops.push_back(LoMul->getOperand(0));
8153   Ops.push_back(LoMul->getOperand(1));
8154   Ops.push_back(*LowAdd);
8155   Ops.push_back(*HiAdd);
8156
8157   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
8158                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
8159
8160   // Replace the ADDs' nodes uses by the MLA node's values.
8161   SDValue HiMLALResult(MLALNode.getNode(), 1);
8162   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8163
8164   SDValue LoMLALResult(MLALNode.getNode(), 0);
8165   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8166
8167   // Return original node to notify the driver to stop replacing.
8168   SDValue resNode(AddcNode, 0);
8169   return resNode;
8170 }
8171
8172 /// PerformADDCCombine - Target-specific dag combine transform from
8173 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8174 static SDValue PerformADDCCombine(SDNode *N,
8175                                  TargetLowering::DAGCombinerInfo &DCI,
8176                                  const ARMSubtarget *Subtarget) {
8177
8178   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8179
8180 }
8181
8182 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8183 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
8184 /// called with the default operands, and if that fails, with commuted
8185 /// operands.
8186 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8187                                           TargetLowering::DAGCombinerInfo &DCI,
8188                                           const ARMSubtarget *Subtarget){
8189
8190   // Attempt to create vpaddl for this add.
8191   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8192   if (Result.getNode())
8193     return Result;
8194
8195   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8196   if (N0.getNode()->hasOneUse()) {
8197     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8198     if (Result.getNode()) return Result;
8199   }
8200   return SDValue();
8201 }
8202
8203 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8204 ///
8205 static SDValue PerformADDCombine(SDNode *N,
8206                                  TargetLowering::DAGCombinerInfo &DCI,
8207                                  const ARMSubtarget *Subtarget) {
8208   SDValue N0 = N->getOperand(0);
8209   SDValue N1 = N->getOperand(1);
8210
8211   // First try with the default operand order.
8212   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8213   if (Result.getNode())
8214     return Result;
8215
8216   // If that didn't work, try again with the operands commuted.
8217   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8218 }
8219
8220 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8221 ///
8222 static SDValue PerformSUBCombine(SDNode *N,
8223                                  TargetLowering::DAGCombinerInfo &DCI) {
8224   SDValue N0 = N->getOperand(0);
8225   SDValue N1 = N->getOperand(1);
8226
8227   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8228   if (N1.getNode()->hasOneUse()) {
8229     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8230     if (Result.getNode()) return Result;
8231   }
8232
8233   return SDValue();
8234 }
8235
8236 /// PerformVMULCombine
8237 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8238 /// special multiplier accumulator forwarding.
8239 ///   vmul d3, d0, d2
8240 ///   vmla d3, d1, d2
8241 /// is faster than
8242 ///   vadd d3, d0, d1
8243 ///   vmul d3, d3, d2
8244 //  However, for (A + B) * (A + B),
8245 //    vadd d2, d0, d1
8246 //    vmul d3, d0, d2
8247 //    vmla d3, d1, d2
8248 //  is slower than
8249 //    vadd d2, d0, d1
8250 //    vmul d3, d2, d2
8251 static SDValue PerformVMULCombine(SDNode *N,
8252                                   TargetLowering::DAGCombinerInfo &DCI,
8253                                   const ARMSubtarget *Subtarget) {
8254   if (!Subtarget->hasVMLxForwarding())
8255     return SDValue();
8256
8257   SelectionDAG &DAG = DCI.DAG;
8258   SDValue N0 = N->getOperand(0);
8259   SDValue N1 = N->getOperand(1);
8260   unsigned Opcode = N0.getOpcode();
8261   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8262       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8263     Opcode = N1.getOpcode();
8264     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8265         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8266       return SDValue();
8267     std::swap(N0, N1);
8268   }
8269
8270   if (N0 == N1)
8271     return SDValue();
8272
8273   EVT VT = N->getValueType(0);
8274   SDLoc DL(N);
8275   SDValue N00 = N0->getOperand(0);
8276   SDValue N01 = N0->getOperand(1);
8277   return DAG.getNode(Opcode, DL, VT,
8278                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8279                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8280 }
8281
8282 static SDValue PerformMULCombine(SDNode *N,
8283                                  TargetLowering::DAGCombinerInfo &DCI,
8284                                  const ARMSubtarget *Subtarget) {
8285   SelectionDAG &DAG = DCI.DAG;
8286
8287   if (Subtarget->isThumb1Only())
8288     return SDValue();
8289
8290   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8291     return SDValue();
8292
8293   EVT VT = N->getValueType(0);
8294   if (VT.is64BitVector() || VT.is128BitVector())
8295     return PerformVMULCombine(N, DCI, Subtarget);
8296   if (VT != MVT::i32)
8297     return SDValue();
8298
8299   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8300   if (!C)
8301     return SDValue();
8302
8303   int64_t MulAmt = C->getSExtValue();
8304   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8305
8306   ShiftAmt = ShiftAmt & (32 - 1);
8307   SDValue V = N->getOperand(0);
8308   SDLoc DL(N);
8309
8310   SDValue Res;
8311   MulAmt >>= ShiftAmt;
8312
8313   if (MulAmt >= 0) {
8314     if (isPowerOf2_32(MulAmt - 1)) {
8315       // (mul x, 2^N + 1) => (add (shl x, N), x)
8316       Res = DAG.getNode(ISD::ADD, DL, VT,
8317                         V,
8318                         DAG.getNode(ISD::SHL, DL, VT,
8319                                     V,
8320                                     DAG.getConstant(Log2_32(MulAmt - 1), DL,
8321                                                     MVT::i32)));
8322     } else if (isPowerOf2_32(MulAmt + 1)) {
8323       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8324       Res = DAG.getNode(ISD::SUB, DL, VT,
8325                         DAG.getNode(ISD::SHL, DL, VT,
8326                                     V,
8327                                     DAG.getConstant(Log2_32(MulAmt + 1), DL,
8328                                                     MVT::i32)),
8329                         V);
8330     } else
8331       return SDValue();
8332   } else {
8333     uint64_t MulAmtAbs = -MulAmt;
8334     if (isPowerOf2_32(MulAmtAbs + 1)) {
8335       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8336       Res = DAG.getNode(ISD::SUB, DL, VT,
8337                         V,
8338                         DAG.getNode(ISD::SHL, DL, VT,
8339                                     V,
8340                                     DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
8341                                                     MVT::i32)));
8342     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8343       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8344       Res = DAG.getNode(ISD::ADD, DL, VT,
8345                         V,
8346                         DAG.getNode(ISD::SHL, DL, VT,
8347                                     V,
8348                                     DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
8349                                                     MVT::i32)));
8350       Res = DAG.getNode(ISD::SUB, DL, VT,
8351                         DAG.getConstant(0, DL, MVT::i32), Res);
8352
8353     } else
8354       return SDValue();
8355   }
8356
8357   if (ShiftAmt != 0)
8358     Res = DAG.getNode(ISD::SHL, DL, VT,
8359                       Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
8360
8361   // Do not add new nodes to DAG combiner worklist.
8362   DCI.CombineTo(N, Res, false);
8363   return SDValue();
8364 }
8365
8366 static SDValue PerformANDCombine(SDNode *N,
8367                                  TargetLowering::DAGCombinerInfo &DCI,
8368                                  const ARMSubtarget *Subtarget) {
8369
8370   // Attempt to use immediate-form VBIC
8371   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8372   SDLoc dl(N);
8373   EVT VT = N->getValueType(0);
8374   SelectionDAG &DAG = DCI.DAG;
8375
8376   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8377     return SDValue();
8378
8379   APInt SplatBits, SplatUndef;
8380   unsigned SplatBitSize;
8381   bool HasAnyUndefs;
8382   if (BVN &&
8383       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8384     if (SplatBitSize <= 64) {
8385       EVT VbicVT;
8386       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8387                                       SplatUndef.getZExtValue(), SplatBitSize,
8388                                       DAG, dl, VbicVT, VT.is128BitVector(),
8389                                       OtherModImm);
8390       if (Val.getNode()) {
8391         SDValue Input =
8392           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8393         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8394         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8395       }
8396     }
8397   }
8398
8399   if (!Subtarget->isThumb1Only()) {
8400     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8401     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8402     if (Result.getNode())
8403       return Result;
8404   }
8405
8406   return SDValue();
8407 }
8408
8409 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8410 static SDValue PerformORCombine(SDNode *N,
8411                                 TargetLowering::DAGCombinerInfo &DCI,
8412                                 const ARMSubtarget *Subtarget) {
8413   // Attempt to use immediate-form VORR
8414   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8415   SDLoc dl(N);
8416   EVT VT = N->getValueType(0);
8417   SelectionDAG &DAG = DCI.DAG;
8418
8419   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8420     return SDValue();
8421
8422   APInt SplatBits, SplatUndef;
8423   unsigned SplatBitSize;
8424   bool HasAnyUndefs;
8425   if (BVN && Subtarget->hasNEON() &&
8426       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8427     if (SplatBitSize <= 64) {
8428       EVT VorrVT;
8429       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8430                                       SplatUndef.getZExtValue(), SplatBitSize,
8431                                       DAG, dl, VorrVT, VT.is128BitVector(),
8432                                       OtherModImm);
8433       if (Val.getNode()) {
8434         SDValue Input =
8435           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8436         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8437         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8438       }
8439     }
8440   }
8441
8442   if (!Subtarget->isThumb1Only()) {
8443     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8444     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8445     if (Result.getNode())
8446       return Result;
8447   }
8448
8449   // The code below optimizes (or (and X, Y), Z).
8450   // The AND operand needs to have a single user to make these optimizations
8451   // profitable.
8452   SDValue N0 = N->getOperand(0);
8453   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8454     return SDValue();
8455   SDValue N1 = N->getOperand(1);
8456
8457   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8458   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8459       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8460     APInt SplatUndef;
8461     unsigned SplatBitSize;
8462     bool HasAnyUndefs;
8463
8464     APInt SplatBits0, SplatBits1;
8465     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8466     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8467     // Ensure that the second operand of both ands are constants
8468     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8469                                       HasAnyUndefs) && !HasAnyUndefs) {
8470         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8471                                           HasAnyUndefs) && !HasAnyUndefs) {
8472             // Ensure that the bit width of the constants are the same and that
8473             // the splat arguments are logical inverses as per the pattern we
8474             // are trying to simplify.
8475             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8476                 SplatBits0 == ~SplatBits1) {
8477                 // Canonicalize the vector type to make instruction selection
8478                 // simpler.
8479                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8480                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8481                                              N0->getOperand(1),
8482                                              N0->getOperand(0),
8483                                              N1->getOperand(0));
8484                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8485             }
8486         }
8487     }
8488   }
8489
8490   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8491   // reasonable.
8492
8493   // BFI is only available on V6T2+
8494   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8495     return SDValue();
8496
8497   SDLoc DL(N);
8498   // 1) or (and A, mask), val => ARMbfi A, val, mask
8499   //      iff (val & mask) == val
8500   //
8501   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8502   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8503   //          && mask == ~mask2
8504   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8505   //          && ~mask == mask2
8506   //  (i.e., copy a bitfield value into another bitfield of the same width)
8507
8508   if (VT != MVT::i32)
8509     return SDValue();
8510
8511   SDValue N00 = N0.getOperand(0);
8512
8513   // The value and the mask need to be constants so we can verify this is
8514   // actually a bitfield set. If the mask is 0xffff, we can do better
8515   // via a movt instruction, so don't use BFI in that case.
8516   SDValue MaskOp = N0.getOperand(1);
8517   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8518   if (!MaskC)
8519     return SDValue();
8520   unsigned Mask = MaskC->getZExtValue();
8521   if (Mask == 0xffff)
8522     return SDValue();
8523   SDValue Res;
8524   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8525   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8526   if (N1C) {
8527     unsigned Val = N1C->getZExtValue();
8528     if ((Val & ~Mask) != Val)
8529       return SDValue();
8530
8531     if (ARM::isBitFieldInvertedMask(Mask)) {
8532       Val >>= countTrailingZeros(~Mask);
8533
8534       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8535                         DAG.getConstant(Val, DL, MVT::i32),
8536                         DAG.getConstant(Mask, DL, MVT::i32));
8537
8538       // Do not add new nodes to DAG combiner worklist.
8539       DCI.CombineTo(N, Res, false);
8540       return SDValue();
8541     }
8542   } else if (N1.getOpcode() == ISD::AND) {
8543     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8544     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8545     if (!N11C)
8546       return SDValue();
8547     unsigned Mask2 = N11C->getZExtValue();
8548
8549     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8550     // as is to match.
8551     if (ARM::isBitFieldInvertedMask(Mask) &&
8552         (Mask == ~Mask2)) {
8553       // The pack halfword instruction works better for masks that fit it,
8554       // so use that when it's available.
8555       if (Subtarget->hasT2ExtractPack() &&
8556           (Mask == 0xffff || Mask == 0xffff0000))
8557         return SDValue();
8558       // 2a
8559       unsigned amt = countTrailingZeros(Mask2);
8560       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8561                         DAG.getConstant(amt, DL, MVT::i32));
8562       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8563                         DAG.getConstant(Mask, DL, MVT::i32));
8564       // Do not add new nodes to DAG combiner worklist.
8565       DCI.CombineTo(N, Res, false);
8566       return SDValue();
8567     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8568                (~Mask == Mask2)) {
8569       // The pack halfword instruction works better for masks that fit it,
8570       // so use that when it's available.
8571       if (Subtarget->hasT2ExtractPack() &&
8572           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8573         return SDValue();
8574       // 2b
8575       unsigned lsb = countTrailingZeros(Mask);
8576       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8577                         DAG.getConstant(lsb, DL, MVT::i32));
8578       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8579                         DAG.getConstant(Mask2, DL, MVT::i32));
8580       // Do not add new nodes to DAG combiner worklist.
8581       DCI.CombineTo(N, Res, false);
8582       return SDValue();
8583     }
8584   }
8585
8586   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8587       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8588       ARM::isBitFieldInvertedMask(~Mask)) {
8589     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8590     // where lsb(mask) == #shamt and masked bits of B are known zero.
8591     SDValue ShAmt = N00.getOperand(1);
8592     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8593     unsigned LSB = countTrailingZeros(Mask);
8594     if (ShAmtC != LSB)
8595       return SDValue();
8596
8597     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8598                       DAG.getConstant(~Mask, DL, MVT::i32));
8599
8600     // Do not add new nodes to DAG combiner worklist.
8601     DCI.CombineTo(N, Res, false);
8602   }
8603
8604   return SDValue();
8605 }
8606
8607 static SDValue PerformXORCombine(SDNode *N,
8608                                  TargetLowering::DAGCombinerInfo &DCI,
8609                                  const ARMSubtarget *Subtarget) {
8610   EVT VT = N->getValueType(0);
8611   SelectionDAG &DAG = DCI.DAG;
8612
8613   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8614     return SDValue();
8615
8616   if (!Subtarget->isThumb1Only()) {
8617     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8618     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8619     if (Result.getNode())
8620       return Result;
8621   }
8622
8623   return SDValue();
8624 }
8625
8626 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8627 /// the bits being cleared by the AND are not demanded by the BFI.
8628 static SDValue PerformBFICombine(SDNode *N,
8629                                  TargetLowering::DAGCombinerInfo &DCI) {
8630   SDValue N1 = N->getOperand(1);
8631   if (N1.getOpcode() == ISD::AND) {
8632     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8633     if (!N11C)
8634       return SDValue();
8635     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8636     unsigned LSB = countTrailingZeros(~InvMask);
8637     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8638     assert(Width <
8639                static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
8640            "undefined behavior");
8641     unsigned Mask = (1u << Width) - 1;
8642     unsigned Mask2 = N11C->getZExtValue();
8643     if ((Mask & (~Mask2)) == 0)
8644       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8645                              N->getOperand(0), N1.getOperand(0),
8646                              N->getOperand(2));
8647   }
8648   return SDValue();
8649 }
8650
8651 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8652 /// ARMISD::VMOVRRD.
8653 static SDValue PerformVMOVRRDCombine(SDNode *N,
8654                                      TargetLowering::DAGCombinerInfo &DCI,
8655                                      const ARMSubtarget *Subtarget) {
8656   // vmovrrd(vmovdrr x, y) -> x,y
8657   SDValue InDouble = N->getOperand(0);
8658   if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
8659     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8660
8661   // vmovrrd(load f64) -> (load i32), (load i32)
8662   SDNode *InNode = InDouble.getNode();
8663   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8664       InNode->getValueType(0) == MVT::f64 &&
8665       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8666       !cast<LoadSDNode>(InNode)->isVolatile()) {
8667     // TODO: Should this be done for non-FrameIndex operands?
8668     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8669
8670     SelectionDAG &DAG = DCI.DAG;
8671     SDLoc DL(LD);
8672     SDValue BasePtr = LD->getBasePtr();
8673     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8674                                  LD->getPointerInfo(), LD->isVolatile(),
8675                                  LD->isNonTemporal(), LD->isInvariant(),
8676                                  LD->getAlignment());
8677
8678     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8679                                     DAG.getConstant(4, DL, MVT::i32));
8680     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8681                                  LD->getPointerInfo(), LD->isVolatile(),
8682                                  LD->isNonTemporal(), LD->isInvariant(),
8683                                  std::min(4U, LD->getAlignment() / 2));
8684
8685     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8686     if (DCI.DAG.getTargetLoweringInfo().isBigEndian())
8687       std::swap (NewLD1, NewLD2);
8688     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8689     return Result;
8690   }
8691
8692   return SDValue();
8693 }
8694
8695 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8696 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8697 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8698   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8699   SDValue Op0 = N->getOperand(0);
8700   SDValue Op1 = N->getOperand(1);
8701   if (Op0.getOpcode() == ISD::BITCAST)
8702     Op0 = Op0.getOperand(0);
8703   if (Op1.getOpcode() == ISD::BITCAST)
8704     Op1 = Op1.getOperand(0);
8705   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8706       Op0.getNode() == Op1.getNode() &&
8707       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8708     return DAG.getNode(ISD::BITCAST, SDLoc(N),
8709                        N->getValueType(0), Op0.getOperand(0));
8710   return SDValue();
8711 }
8712
8713 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8714 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8715 /// i64 vector to have f64 elements, since the value can then be loaded
8716 /// directly into a VFP register.
8717 static bool hasNormalLoadOperand(SDNode *N) {
8718   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8719   for (unsigned i = 0; i < NumElts; ++i) {
8720     SDNode *Elt = N->getOperand(i).getNode();
8721     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8722       return true;
8723   }
8724   return false;
8725 }
8726
8727 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8728 /// ISD::BUILD_VECTOR.
8729 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8730                                           TargetLowering::DAGCombinerInfo &DCI,
8731                                           const ARMSubtarget *Subtarget) {
8732   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8733   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
8734   // into a pair of GPRs, which is fine when the value is used as a scalar,
8735   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8736   SelectionDAG &DAG = DCI.DAG;
8737   if (N->getNumOperands() == 2) {
8738     SDValue RV = PerformVMOVDRRCombine(N, DAG);
8739     if (RV.getNode())
8740       return RV;
8741   }
8742
8743   // Load i64 elements as f64 values so that type legalization does not split
8744   // them up into i32 values.
8745   EVT VT = N->getValueType(0);
8746   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8747     return SDValue();
8748   SDLoc dl(N);
8749   SmallVector<SDValue, 8> Ops;
8750   unsigned NumElts = VT.getVectorNumElements();
8751   for (unsigned i = 0; i < NumElts; ++i) {
8752     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8753     Ops.push_back(V);
8754     // Make the DAGCombiner fold the bitcast.
8755     DCI.AddToWorklist(V.getNode());
8756   }
8757   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8758   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8759   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8760 }
8761
8762 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8763 static SDValue
8764 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8765   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8766   // At that time, we may have inserted bitcasts from integer to float.
8767   // If these bitcasts have survived DAGCombine, change the lowering of this
8768   // BUILD_VECTOR in something more vector friendly, i.e., that does not
8769   // force to use floating point types.
8770
8771   // Make sure we can change the type of the vector.
8772   // This is possible iff:
8773   // 1. The vector is only used in a bitcast to a integer type. I.e.,
8774   //    1.1. Vector is used only once.
8775   //    1.2. Use is a bit convert to an integer type.
8776   // 2. The size of its operands are 32-bits (64-bits are not legal).
8777   EVT VT = N->getValueType(0);
8778   EVT EltVT = VT.getVectorElementType();
8779
8780   // Check 1.1. and 2.
8781   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8782     return SDValue();
8783
8784   // By construction, the input type must be float.
8785   assert(EltVT == MVT::f32 && "Unexpected type!");
8786
8787   // Check 1.2.
8788   SDNode *Use = *N->use_begin();
8789   if (Use->getOpcode() != ISD::BITCAST ||
8790       Use->getValueType(0).isFloatingPoint())
8791     return SDValue();
8792
8793   // Check profitability.
8794   // Model is, if more than half of the relevant operands are bitcast from
8795   // i32, turn the build_vector into a sequence of insert_vector_elt.
8796   // Relevant operands are everything that is not statically
8797   // (i.e., at compile time) bitcasted.
8798   unsigned NumOfBitCastedElts = 0;
8799   unsigned NumElts = VT.getVectorNumElements();
8800   unsigned NumOfRelevantElts = NumElts;
8801   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8802     SDValue Elt = N->getOperand(Idx);
8803     if (Elt->getOpcode() == ISD::BITCAST) {
8804       // Assume only bit cast to i32 will go away.
8805       if (Elt->getOperand(0).getValueType() == MVT::i32)
8806         ++NumOfBitCastedElts;
8807     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8808       // Constants are statically casted, thus do not count them as
8809       // relevant operands.
8810       --NumOfRelevantElts;
8811   }
8812
8813   // Check if more than half of the elements require a non-free bitcast.
8814   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8815     return SDValue();
8816
8817   SelectionDAG &DAG = DCI.DAG;
8818   // Create the new vector type.
8819   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8820   // Check if the type is legal.
8821   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8822   if (!TLI.isTypeLegal(VecVT))
8823     return SDValue();
8824
8825   // Combine:
8826   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8827   // => BITCAST INSERT_VECTOR_ELT
8828   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8829   //                      (BITCAST EN), N.
8830   SDValue Vec = DAG.getUNDEF(VecVT);
8831   SDLoc dl(N);
8832   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8833     SDValue V = N->getOperand(Idx);
8834     if (V.getOpcode() == ISD::UNDEF)
8835       continue;
8836     if (V.getOpcode() == ISD::BITCAST &&
8837         V->getOperand(0).getValueType() == MVT::i32)
8838       // Fold obvious case.
8839       V = V.getOperand(0);
8840     else {
8841       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
8842       // Make the DAGCombiner fold the bitcasts.
8843       DCI.AddToWorklist(V.getNode());
8844     }
8845     SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
8846     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8847   }
8848   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8849   // Make the DAGCombiner fold the bitcasts.
8850   DCI.AddToWorklist(Vec.getNode());
8851   return Vec;
8852 }
8853
8854 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8855 /// ISD::INSERT_VECTOR_ELT.
8856 static SDValue PerformInsertEltCombine(SDNode *N,
8857                                        TargetLowering::DAGCombinerInfo &DCI) {
8858   // Bitcast an i64 load inserted into a vector to f64.
8859   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8860   EVT VT = N->getValueType(0);
8861   SDNode *Elt = N->getOperand(1).getNode();
8862   if (VT.getVectorElementType() != MVT::i64 ||
8863       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8864     return SDValue();
8865
8866   SelectionDAG &DAG = DCI.DAG;
8867   SDLoc dl(N);
8868   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8869                                  VT.getVectorNumElements());
8870   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8871   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8872   // Make the DAGCombiner fold the bitcasts.
8873   DCI.AddToWorklist(Vec.getNode());
8874   DCI.AddToWorklist(V.getNode());
8875   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8876                                Vec, V, N->getOperand(2));
8877   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8878 }
8879
8880 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8881 /// ISD::VECTOR_SHUFFLE.
8882 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8883   // The LLVM shufflevector instruction does not require the shuffle mask
8884   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8885   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
8886   // operands do not match the mask length, they are extended by concatenating
8887   // them with undef vectors.  That is probably the right thing for other
8888   // targets, but for NEON it is better to concatenate two double-register
8889   // size vector operands into a single quad-register size vector.  Do that
8890   // transformation here:
8891   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
8892   //   shuffle(concat(v1, v2), undef)
8893   SDValue Op0 = N->getOperand(0);
8894   SDValue Op1 = N->getOperand(1);
8895   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8896       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8897       Op0.getNumOperands() != 2 ||
8898       Op1.getNumOperands() != 2)
8899     return SDValue();
8900   SDValue Concat0Op1 = Op0.getOperand(1);
8901   SDValue Concat1Op1 = Op1.getOperand(1);
8902   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8903       Concat1Op1.getOpcode() != ISD::UNDEF)
8904     return SDValue();
8905   // Skip the transformation if any of the types are illegal.
8906   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8907   EVT VT = N->getValueType(0);
8908   if (!TLI.isTypeLegal(VT) ||
8909       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8910       !TLI.isTypeLegal(Concat1Op1.getValueType()))
8911     return SDValue();
8912
8913   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
8914                                   Op0.getOperand(0), Op1.getOperand(0));
8915   // Translate the shuffle mask.
8916   SmallVector<int, 16> NewMask;
8917   unsigned NumElts = VT.getVectorNumElements();
8918   unsigned HalfElts = NumElts/2;
8919   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8920   for (unsigned n = 0; n < NumElts; ++n) {
8921     int MaskElt = SVN->getMaskElt(n);
8922     int NewElt = -1;
8923     if (MaskElt < (int)HalfElts)
8924       NewElt = MaskElt;
8925     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8926       NewElt = HalfElts + MaskElt - NumElts;
8927     NewMask.push_back(NewElt);
8928   }
8929   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
8930                               DAG.getUNDEF(VT), NewMask.data());
8931 }
8932
8933 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
8934 /// NEON load/store intrinsics, and generic vector load/stores, to merge
8935 /// base address updates.
8936 /// For generic load/stores, the memory type is assumed to be a vector.
8937 /// The caller is assumed to have checked legality.
8938 static SDValue CombineBaseUpdate(SDNode *N,
8939                                  TargetLowering::DAGCombinerInfo &DCI) {
8940   SelectionDAG &DAG = DCI.DAG;
8941   const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8942                             N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8943   const bool isStore = N->getOpcode() == ISD::STORE;
8944   const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
8945   SDValue Addr = N->getOperand(AddrOpIdx);
8946   MemSDNode *MemN = cast<MemSDNode>(N);
8947   SDLoc dl(N);
8948
8949   // Search for a use of the address operand that is an increment.
8950   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8951          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8952     SDNode *User = *UI;
8953     if (User->getOpcode() != ISD::ADD ||
8954         UI.getUse().getResNo() != Addr.getResNo())
8955       continue;
8956
8957     // Check that the add is independent of the load/store.  Otherwise, folding
8958     // it would create a cycle.
8959     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8960       continue;
8961
8962     // Find the new opcode for the updating load/store.
8963     bool isLoadOp = true;
8964     bool isLaneOp = false;
8965     unsigned NewOpc = 0;
8966     unsigned NumVecs = 0;
8967     if (isIntrinsic) {
8968       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8969       switch (IntNo) {
8970       default: llvm_unreachable("unexpected intrinsic for Neon base update");
8971       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
8972         NumVecs = 1; break;
8973       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
8974         NumVecs = 2; break;
8975       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
8976         NumVecs = 3; break;
8977       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
8978         NumVecs = 4; break;
8979       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8980         NumVecs = 2; isLaneOp = true; break;
8981       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8982         NumVecs = 3; isLaneOp = true; break;
8983       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8984         NumVecs = 4; isLaneOp = true; break;
8985       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
8986         NumVecs = 1; isLoadOp = false; break;
8987       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
8988         NumVecs = 2; isLoadOp = false; break;
8989       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
8990         NumVecs = 3; isLoadOp = false; break;
8991       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
8992         NumVecs = 4; isLoadOp = false; break;
8993       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8994         NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
8995       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8996         NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
8997       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8998         NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
8999       }
9000     } else {
9001       isLaneOp = true;
9002       switch (N->getOpcode()) {
9003       default: llvm_unreachable("unexpected opcode for Neon base update");
9004       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9005       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9006       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9007       case ISD::LOAD:       NewOpc = ARMISD::VLD1_UPD;
9008         NumVecs = 1; isLaneOp = false; break;
9009       case ISD::STORE:      NewOpc = ARMISD::VST1_UPD;
9010         NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
9011       }
9012     }
9013
9014     // Find the size of memory referenced by the load/store.
9015     EVT VecTy;
9016     if (isLoadOp) {
9017       VecTy = N->getValueType(0);
9018     } else if (isIntrinsic) {
9019       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9020     } else {
9021       assert(isStore && "Node has to be a load, a store, or an intrinsic!");
9022       VecTy = N->getOperand(1).getValueType();
9023     }
9024
9025     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9026     if (isLaneOp)
9027       NumBytes /= VecTy.getVectorNumElements();
9028
9029     // If the increment is a constant, it must match the memory ref size.
9030     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9031     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9032       uint64_t IncVal = CInc->getZExtValue();
9033       if (IncVal != NumBytes)
9034         continue;
9035     } else if (NumBytes >= 3 * 16) {
9036       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9037       // separate instructions that make it harder to use a non-constant update.
9038       continue;
9039     }
9040
9041     // OK, we found an ADD we can fold into the base update.
9042     // Now, create a _UPD node, taking care of not breaking alignment.
9043
9044     EVT AlignedVecTy = VecTy;
9045     unsigned Alignment = MemN->getAlignment();
9046
9047     // If this is a less-than-standard-aligned load/store, change the type to
9048     // match the standard alignment.
9049     // The alignment is overlooked when selecting _UPD variants; and it's
9050     // easier to introduce bitcasts here than fix that.
9051     // There are 3 ways to get to this base-update combine:
9052     // - intrinsics: they are assumed to be properly aligned (to the standard
9053     //   alignment of the memory type), so we don't need to do anything.
9054     // - ARMISD::VLDx nodes: they are only generated from the aforementioned
9055     //   intrinsics, so, likewise, there's nothing to do.
9056     // - generic load/store instructions: the alignment is specified as an
9057     //   explicit operand, rather than implicitly as the standard alignment
9058     //   of the memory type (like the intrisics).  We need to change the
9059     //   memory type to match the explicit alignment.  That way, we don't
9060     //   generate non-standard-aligned ARMISD::VLDx nodes.
9061     if (isa<LSBaseSDNode>(N)) {
9062       if (Alignment == 0)
9063         Alignment = 1;
9064       if (Alignment < VecTy.getScalarSizeInBits() / 8) {
9065         MVT EltTy = MVT::getIntegerVT(Alignment * 8);
9066         assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
9067         assert(!isLaneOp && "Unexpected generic load/store lane.");
9068         unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
9069         AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
9070       }
9071       // Don't set an explicit alignment on regular load/stores that we want
9072       // to transform to VLD/VST 1_UPD nodes.
9073       // This matches the behavior of regular load/stores, which only get an
9074       // explicit alignment if the MMO alignment is larger than the standard
9075       // alignment of the memory type.
9076       // Intrinsics, however, always get an explicit alignment, set to the
9077       // alignment of the MMO.
9078       Alignment = 1;
9079     }
9080
9081     // Create the new updating load/store node.
9082     // First, create an SDVTList for the new updating node's results.
9083     EVT Tys[6];
9084     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
9085     unsigned n;
9086     for (n = 0; n < NumResultVecs; ++n)
9087       Tys[n] = AlignedVecTy;
9088     Tys[n++] = MVT::i32;
9089     Tys[n] = MVT::Other;
9090     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
9091
9092     // Then, gather the new node's operands.
9093     SmallVector<SDValue, 8> Ops;
9094     Ops.push_back(N->getOperand(0)); // incoming chain
9095     Ops.push_back(N->getOperand(AddrOpIdx));
9096     Ops.push_back(Inc);
9097
9098     if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
9099       // Try to match the intrinsic's signature
9100       Ops.push_back(StN->getValue());
9101     } else {
9102       // Loads (and of course intrinsics) match the intrinsics' signature,
9103       // so just add all but the alignment operand.
9104       for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
9105         Ops.push_back(N->getOperand(i));
9106     }
9107
9108     // For all node types, the alignment operand is always the last one.
9109     Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
9110
9111     // If this is a non-standard-aligned STORE, the penultimate operand is the
9112     // stored value.  Bitcast it to the aligned type.
9113     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
9114       SDValue &StVal = Ops[Ops.size()-2];
9115       StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
9116     }
9117
9118     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys,
9119                                            Ops, AlignedVecTy,
9120                                            MemN->getMemOperand());
9121
9122     // Update the uses.
9123     SmallVector<SDValue, 5> NewResults;
9124     for (unsigned i = 0; i < NumResultVecs; ++i)
9125       NewResults.push_back(SDValue(UpdN.getNode(), i));
9126
9127     // If this is an non-standard-aligned LOAD, the first result is the loaded
9128     // value.  Bitcast it to the expected result type.
9129     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
9130       SDValue &LdVal = NewResults[0];
9131       LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
9132     }
9133
9134     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9135     DCI.CombineTo(N, NewResults);
9136     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9137
9138     break;
9139   }
9140   return SDValue();
9141 }
9142
9143 static SDValue PerformVLDCombine(SDNode *N,
9144                                  TargetLowering::DAGCombinerInfo &DCI) {
9145   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9146     return SDValue();
9147
9148   return CombineBaseUpdate(N, DCI);
9149 }
9150
9151 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9152 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9153 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
9154 /// return true.
9155 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9156   SelectionDAG &DAG = DCI.DAG;
9157   EVT VT = N->getValueType(0);
9158   // vldN-dup instructions only support 64-bit vectors for N > 1.
9159   if (!VT.is64BitVector())
9160     return false;
9161
9162   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9163   SDNode *VLD = N->getOperand(0).getNode();
9164   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9165     return false;
9166   unsigned NumVecs = 0;
9167   unsigned NewOpc = 0;
9168   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9169   if (IntNo == Intrinsic::arm_neon_vld2lane) {
9170     NumVecs = 2;
9171     NewOpc = ARMISD::VLD2DUP;
9172   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9173     NumVecs = 3;
9174     NewOpc = ARMISD::VLD3DUP;
9175   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9176     NumVecs = 4;
9177     NewOpc = ARMISD::VLD4DUP;
9178   } else {
9179     return false;
9180   }
9181
9182   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9183   // numbers match the load.
9184   unsigned VLDLaneNo =
9185     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9186   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9187        UI != UE; ++UI) {
9188     // Ignore uses of the chain result.
9189     if (UI.getUse().getResNo() == NumVecs)
9190       continue;
9191     SDNode *User = *UI;
9192     if (User->getOpcode() != ARMISD::VDUPLANE ||
9193         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9194       return false;
9195   }
9196
9197   // Create the vldN-dup node.
9198   EVT Tys[5];
9199   unsigned n;
9200   for (n = 0; n < NumVecs; ++n)
9201     Tys[n] = VT;
9202   Tys[n] = MVT::Other;
9203   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9204   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9205   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9206   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9207                                            Ops, VLDMemInt->getMemoryVT(),
9208                                            VLDMemInt->getMemOperand());
9209
9210   // Update the uses.
9211   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9212        UI != UE; ++UI) {
9213     unsigned ResNo = UI.getUse().getResNo();
9214     // Ignore uses of the chain result.
9215     if (ResNo == NumVecs)
9216       continue;
9217     SDNode *User = *UI;
9218     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9219   }
9220
9221   // Now the vldN-lane intrinsic is dead except for its chain result.
9222   // Update uses of the chain.
9223   std::vector<SDValue> VLDDupResults;
9224   for (unsigned n = 0; n < NumVecs; ++n)
9225     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9226   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9227   DCI.CombineTo(VLD, VLDDupResults);
9228
9229   return true;
9230 }
9231
9232 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9233 /// ARMISD::VDUPLANE.
9234 static SDValue PerformVDUPLANECombine(SDNode *N,
9235                                       TargetLowering::DAGCombinerInfo &DCI) {
9236   SDValue Op = N->getOperand(0);
9237
9238   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9239   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9240   if (CombineVLDDUP(N, DCI))
9241     return SDValue(N, 0);
9242
9243   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9244   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9245   while (Op.getOpcode() == ISD::BITCAST)
9246     Op = Op.getOperand(0);
9247   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9248     return SDValue();
9249
9250   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9251   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9252   // The canonical VMOV for a zero vector uses a 32-bit element size.
9253   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9254   unsigned EltBits;
9255   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9256     EltSize = 8;
9257   EVT VT = N->getValueType(0);
9258   if (EltSize > VT.getVectorElementType().getSizeInBits())
9259     return SDValue();
9260
9261   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9262 }
9263
9264 static SDValue PerformLOADCombine(SDNode *N,
9265                                   TargetLowering::DAGCombinerInfo &DCI) {
9266   EVT VT = N->getValueType(0);
9267
9268   // If this is a legal vector load, try to combine it into a VLD1_UPD.
9269   if (ISD::isNormalLoad(N) && VT.isVector() &&
9270       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9271     return CombineBaseUpdate(N, DCI);
9272
9273   return SDValue();
9274 }
9275
9276 /// PerformSTORECombine - Target-specific dag combine xforms for
9277 /// ISD::STORE.
9278 static SDValue PerformSTORECombine(SDNode *N,
9279                                    TargetLowering::DAGCombinerInfo &DCI) {
9280   StoreSDNode *St = cast<StoreSDNode>(N);
9281   if (St->isVolatile())
9282     return SDValue();
9283
9284   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
9285   // pack all of the elements in one place.  Next, store to memory in fewer
9286   // chunks.
9287   SDValue StVal = St->getValue();
9288   EVT VT = StVal.getValueType();
9289   if (St->isTruncatingStore() && VT.isVector()) {
9290     SelectionDAG &DAG = DCI.DAG;
9291     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9292     EVT StVT = St->getMemoryVT();
9293     unsigned NumElems = VT.getVectorNumElements();
9294     assert(StVT != VT && "Cannot truncate to the same type");
9295     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
9296     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
9297
9298     // From, To sizes and ElemCount must be pow of two
9299     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
9300
9301     // We are going to use the original vector elt for storing.
9302     // Accumulated smaller vector elements must be a multiple of the store size.
9303     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
9304
9305     unsigned SizeRatio  = FromEltSz / ToEltSz;
9306     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
9307
9308     // Create a type on which we perform the shuffle.
9309     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9310                                      NumElems*SizeRatio);
9311     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9312
9313     SDLoc DL(St);
9314     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9315     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9316     for (unsigned i = 0; i < NumElems; ++i)
9317       ShuffleVec[i] = TLI.isBigEndian() ? (i+1) * SizeRatio - 1 : i * SizeRatio;
9318
9319     // Can't shuffle using an illegal type.
9320     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9321
9322     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9323                                 DAG.getUNDEF(WideVec.getValueType()),
9324                                 ShuffleVec.data());
9325     // At this point all of the data is stored at the bottom of the
9326     // register. We now need to save it to mem.
9327
9328     // Find the largest store unit
9329     MVT StoreType = MVT::i8;
9330     for (MVT Tp : MVT::integer_valuetypes()) {
9331       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9332         StoreType = Tp;
9333     }
9334     // Didn't find a legal store type.
9335     if (!TLI.isTypeLegal(StoreType))
9336       return SDValue();
9337
9338     // Bitcast the original vector into a vector of store-size units
9339     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9340             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9341     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9342     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9343     SmallVector<SDValue, 8> Chains;
9344     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8, DL,
9345                                         TLI.getPointerTy());
9346     SDValue BasePtr = St->getBasePtr();
9347
9348     // Perform one or more big stores into memory.
9349     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9350     for (unsigned I = 0; I < E; I++) {
9351       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9352                                    StoreType, ShuffWide,
9353                                    DAG.getIntPtrConstant(I, DL));
9354       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9355                                 St->getPointerInfo(), St->isVolatile(),
9356                                 St->isNonTemporal(), St->getAlignment());
9357       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9358                             Increment);
9359       Chains.push_back(Ch);
9360     }
9361     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
9362   }
9363
9364   if (!ISD::isNormalStore(St))
9365     return SDValue();
9366
9367   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9368   // ARM stores of arguments in the same cache line.
9369   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9370       StVal.getNode()->hasOneUse()) {
9371     SelectionDAG  &DAG = DCI.DAG;
9372     bool isBigEndian = DAG.getTargetLoweringInfo().isBigEndian();
9373     SDLoc DL(St);
9374     SDValue BasePtr = St->getBasePtr();
9375     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9376                                   StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
9377                                   BasePtr, St->getPointerInfo(), St->isVolatile(),
9378                                   St->isNonTemporal(), St->getAlignment());
9379
9380     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9381                                     DAG.getConstant(4, DL, MVT::i32));
9382     return DAG.getStore(NewST1.getValue(0), DL,
9383                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
9384                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9385                         St->isNonTemporal(),
9386                         std::min(4U, St->getAlignment() / 2));
9387   }
9388
9389   if (StVal.getValueType() == MVT::i64 &&
9390       StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9391
9392     // Bitcast an i64 store extracted from a vector to f64.
9393     // Otherwise, the i64 value will be legalized to a pair of i32 values.
9394     SelectionDAG &DAG = DCI.DAG;
9395     SDLoc dl(StVal);
9396     SDValue IntVec = StVal.getOperand(0);
9397     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9398                                    IntVec.getValueType().getVectorNumElements());
9399     SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9400     SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9401                                  Vec, StVal.getOperand(1));
9402     dl = SDLoc(N);
9403     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9404     // Make the DAGCombiner fold the bitcasts.
9405     DCI.AddToWorklist(Vec.getNode());
9406     DCI.AddToWorklist(ExtElt.getNode());
9407     DCI.AddToWorklist(V.getNode());
9408     return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9409                         St->getPointerInfo(), St->isVolatile(),
9410                         St->isNonTemporal(), St->getAlignment(),
9411                         St->getAAInfo());
9412   }
9413
9414   // If this is a legal vector store, try to combine it into a VST1_UPD.
9415   if (ISD::isNormalStore(N) && VT.isVector() &&
9416       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9417     return CombineBaseUpdate(N, DCI);
9418
9419   return SDValue();
9420 }
9421
9422 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9423 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9424 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9425 {
9426   integerPart cN;
9427   integerPart c0 = 0;
9428   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9429        I != E; I++) {
9430     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9431     if (!C)
9432       return false;
9433
9434     bool isExact;
9435     APFloat APF = C->getValueAPF();
9436     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9437         != APFloat::opOK || !isExact)
9438       return false;
9439
9440     c0 = (I == 0) ? cN : c0;
9441     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9442       return false;
9443   }
9444   C = c0;
9445   return true;
9446 }
9447
9448 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9449 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9450 /// when the VMUL has a constant operand that is a power of 2.
9451 ///
9452 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9453 ///  vmul.f32        d16, d17, d16
9454 ///  vcvt.s32.f32    d16, d16
9455 /// becomes:
9456 ///  vcvt.s32.f32    d16, d16, #3
9457 static SDValue PerformVCVTCombine(SDNode *N,
9458                                   TargetLowering::DAGCombinerInfo &DCI,
9459                                   const ARMSubtarget *Subtarget) {
9460   SelectionDAG &DAG = DCI.DAG;
9461   SDValue Op = N->getOperand(0);
9462
9463   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9464       Op.getOpcode() != ISD::FMUL)
9465     return SDValue();
9466
9467   uint64_t C;
9468   SDValue N0 = Op->getOperand(0);
9469   SDValue ConstVec = Op->getOperand(1);
9470   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9471
9472   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9473       !isConstVecPow2(ConstVec, isSigned, C))
9474     return SDValue();
9475
9476   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9477   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9478   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9479   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32 ||
9480       NumLanes > 4) {
9481     // These instructions only exist converting from f32 to i32. We can handle
9482     // smaller integers by generating an extra truncate, but larger ones would
9483     // be lossy. We also can't handle more then 4 lanes, since these intructions
9484     // only support v2i32/v4i32 types.
9485     return SDValue();
9486   }
9487
9488   SDLoc dl(N);
9489   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9490     Intrinsic::arm_neon_vcvtfp2fxu;
9491   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9492                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9493                                  DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9494                                  N0,
9495                                  DAG.getConstant(Log2_64(C), dl, MVT::i32));
9496
9497   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9498     FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
9499
9500   return FixConv;
9501 }
9502
9503 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9504 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9505 /// when the VDIV has a constant operand that is a power of 2.
9506 ///
9507 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9508 ///  vcvt.f32.s32    d16, d16
9509 ///  vdiv.f32        d16, d17, d16
9510 /// becomes:
9511 ///  vcvt.f32.s32    d16, d16, #3
9512 static SDValue PerformVDIVCombine(SDNode *N,
9513                                   TargetLowering::DAGCombinerInfo &DCI,
9514                                   const ARMSubtarget *Subtarget) {
9515   SelectionDAG &DAG = DCI.DAG;
9516   SDValue Op = N->getOperand(0);
9517   unsigned OpOpcode = Op.getNode()->getOpcode();
9518
9519   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9520       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9521     return SDValue();
9522
9523   uint64_t C;
9524   SDValue ConstVec = N->getOperand(1);
9525   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9526
9527   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9528       !isConstVecPow2(ConstVec, isSigned, C))
9529     return SDValue();
9530
9531   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9532   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9533   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9534     // These instructions only exist converting from i32 to f32. We can handle
9535     // smaller integers by generating an extra extend, but larger ones would
9536     // be lossy.
9537     return SDValue();
9538   }
9539
9540   SDLoc dl(N);
9541   SDValue ConvInput = Op.getOperand(0);
9542   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9543   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9544     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9545                             dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9546                             ConvInput);
9547
9548   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9549     Intrinsic::arm_neon_vcvtfxu2fp;
9550   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9551                      Op.getValueType(),
9552                      DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9553                      ConvInput, DAG.getConstant(Log2_64(C), dl, MVT::i32));
9554 }
9555
9556 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9557 /// operand of a vector shift operation, where all the elements of the
9558 /// build_vector must have the same constant integer value.
9559 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9560   // Ignore bit_converts.
9561   while (Op.getOpcode() == ISD::BITCAST)
9562     Op = Op.getOperand(0);
9563   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9564   APInt SplatBits, SplatUndef;
9565   unsigned SplatBitSize;
9566   bool HasAnyUndefs;
9567   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9568                                       HasAnyUndefs, ElementBits) ||
9569       SplatBitSize > ElementBits)
9570     return false;
9571   Cnt = SplatBits.getSExtValue();
9572   return true;
9573 }
9574
9575 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9576 /// operand of a vector shift left operation.  That value must be in the range:
9577 ///   0 <= Value < ElementBits for a left shift; or
9578 ///   0 <= Value <= ElementBits for a long left shift.
9579 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9580   assert(VT.isVector() && "vector shift count is not a vector type");
9581   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9582   if (! getVShiftImm(Op, ElementBits, Cnt))
9583     return false;
9584   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9585 }
9586
9587 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9588 /// operand of a vector shift right operation.  For a shift opcode, the value
9589 /// is positive, but for an intrinsic the value count must be negative. The
9590 /// absolute value must be in the range:
9591 ///   1 <= |Value| <= ElementBits for a right shift; or
9592 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9593 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9594                          int64_t &Cnt) {
9595   assert(VT.isVector() && "vector shift count is not a vector type");
9596   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9597   if (! getVShiftImm(Op, ElementBits, Cnt))
9598     return false;
9599   if (isIntrinsic)
9600     Cnt = -Cnt;
9601   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9602 }
9603
9604 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9605 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9606   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9607   switch (IntNo) {
9608   default:
9609     // Don't do anything for most intrinsics.
9610     break;
9611
9612   // Vector shifts: check for immediate versions and lower them.
9613   // Note: This is done during DAG combining instead of DAG legalizing because
9614   // the build_vectors for 64-bit vector element shift counts are generally
9615   // not legal, and it is hard to see their values after they get legalized to
9616   // loads from a constant pool.
9617   case Intrinsic::arm_neon_vshifts:
9618   case Intrinsic::arm_neon_vshiftu:
9619   case Intrinsic::arm_neon_vrshifts:
9620   case Intrinsic::arm_neon_vrshiftu:
9621   case Intrinsic::arm_neon_vrshiftn:
9622   case Intrinsic::arm_neon_vqshifts:
9623   case Intrinsic::arm_neon_vqshiftu:
9624   case Intrinsic::arm_neon_vqshiftsu:
9625   case Intrinsic::arm_neon_vqshiftns:
9626   case Intrinsic::arm_neon_vqshiftnu:
9627   case Intrinsic::arm_neon_vqshiftnsu:
9628   case Intrinsic::arm_neon_vqrshiftns:
9629   case Intrinsic::arm_neon_vqrshiftnu:
9630   case Intrinsic::arm_neon_vqrshiftnsu: {
9631     EVT VT = N->getOperand(1).getValueType();
9632     int64_t Cnt;
9633     unsigned VShiftOpc = 0;
9634
9635     switch (IntNo) {
9636     case Intrinsic::arm_neon_vshifts:
9637     case Intrinsic::arm_neon_vshiftu:
9638       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9639         VShiftOpc = ARMISD::VSHL;
9640         break;
9641       }
9642       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9643         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9644                      ARMISD::VSHRs : ARMISD::VSHRu);
9645         break;
9646       }
9647       return SDValue();
9648
9649     case Intrinsic::arm_neon_vrshifts:
9650     case Intrinsic::arm_neon_vrshiftu:
9651       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9652         break;
9653       return SDValue();
9654
9655     case Intrinsic::arm_neon_vqshifts:
9656     case Intrinsic::arm_neon_vqshiftu:
9657       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9658         break;
9659       return SDValue();
9660
9661     case Intrinsic::arm_neon_vqshiftsu:
9662       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9663         break;
9664       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9665
9666     case Intrinsic::arm_neon_vrshiftn:
9667     case Intrinsic::arm_neon_vqshiftns:
9668     case Intrinsic::arm_neon_vqshiftnu:
9669     case Intrinsic::arm_neon_vqshiftnsu:
9670     case Intrinsic::arm_neon_vqrshiftns:
9671     case Intrinsic::arm_neon_vqrshiftnu:
9672     case Intrinsic::arm_neon_vqrshiftnsu:
9673       // Narrowing shifts require an immediate right shift.
9674       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9675         break;
9676       llvm_unreachable("invalid shift count for narrowing vector shift "
9677                        "intrinsic");
9678
9679     default:
9680       llvm_unreachable("unhandled vector shift");
9681     }
9682
9683     switch (IntNo) {
9684     case Intrinsic::arm_neon_vshifts:
9685     case Intrinsic::arm_neon_vshiftu:
9686       // Opcode already set above.
9687       break;
9688     case Intrinsic::arm_neon_vrshifts:
9689       VShiftOpc = ARMISD::VRSHRs; break;
9690     case Intrinsic::arm_neon_vrshiftu:
9691       VShiftOpc = ARMISD::VRSHRu; break;
9692     case Intrinsic::arm_neon_vrshiftn:
9693       VShiftOpc = ARMISD::VRSHRN; break;
9694     case Intrinsic::arm_neon_vqshifts:
9695       VShiftOpc = ARMISD::VQSHLs; break;
9696     case Intrinsic::arm_neon_vqshiftu:
9697       VShiftOpc = ARMISD::VQSHLu; break;
9698     case Intrinsic::arm_neon_vqshiftsu:
9699       VShiftOpc = ARMISD::VQSHLsu; break;
9700     case Intrinsic::arm_neon_vqshiftns:
9701       VShiftOpc = ARMISD::VQSHRNs; break;
9702     case Intrinsic::arm_neon_vqshiftnu:
9703       VShiftOpc = ARMISD::VQSHRNu; break;
9704     case Intrinsic::arm_neon_vqshiftnsu:
9705       VShiftOpc = ARMISD::VQSHRNsu; break;
9706     case Intrinsic::arm_neon_vqrshiftns:
9707       VShiftOpc = ARMISD::VQRSHRNs; break;
9708     case Intrinsic::arm_neon_vqrshiftnu:
9709       VShiftOpc = ARMISD::VQRSHRNu; break;
9710     case Intrinsic::arm_neon_vqrshiftnsu:
9711       VShiftOpc = ARMISD::VQRSHRNsu; break;
9712     }
9713
9714     SDLoc dl(N);
9715     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
9716                        N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
9717   }
9718
9719   case Intrinsic::arm_neon_vshiftins: {
9720     EVT VT = N->getOperand(1).getValueType();
9721     int64_t Cnt;
9722     unsigned VShiftOpc = 0;
9723
9724     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9725       VShiftOpc = ARMISD::VSLI;
9726     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9727       VShiftOpc = ARMISD::VSRI;
9728     else {
9729       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9730     }
9731
9732     SDLoc dl(N);
9733     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
9734                        N->getOperand(1), N->getOperand(2),
9735                        DAG.getConstant(Cnt, dl, MVT::i32));
9736   }
9737
9738   case Intrinsic::arm_neon_vqrshifts:
9739   case Intrinsic::arm_neon_vqrshiftu:
9740     // No immediate versions of these to check for.
9741     break;
9742   }
9743
9744   return SDValue();
9745 }
9746
9747 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9748 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9749 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9750 /// vector element shift counts are generally not legal, and it is hard to see
9751 /// their values after they get legalized to loads from a constant pool.
9752 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9753                                    const ARMSubtarget *ST) {
9754   EVT VT = N->getValueType(0);
9755   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9756     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9757     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9758     SDValue N1 = N->getOperand(1);
9759     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9760       SDValue N0 = N->getOperand(0);
9761       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9762           DAG.MaskedValueIsZero(N0.getOperand(0),
9763                                 APInt::getHighBitsSet(32, 16)))
9764         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9765     }
9766   }
9767
9768   // Nothing to be done for scalar shifts.
9769   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9770   if (!VT.isVector() || !TLI.isTypeLegal(VT))
9771     return SDValue();
9772
9773   assert(ST->hasNEON() && "unexpected vector shift");
9774   int64_t Cnt;
9775
9776   switch (N->getOpcode()) {
9777   default: llvm_unreachable("unexpected shift opcode");
9778
9779   case ISD::SHL:
9780     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
9781       SDLoc dl(N);
9782       return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
9783                          DAG.getConstant(Cnt, dl, MVT::i32));
9784     }
9785     break;
9786
9787   case ISD::SRA:
9788   case ISD::SRL:
9789     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9790       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9791                             ARMISD::VSHRs : ARMISD::VSHRu);
9792       SDLoc dl(N);
9793       return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
9794                          DAG.getConstant(Cnt, dl, MVT::i32));
9795     }
9796   }
9797   return SDValue();
9798 }
9799
9800 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9801 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9802 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9803                                     const ARMSubtarget *ST) {
9804   SDValue N0 = N->getOperand(0);
9805
9806   // Check for sign- and zero-extensions of vector extract operations of 8-
9807   // and 16-bit vector elements.  NEON supports these directly.  They are
9808   // handled during DAG combining because type legalization will promote them
9809   // to 32-bit types and it is messy to recognize the operations after that.
9810   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9811     SDValue Vec = N0.getOperand(0);
9812     SDValue Lane = N0.getOperand(1);
9813     EVT VT = N->getValueType(0);
9814     EVT EltVT = N0.getValueType();
9815     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9816
9817     if (VT == MVT::i32 &&
9818         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9819         TLI.isTypeLegal(Vec.getValueType()) &&
9820         isa<ConstantSDNode>(Lane)) {
9821
9822       unsigned Opc = 0;
9823       switch (N->getOpcode()) {
9824       default: llvm_unreachable("unexpected opcode");
9825       case ISD::SIGN_EXTEND:
9826         Opc = ARMISD::VGETLANEs;
9827         break;
9828       case ISD::ZERO_EXTEND:
9829       case ISD::ANY_EXTEND:
9830         Opc = ARMISD::VGETLANEu;
9831         break;
9832       }
9833       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9834     }
9835   }
9836
9837   return SDValue();
9838 }
9839
9840 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9841 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9842 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9843                                        const ARMSubtarget *ST) {
9844   // If the target supports NEON, try to use vmax/vmin instructions for f32
9845   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
9846   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
9847   // a NaN; only do the transformation when it matches that behavior.
9848
9849   // For now only do this when using NEON for FP operations; if using VFP, it
9850   // is not obvious that the benefit outweighs the cost of switching to the
9851   // NEON pipeline.
9852   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9853       N->getValueType(0) != MVT::f32)
9854     return SDValue();
9855
9856   SDValue CondLHS = N->getOperand(0);
9857   SDValue CondRHS = N->getOperand(1);
9858   SDValue LHS = N->getOperand(2);
9859   SDValue RHS = N->getOperand(3);
9860   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9861
9862   unsigned Opcode = 0;
9863   bool IsReversed;
9864   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9865     IsReversed = false; // x CC y ? x : y
9866   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9867     IsReversed = true ; // x CC y ? y : x
9868   } else {
9869     return SDValue();
9870   }
9871
9872   bool IsUnordered;
9873   switch (CC) {
9874   default: break;
9875   case ISD::SETOLT:
9876   case ISD::SETOLE:
9877   case ISD::SETLT:
9878   case ISD::SETLE:
9879   case ISD::SETULT:
9880   case ISD::SETULE:
9881     // If LHS is NaN, an ordered comparison will be false and the result will
9882     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
9883     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9884     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9885     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9886       break;
9887     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9888     // will return -0, so vmin can only be used for unsafe math or if one of
9889     // the operands is known to be nonzero.
9890     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9891         !DAG.getTarget().Options.UnsafeFPMath &&
9892         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9893       break;
9894     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9895     break;
9896
9897   case ISD::SETOGT:
9898   case ISD::SETOGE:
9899   case ISD::SETGT:
9900   case ISD::SETGE:
9901   case ISD::SETUGT:
9902   case ISD::SETUGE:
9903     // If LHS is NaN, an ordered comparison will be false and the result will
9904     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
9905     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9906     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9907     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9908       break;
9909     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9910     // will return +0, so vmax can only be used for unsafe math or if one of
9911     // the operands is known to be nonzero.
9912     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9913         !DAG.getTarget().Options.UnsafeFPMath &&
9914         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9915       break;
9916     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9917     break;
9918   }
9919
9920   if (!Opcode)
9921     return SDValue();
9922   return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9923 }
9924
9925 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9926 SDValue
9927 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9928   SDValue Cmp = N->getOperand(4);
9929   if (Cmp.getOpcode() != ARMISD::CMPZ)
9930     // Only looking at EQ and NE cases.
9931     return SDValue();
9932
9933   EVT VT = N->getValueType(0);
9934   SDLoc dl(N);
9935   SDValue LHS = Cmp.getOperand(0);
9936   SDValue RHS = Cmp.getOperand(1);
9937   SDValue FalseVal = N->getOperand(0);
9938   SDValue TrueVal = N->getOperand(1);
9939   SDValue ARMcc = N->getOperand(2);
9940   ARMCC::CondCodes CC =
9941     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9942
9943   // Simplify
9944   //   mov     r1, r0
9945   //   cmp     r1, x
9946   //   mov     r0, y
9947   //   moveq   r0, x
9948   // to
9949   //   cmp     r0, x
9950   //   movne   r0, y
9951   //
9952   //   mov     r1, r0
9953   //   cmp     r1, x
9954   //   mov     r0, x
9955   //   movne   r0, y
9956   // to
9957   //   cmp     r0, x
9958   //   movne   r0, y
9959   /// FIXME: Turn this into a target neutral optimization?
9960   SDValue Res;
9961   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9962     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9963                       N->getOperand(3), Cmp);
9964   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9965     SDValue ARMcc;
9966     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9967     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9968                       N->getOperand(3), NewCmp);
9969   }
9970
9971   if (Res.getNode()) {
9972     APInt KnownZero, KnownOne;
9973     DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
9974     // Capture demanded bits information that would be otherwise lost.
9975     if (KnownZero == 0xfffffffe)
9976       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9977                         DAG.getValueType(MVT::i1));
9978     else if (KnownZero == 0xffffff00)
9979       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9980                         DAG.getValueType(MVT::i8));
9981     else if (KnownZero == 0xffff0000)
9982       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9983                         DAG.getValueType(MVT::i16));
9984   }
9985
9986   return Res;
9987 }
9988
9989 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9990                                              DAGCombinerInfo &DCI) const {
9991   switch (N->getOpcode()) {
9992   default: break;
9993   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
9994   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
9995   case ISD::SUB:        return PerformSUBCombine(N, DCI);
9996   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
9997   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
9998   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
9999   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
10000   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
10001   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
10002   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
10003   case ISD::STORE:      return PerformSTORECombine(N, DCI);
10004   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
10005   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
10006   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
10007   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
10008   case ISD::FP_TO_SINT:
10009   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
10010   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
10011   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
10012   case ISD::SHL:
10013   case ISD::SRA:
10014   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
10015   case ISD::SIGN_EXTEND:
10016   case ISD::ZERO_EXTEND:
10017   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
10018   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
10019   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
10020   case ISD::LOAD:       return PerformLOADCombine(N, DCI);
10021   case ARMISD::VLD2DUP:
10022   case ARMISD::VLD3DUP:
10023   case ARMISD::VLD4DUP:
10024     return PerformVLDCombine(N, DCI);
10025   case ARMISD::BUILD_VECTOR:
10026     return PerformARMBUILD_VECTORCombine(N, DCI);
10027   case ISD::INTRINSIC_VOID:
10028   case ISD::INTRINSIC_W_CHAIN:
10029     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10030     case Intrinsic::arm_neon_vld1:
10031     case Intrinsic::arm_neon_vld2:
10032     case Intrinsic::arm_neon_vld3:
10033     case Intrinsic::arm_neon_vld4:
10034     case Intrinsic::arm_neon_vld2lane:
10035     case Intrinsic::arm_neon_vld3lane:
10036     case Intrinsic::arm_neon_vld4lane:
10037     case Intrinsic::arm_neon_vst1:
10038     case Intrinsic::arm_neon_vst2:
10039     case Intrinsic::arm_neon_vst3:
10040     case Intrinsic::arm_neon_vst4:
10041     case Intrinsic::arm_neon_vst2lane:
10042     case Intrinsic::arm_neon_vst3lane:
10043     case Intrinsic::arm_neon_vst4lane:
10044       return PerformVLDCombine(N, DCI);
10045     default: break;
10046     }
10047     break;
10048   }
10049   return SDValue();
10050 }
10051
10052 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
10053                                                           EVT VT) const {
10054   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
10055 }
10056
10057 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
10058                                                        unsigned,
10059                                                        unsigned,
10060                                                        bool *Fast) const {
10061   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
10062   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
10063
10064   switch (VT.getSimpleVT().SimpleTy) {
10065   default:
10066     return false;
10067   case MVT::i8:
10068   case MVT::i16:
10069   case MVT::i32: {
10070     // Unaligned access can use (for example) LRDB, LRDH, LDR
10071     if (AllowsUnaligned) {
10072       if (Fast)
10073         *Fast = Subtarget->hasV7Ops();
10074       return true;
10075     }
10076     return false;
10077   }
10078   case MVT::f64:
10079   case MVT::v2f64: {
10080     // For any little-endian targets with neon, we can support unaligned ld/st
10081     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10082     // A big-endian target may also explicitly support unaligned accesses
10083     if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
10084       if (Fast)
10085         *Fast = true;
10086       return true;
10087     }
10088     return false;
10089   }
10090   }
10091 }
10092
10093 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10094                        unsigned AlignCheck) {
10095   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10096           (DstAlign == 0 || DstAlign % AlignCheck == 0));
10097 }
10098
10099 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10100                                            unsigned DstAlign, unsigned SrcAlign,
10101                                            bool IsMemset, bool ZeroMemset,
10102                                            bool MemcpyStrSrc,
10103                                            MachineFunction &MF) const {
10104   const Function *F = MF.getFunction();
10105
10106   // See if we can use NEON instructions for this...
10107   if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
10108       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10109     bool Fast;
10110     if (Size >= 16 &&
10111         (memOpAlign(SrcAlign, DstAlign, 16) ||
10112          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
10113       return MVT::v2f64;
10114     } else if (Size >= 8 &&
10115                (memOpAlign(SrcAlign, DstAlign, 8) ||
10116                 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
10117                  Fast))) {
10118       return MVT::f64;
10119     }
10120   }
10121
10122   // Lowering to i32/i16 if the size permits.
10123   if (Size >= 4)
10124     return MVT::i32;
10125   else if (Size >= 2)
10126     return MVT::i16;
10127
10128   // Let the target-independent logic figure it out.
10129   return MVT::Other;
10130 }
10131
10132 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10133   if (Val.getOpcode() != ISD::LOAD)
10134     return false;
10135
10136   EVT VT1 = Val.getValueType();
10137   if (!VT1.isSimple() || !VT1.isInteger() ||
10138       !VT2.isSimple() || !VT2.isInteger())
10139     return false;
10140
10141   switch (VT1.getSimpleVT().SimpleTy) {
10142   default: break;
10143   case MVT::i1:
10144   case MVT::i8:
10145   case MVT::i16:
10146     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10147     return true;
10148   }
10149
10150   return false;
10151 }
10152
10153 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
10154   EVT VT = ExtVal.getValueType();
10155
10156   if (!isTypeLegal(VT))
10157     return false;
10158
10159   // Don't create a loadext if we can fold the extension into a wide/long
10160   // instruction.
10161   // If there's more than one user instruction, the loadext is desirable no
10162   // matter what.  There can be two uses by the same instruction.
10163   if (ExtVal->use_empty() ||
10164       !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
10165     return true;
10166
10167   SDNode *U = *ExtVal->use_begin();
10168   if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
10169        U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
10170     return false;
10171
10172   return true;
10173 }
10174
10175 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10176   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10177     return false;
10178
10179   if (!isTypeLegal(EVT::getEVT(Ty1)))
10180     return false;
10181
10182   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10183
10184   // Assuming the caller doesn't have a zeroext or signext return parameter,
10185   // truncation all the way down to i1 is valid.
10186   return true;
10187 }
10188
10189
10190 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10191   if (V < 0)
10192     return false;
10193
10194   unsigned Scale = 1;
10195   switch (VT.getSimpleVT().SimpleTy) {
10196   default: return false;
10197   case MVT::i1:
10198   case MVT::i8:
10199     // Scale == 1;
10200     break;
10201   case MVT::i16:
10202     // Scale == 2;
10203     Scale = 2;
10204     break;
10205   case MVT::i32:
10206     // Scale == 4;
10207     Scale = 4;
10208     break;
10209   }
10210
10211   if ((V & (Scale - 1)) != 0)
10212     return false;
10213   V /= Scale;
10214   return V == (V & ((1LL << 5) - 1));
10215 }
10216
10217 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10218                                       const ARMSubtarget *Subtarget) {
10219   bool isNeg = false;
10220   if (V < 0) {
10221     isNeg = true;
10222     V = - V;
10223   }
10224
10225   switch (VT.getSimpleVT().SimpleTy) {
10226   default: return false;
10227   case MVT::i1:
10228   case MVT::i8:
10229   case MVT::i16:
10230   case MVT::i32:
10231     // + imm12 or - imm8
10232     if (isNeg)
10233       return V == (V & ((1LL << 8) - 1));
10234     return V == (V & ((1LL << 12) - 1));
10235   case MVT::f32:
10236   case MVT::f64:
10237     // Same as ARM mode. FIXME: NEON?
10238     if (!Subtarget->hasVFP2())
10239       return false;
10240     if ((V & 3) != 0)
10241       return false;
10242     V >>= 2;
10243     return V == (V & ((1LL << 8) - 1));
10244   }
10245 }
10246
10247 /// isLegalAddressImmediate - Return true if the integer value can be used
10248 /// as the offset of the target addressing mode for load / store of the
10249 /// given type.
10250 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10251                                     const ARMSubtarget *Subtarget) {
10252   if (V == 0)
10253     return true;
10254
10255   if (!VT.isSimple())
10256     return false;
10257
10258   if (Subtarget->isThumb1Only())
10259     return isLegalT1AddressImmediate(V, VT);
10260   else if (Subtarget->isThumb2())
10261     return isLegalT2AddressImmediate(V, VT, Subtarget);
10262
10263   // ARM mode.
10264   if (V < 0)
10265     V = - V;
10266   switch (VT.getSimpleVT().SimpleTy) {
10267   default: return false;
10268   case MVT::i1:
10269   case MVT::i8:
10270   case MVT::i32:
10271     // +- imm12
10272     return V == (V & ((1LL << 12) - 1));
10273   case MVT::i16:
10274     // +- imm8
10275     return V == (V & ((1LL << 8) - 1));
10276   case MVT::f32:
10277   case MVT::f64:
10278     if (!Subtarget->hasVFP2()) // FIXME: NEON?
10279       return false;
10280     if ((V & 3) != 0)
10281       return false;
10282     V >>= 2;
10283     return V == (V & ((1LL << 8) - 1));
10284   }
10285 }
10286
10287 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10288                                                       EVT VT) const {
10289   int Scale = AM.Scale;
10290   if (Scale < 0)
10291     return false;
10292
10293   switch (VT.getSimpleVT().SimpleTy) {
10294   default: return false;
10295   case MVT::i1:
10296   case MVT::i8:
10297   case MVT::i16:
10298   case MVT::i32:
10299     if (Scale == 1)
10300       return true;
10301     // r + r << imm
10302     Scale = Scale & ~1;
10303     return Scale == 2 || Scale == 4 || Scale == 8;
10304   case MVT::i64:
10305     // r + r
10306     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10307       return true;
10308     return false;
10309   case MVT::isVoid:
10310     // Note, we allow "void" uses (basically, uses that aren't loads or
10311     // stores), because arm allows folding a scale into many arithmetic
10312     // operations.  This should be made more precise and revisited later.
10313
10314     // Allow r << imm, but the imm has to be a multiple of two.
10315     if (Scale & 1) return false;
10316     return isPowerOf2_32(Scale);
10317   }
10318 }
10319
10320 /// isLegalAddressingMode - Return true if the addressing mode represented
10321 /// by AM is legal for this target, for a load/store of the specified type.
10322 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10323                                               Type *Ty,
10324                                               unsigned AS) const {
10325   EVT VT = getValueType(Ty, true);
10326   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10327     return false;
10328
10329   // Can never fold addr of global into load/store.
10330   if (AM.BaseGV)
10331     return false;
10332
10333   switch (AM.Scale) {
10334   case 0:  // no scale reg, must be "r+i" or "r", or "i".
10335     break;
10336   case 1:
10337     if (Subtarget->isThumb1Only())
10338       return false;
10339     // FALL THROUGH.
10340   default:
10341     // ARM doesn't support any R+R*scale+imm addr modes.
10342     if (AM.BaseOffs)
10343       return false;
10344
10345     if (!VT.isSimple())
10346       return false;
10347
10348     if (Subtarget->isThumb2())
10349       return isLegalT2ScaledAddressingMode(AM, VT);
10350
10351     int Scale = AM.Scale;
10352     switch (VT.getSimpleVT().SimpleTy) {
10353     default: return false;
10354     case MVT::i1:
10355     case MVT::i8:
10356     case MVT::i32:
10357       if (Scale < 0) Scale = -Scale;
10358       if (Scale == 1)
10359         return true;
10360       // r + r << imm
10361       return isPowerOf2_32(Scale & ~1);
10362     case MVT::i16:
10363     case MVT::i64:
10364       // r + r
10365       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10366         return true;
10367       return false;
10368
10369     case MVT::isVoid:
10370       // Note, we allow "void" uses (basically, uses that aren't loads or
10371       // stores), because arm allows folding a scale into many arithmetic
10372       // operations.  This should be made more precise and revisited later.
10373
10374       // Allow r << imm, but the imm has to be a multiple of two.
10375       if (Scale & 1) return false;
10376       return isPowerOf2_32(Scale);
10377     }
10378   }
10379   return true;
10380 }
10381
10382 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10383 /// icmp immediate, that is the target has icmp instructions which can compare
10384 /// a register against the immediate without having to materialize the
10385 /// immediate into a register.
10386 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10387   // Thumb2 and ARM modes can use cmn for negative immediates.
10388   if (!Subtarget->isThumb())
10389     return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
10390   if (Subtarget->isThumb2())
10391     return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
10392   // Thumb1 doesn't have cmn, and only 8-bit immediates.
10393   return Imm >= 0 && Imm <= 255;
10394 }
10395
10396 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10397 /// *or sub* immediate, that is the target has add or sub instructions which can
10398 /// add a register with the immediate without having to materialize the
10399 /// immediate into a register.
10400 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10401   // Same encoding for add/sub, just flip the sign.
10402   int64_t AbsImm = std::abs(Imm);
10403   if (!Subtarget->isThumb())
10404     return ARM_AM::getSOImmVal(AbsImm) != -1;
10405   if (Subtarget->isThumb2())
10406     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10407   // Thumb1 only has 8-bit unsigned immediate.
10408   return AbsImm >= 0 && AbsImm <= 255;
10409 }
10410
10411 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10412                                       bool isSEXTLoad, SDValue &Base,
10413                                       SDValue &Offset, bool &isInc,
10414                                       SelectionDAG &DAG) {
10415   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10416     return false;
10417
10418   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10419     // AddressingMode 3
10420     Base = Ptr->getOperand(0);
10421     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10422       int RHSC = (int)RHS->getZExtValue();
10423       if (RHSC < 0 && RHSC > -256) {
10424         assert(Ptr->getOpcode() == ISD::ADD);
10425         isInc = false;
10426         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10427         return true;
10428       }
10429     }
10430     isInc = (Ptr->getOpcode() == ISD::ADD);
10431     Offset = Ptr->getOperand(1);
10432     return true;
10433   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10434     // AddressingMode 2
10435     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10436       int RHSC = (int)RHS->getZExtValue();
10437       if (RHSC < 0 && RHSC > -0x1000) {
10438         assert(Ptr->getOpcode() == ISD::ADD);
10439         isInc = false;
10440         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10441         Base = Ptr->getOperand(0);
10442         return true;
10443       }
10444     }
10445
10446     if (Ptr->getOpcode() == ISD::ADD) {
10447       isInc = true;
10448       ARM_AM::ShiftOpc ShOpcVal=
10449         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10450       if (ShOpcVal != ARM_AM::no_shift) {
10451         Base = Ptr->getOperand(1);
10452         Offset = Ptr->getOperand(0);
10453       } else {
10454         Base = Ptr->getOperand(0);
10455         Offset = Ptr->getOperand(1);
10456       }
10457       return true;
10458     }
10459
10460     isInc = (Ptr->getOpcode() == ISD::ADD);
10461     Base = Ptr->getOperand(0);
10462     Offset = Ptr->getOperand(1);
10463     return true;
10464   }
10465
10466   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10467   return false;
10468 }
10469
10470 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10471                                      bool isSEXTLoad, SDValue &Base,
10472                                      SDValue &Offset, bool &isInc,
10473                                      SelectionDAG &DAG) {
10474   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10475     return false;
10476
10477   Base = Ptr->getOperand(0);
10478   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10479     int RHSC = (int)RHS->getZExtValue();
10480     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10481       assert(Ptr->getOpcode() == ISD::ADD);
10482       isInc = false;
10483       Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10484       return true;
10485     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10486       isInc = Ptr->getOpcode() == ISD::ADD;
10487       Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
10488       return true;
10489     }
10490   }
10491
10492   return false;
10493 }
10494
10495 /// getPreIndexedAddressParts - returns true by value, base pointer and
10496 /// offset pointer and addressing mode by reference if the node's address
10497 /// can be legally represented as pre-indexed load / store address.
10498 bool
10499 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10500                                              SDValue &Offset,
10501                                              ISD::MemIndexedMode &AM,
10502                                              SelectionDAG &DAG) const {
10503   if (Subtarget->isThumb1Only())
10504     return false;
10505
10506   EVT VT;
10507   SDValue Ptr;
10508   bool isSEXTLoad = false;
10509   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10510     Ptr = LD->getBasePtr();
10511     VT  = LD->getMemoryVT();
10512     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10513   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10514     Ptr = ST->getBasePtr();
10515     VT  = ST->getMemoryVT();
10516   } else
10517     return false;
10518
10519   bool isInc;
10520   bool isLegal = false;
10521   if (Subtarget->isThumb2())
10522     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10523                                        Offset, isInc, DAG);
10524   else
10525     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10526                                         Offset, isInc, DAG);
10527   if (!isLegal)
10528     return false;
10529
10530   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10531   return true;
10532 }
10533
10534 /// getPostIndexedAddressParts - returns true by value, base pointer and
10535 /// offset pointer and addressing mode by reference if this node can be
10536 /// combined with a load / store to form a post-indexed load / store.
10537 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10538                                                    SDValue &Base,
10539                                                    SDValue &Offset,
10540                                                    ISD::MemIndexedMode &AM,
10541                                                    SelectionDAG &DAG) const {
10542   if (Subtarget->isThumb1Only())
10543     return false;
10544
10545   EVT VT;
10546   SDValue Ptr;
10547   bool isSEXTLoad = false;
10548   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10549     VT  = LD->getMemoryVT();
10550     Ptr = LD->getBasePtr();
10551     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10552   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10553     VT  = ST->getMemoryVT();
10554     Ptr = ST->getBasePtr();
10555   } else
10556     return false;
10557
10558   bool isInc;
10559   bool isLegal = false;
10560   if (Subtarget->isThumb2())
10561     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10562                                        isInc, DAG);
10563   else
10564     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10565                                         isInc, DAG);
10566   if (!isLegal)
10567     return false;
10568
10569   if (Ptr != Base) {
10570     // Swap base ptr and offset to catch more post-index load / store when
10571     // it's legal. In Thumb2 mode, offset must be an immediate.
10572     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10573         !Subtarget->isThumb2())
10574       std::swap(Base, Offset);
10575
10576     // Post-indexed load / store update the base pointer.
10577     if (Ptr != Base)
10578       return false;
10579   }
10580
10581   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10582   return true;
10583 }
10584
10585 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10586                                                       APInt &KnownZero,
10587                                                       APInt &KnownOne,
10588                                                       const SelectionDAG &DAG,
10589                                                       unsigned Depth) const {
10590   unsigned BitWidth = KnownOne.getBitWidth();
10591   KnownZero = KnownOne = APInt(BitWidth, 0);
10592   switch (Op.getOpcode()) {
10593   default: break;
10594   case ARMISD::ADDC:
10595   case ARMISD::ADDE:
10596   case ARMISD::SUBC:
10597   case ARMISD::SUBE:
10598     // These nodes' second result is a boolean
10599     if (Op.getResNo() == 0)
10600       break;
10601     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10602     break;
10603   case ARMISD::CMOV: {
10604     // Bits are known zero/one if known on the LHS and RHS.
10605     DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10606     if (KnownZero == 0 && KnownOne == 0) return;
10607
10608     APInt KnownZeroRHS, KnownOneRHS;
10609     DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10610     KnownZero &= KnownZeroRHS;
10611     KnownOne  &= KnownOneRHS;
10612     return;
10613   }
10614   case ISD::INTRINSIC_W_CHAIN: {
10615     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10616     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10617     switch (IntID) {
10618     default: return;
10619     case Intrinsic::arm_ldaex:
10620     case Intrinsic::arm_ldrex: {
10621       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10622       unsigned MemBits = VT.getScalarType().getSizeInBits();
10623       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10624       return;
10625     }
10626     }
10627   }
10628   }
10629 }
10630
10631 //===----------------------------------------------------------------------===//
10632 //                           ARM Inline Assembly Support
10633 //===----------------------------------------------------------------------===//
10634
10635 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10636   // Looking for "rev" which is V6+.
10637   if (!Subtarget->hasV6Ops())
10638     return false;
10639
10640   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10641   std::string AsmStr = IA->getAsmString();
10642   SmallVector<StringRef, 4> AsmPieces;
10643   SplitString(AsmStr, AsmPieces, ";\n");
10644
10645   switch (AsmPieces.size()) {
10646   default: return false;
10647   case 1:
10648     AsmStr = AsmPieces[0];
10649     AsmPieces.clear();
10650     SplitString(AsmStr, AsmPieces, " \t,");
10651
10652     // rev $0, $1
10653     if (AsmPieces.size() == 3 &&
10654         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10655         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10656       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10657       if (Ty && Ty->getBitWidth() == 32)
10658         return IntrinsicLowering::LowerToByteSwap(CI);
10659     }
10660     break;
10661   }
10662
10663   return false;
10664 }
10665
10666 /// getConstraintType - Given a constraint letter, return the type of
10667 /// constraint it is for this target.
10668 ARMTargetLowering::ConstraintType
10669 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10670   if (Constraint.size() == 1) {
10671     switch (Constraint[0]) {
10672     default:  break;
10673     case 'l': return C_RegisterClass;
10674     case 'w': return C_RegisterClass;
10675     case 'h': return C_RegisterClass;
10676     case 'x': return C_RegisterClass;
10677     case 't': return C_RegisterClass;
10678     case 'j': return C_Other; // Constant for movw.
10679       // An address with a single base register. Due to the way we
10680       // currently handle addresses it is the same as an 'r' memory constraint.
10681     case 'Q': return C_Memory;
10682     }
10683   } else if (Constraint.size() == 2) {
10684     switch (Constraint[0]) {
10685     default: break;
10686     // All 'U+' constraints are addresses.
10687     case 'U': return C_Memory;
10688     }
10689   }
10690   return TargetLowering::getConstraintType(Constraint);
10691 }
10692
10693 /// Examine constraint type and operand type and determine a weight value.
10694 /// This object must already have been set up with the operand type
10695 /// and the current alternative constraint selected.
10696 TargetLowering::ConstraintWeight
10697 ARMTargetLowering::getSingleConstraintMatchWeight(
10698     AsmOperandInfo &info, const char *constraint) const {
10699   ConstraintWeight weight = CW_Invalid;
10700   Value *CallOperandVal = info.CallOperandVal;
10701     // If we don't have a value, we can't do a match,
10702     // but allow it at the lowest weight.
10703   if (!CallOperandVal)
10704     return CW_Default;
10705   Type *type = CallOperandVal->getType();
10706   // Look at the constraint type.
10707   switch (*constraint) {
10708   default:
10709     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10710     break;
10711   case 'l':
10712     if (type->isIntegerTy()) {
10713       if (Subtarget->isThumb())
10714         weight = CW_SpecificReg;
10715       else
10716         weight = CW_Register;
10717     }
10718     break;
10719   case 'w':
10720     if (type->isFloatingPointTy())
10721       weight = CW_Register;
10722     break;
10723   }
10724   return weight;
10725 }
10726
10727 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10728 RCPair
10729 ARMTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
10730                                                 const std::string &Constraint,
10731                                                 MVT VT) const {
10732   if (Constraint.size() == 1) {
10733     // GCC ARM Constraint Letters
10734     switch (Constraint[0]) {
10735     case 'l': // Low regs or general regs.
10736       if (Subtarget->isThumb())
10737         return RCPair(0U, &ARM::tGPRRegClass);
10738       return RCPair(0U, &ARM::GPRRegClass);
10739     case 'h': // High regs or no regs.
10740       if (Subtarget->isThumb())
10741         return RCPair(0U, &ARM::hGPRRegClass);
10742       break;
10743     case 'r':
10744       if (Subtarget->isThumb1Only())
10745         return RCPair(0U, &ARM::tGPRRegClass);
10746       return RCPair(0U, &ARM::GPRRegClass);
10747     case 'w':
10748       if (VT == MVT::Other)
10749         break;
10750       if (VT == MVT::f32)
10751         return RCPair(0U, &ARM::SPRRegClass);
10752       if (VT.getSizeInBits() == 64)
10753         return RCPair(0U, &ARM::DPRRegClass);
10754       if (VT.getSizeInBits() == 128)
10755         return RCPair(0U, &ARM::QPRRegClass);
10756       break;
10757     case 'x':
10758       if (VT == MVT::Other)
10759         break;
10760       if (VT == MVT::f32)
10761         return RCPair(0U, &ARM::SPR_8RegClass);
10762       if (VT.getSizeInBits() == 64)
10763         return RCPair(0U, &ARM::DPR_8RegClass);
10764       if (VT.getSizeInBits() == 128)
10765         return RCPair(0U, &ARM::QPR_8RegClass);
10766       break;
10767     case 't':
10768       if (VT == MVT::f32)
10769         return RCPair(0U, &ARM::SPRRegClass);
10770       break;
10771     }
10772   }
10773   if (StringRef("{cc}").equals_lower(Constraint))
10774     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10775
10776   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10777 }
10778
10779 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10780 /// vector.  If it is invalid, don't add anything to Ops.
10781 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10782                                                      std::string &Constraint,
10783                                                      std::vector<SDValue>&Ops,
10784                                                      SelectionDAG &DAG) const {
10785   SDValue Result;
10786
10787   // Currently only support length 1 constraints.
10788   if (Constraint.length() != 1) return;
10789
10790   char ConstraintLetter = Constraint[0];
10791   switch (ConstraintLetter) {
10792   default: break;
10793   case 'j':
10794   case 'I': case 'J': case 'K': case 'L':
10795   case 'M': case 'N': case 'O':
10796     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10797     if (!C)
10798       return;
10799
10800     int64_t CVal64 = C->getSExtValue();
10801     int CVal = (int) CVal64;
10802     // None of these constraints allow values larger than 32 bits.  Check
10803     // that the value fits in an int.
10804     if (CVal != CVal64)
10805       return;
10806
10807     switch (ConstraintLetter) {
10808       case 'j':
10809         // Constant suitable for movw, must be between 0 and
10810         // 65535.
10811         if (Subtarget->hasV6T2Ops())
10812           if (CVal >= 0 && CVal <= 65535)
10813             break;
10814         return;
10815       case 'I':
10816         if (Subtarget->isThumb1Only()) {
10817           // This must be a constant between 0 and 255, for ADD
10818           // immediates.
10819           if (CVal >= 0 && CVal <= 255)
10820             break;
10821         } else if (Subtarget->isThumb2()) {
10822           // A constant that can be used as an immediate value in a
10823           // data-processing instruction.
10824           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10825             break;
10826         } else {
10827           // A constant that can be used as an immediate value in a
10828           // data-processing instruction.
10829           if (ARM_AM::getSOImmVal(CVal) != -1)
10830             break;
10831         }
10832         return;
10833
10834       case 'J':
10835         if (Subtarget->isThumb()) {  // FIXME thumb2
10836           // This must be a constant between -255 and -1, for negated ADD
10837           // immediates. This can be used in GCC with an "n" modifier that
10838           // prints the negated value, for use with SUB instructions. It is
10839           // not useful otherwise but is implemented for compatibility.
10840           if (CVal >= -255 && CVal <= -1)
10841             break;
10842         } else {
10843           // This must be a constant between -4095 and 4095. It is not clear
10844           // what this constraint is intended for. Implemented for
10845           // compatibility with GCC.
10846           if (CVal >= -4095 && CVal <= 4095)
10847             break;
10848         }
10849         return;
10850
10851       case 'K':
10852         if (Subtarget->isThumb1Only()) {
10853           // A 32-bit value where only one byte has a nonzero value. Exclude
10854           // zero to match GCC. This constraint is used by GCC internally for
10855           // constants that can be loaded with a move/shift combination.
10856           // It is not useful otherwise but is implemented for compatibility.
10857           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10858             break;
10859         } else if (Subtarget->isThumb2()) {
10860           // A constant whose bitwise inverse can be used as an immediate
10861           // value in a data-processing instruction. This can be used in GCC
10862           // with a "B" modifier that prints the inverted value, for use with
10863           // BIC and MVN instructions. It is not useful otherwise but is
10864           // implemented for compatibility.
10865           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10866             break;
10867         } else {
10868           // A constant whose bitwise inverse can be used as an immediate
10869           // value in a data-processing instruction. This can be used in GCC
10870           // with a "B" modifier that prints the inverted value, for use with
10871           // BIC and MVN instructions. It is not useful otherwise but is
10872           // implemented for compatibility.
10873           if (ARM_AM::getSOImmVal(~CVal) != -1)
10874             break;
10875         }
10876         return;
10877
10878       case 'L':
10879         if (Subtarget->isThumb1Only()) {
10880           // This must be a constant between -7 and 7,
10881           // for 3-operand ADD/SUB immediate instructions.
10882           if (CVal >= -7 && CVal < 7)
10883             break;
10884         } else if (Subtarget->isThumb2()) {
10885           // A constant whose negation can be used as an immediate value in a
10886           // data-processing instruction. This can be used in GCC with an "n"
10887           // modifier that prints the negated value, for use with SUB
10888           // instructions. It is not useful otherwise but is implemented for
10889           // compatibility.
10890           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10891             break;
10892         } else {
10893           // A constant whose negation can be used as an immediate value in a
10894           // data-processing instruction. This can be used in GCC with an "n"
10895           // modifier that prints the negated value, for use with SUB
10896           // instructions. It is not useful otherwise but is implemented for
10897           // compatibility.
10898           if (ARM_AM::getSOImmVal(-CVal) != -1)
10899             break;
10900         }
10901         return;
10902
10903       case 'M':
10904         if (Subtarget->isThumb()) { // FIXME thumb2
10905           // This must be a multiple of 4 between 0 and 1020, for
10906           // ADD sp + immediate.
10907           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10908             break;
10909         } else {
10910           // A power of two or a constant between 0 and 32.  This is used in
10911           // GCC for the shift amount on shifted register operands, but it is
10912           // useful in general for any shift amounts.
10913           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10914             break;
10915         }
10916         return;
10917
10918       case 'N':
10919         if (Subtarget->isThumb()) {  // FIXME thumb2
10920           // This must be a constant between 0 and 31, for shift amounts.
10921           if (CVal >= 0 && CVal <= 31)
10922             break;
10923         }
10924         return;
10925
10926       case 'O':
10927         if (Subtarget->isThumb()) {  // FIXME thumb2
10928           // This must be a multiple of 4 between -508 and 508, for
10929           // ADD/SUB sp = sp + immediate.
10930           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10931             break;
10932         }
10933         return;
10934     }
10935     Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
10936     break;
10937   }
10938
10939   if (Result.getNode()) {
10940     Ops.push_back(Result);
10941     return;
10942   }
10943   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10944 }
10945
10946 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10947   assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10948   unsigned Opcode = Op->getOpcode();
10949   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10950          "Invalid opcode for Div/Rem lowering");
10951   bool isSigned = (Opcode == ISD::SDIVREM);
10952   EVT VT = Op->getValueType(0);
10953   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10954
10955   RTLIB::Libcall LC;
10956   switch (VT.getSimpleVT().SimpleTy) {
10957   default: llvm_unreachable("Unexpected request for libcall!");
10958   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
10959   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10960   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10961   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10962   }
10963
10964   SDValue InChain = DAG.getEntryNode();
10965
10966   TargetLowering::ArgListTy Args;
10967   TargetLowering::ArgListEntry Entry;
10968   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
10969     EVT ArgVT = Op->getOperand(i).getValueType();
10970     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10971     Entry.Node = Op->getOperand(i);
10972     Entry.Ty = ArgTy;
10973     Entry.isSExt = isSigned;
10974     Entry.isZExt = !isSigned;
10975     Args.push_back(Entry);
10976   }
10977
10978   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
10979                                          getPointerTy());
10980
10981   Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
10982
10983   SDLoc dl(Op);
10984   TargetLowering::CallLoweringInfo CLI(DAG);
10985   CLI.setDebugLoc(dl).setChain(InChain)
10986     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
10987     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
10988
10989   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
10990   return CallInfo.first;
10991 }
10992
10993 SDValue
10994 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
10995   assert(Subtarget->isTargetWindows() && "unsupported target platform");
10996   SDLoc DL(Op);
10997
10998   // Get the inputs.
10999   SDValue Chain = Op.getOperand(0);
11000   SDValue Size  = Op.getOperand(1);
11001
11002   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
11003                               DAG.getConstant(2, DL, MVT::i32));
11004
11005   SDValue Flag;
11006   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
11007   Flag = Chain.getValue(1);
11008
11009   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11010   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
11011
11012   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
11013   Chain = NewSP.getValue(1);
11014
11015   SDValue Ops[2] = { NewSP, Chain };
11016   return DAG.getMergeValues(Ops, DL);
11017 }
11018
11019 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
11020   assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
11021          "Unexpected type for custom-lowering FP_EXTEND");
11022
11023   RTLIB::Libcall LC;
11024   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
11025
11026   SDValue SrcVal = Op.getOperand(0);
11027   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
11028                      /*isSigned*/ false, SDLoc(Op)).first;
11029 }
11030
11031 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
11032   assert(Op.getOperand(0).getValueType() == MVT::f64 &&
11033          Subtarget->isFPOnlySP() &&
11034          "Unexpected type for custom-lowering FP_ROUND");
11035
11036   RTLIB::Libcall LC;
11037   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
11038
11039   SDValue SrcVal = Op.getOperand(0);
11040   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
11041                      /*isSigned*/ false, SDLoc(Op)).first;
11042 }
11043
11044 bool
11045 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11046   // The ARM target isn't yet aware of offsets.
11047   return false;
11048 }
11049
11050 bool ARM::isBitFieldInvertedMask(unsigned v) {
11051   if (v == 0xffffffff)
11052     return false;
11053
11054   // there can be 1's on either or both "outsides", all the "inside"
11055   // bits must be 0's
11056   return isShiftedMask_32(~v);
11057 }
11058
11059 /// isFPImmLegal - Returns true if the target can instruction select the
11060 /// specified FP immediate natively. If false, the legalizer will
11061 /// materialize the FP immediate as a load from a constant pool.
11062 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
11063   if (!Subtarget->hasVFP3())
11064     return false;
11065   if (VT == MVT::f32)
11066     return ARM_AM::getFP32Imm(Imm) != -1;
11067   if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
11068     return ARM_AM::getFP64Imm(Imm) != -1;
11069   return false;
11070 }
11071
11072 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
11073 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
11074 /// specified in the intrinsic calls.
11075 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11076                                            const CallInst &I,
11077                                            unsigned Intrinsic) const {
11078   switch (Intrinsic) {
11079   case Intrinsic::arm_neon_vld1:
11080   case Intrinsic::arm_neon_vld2:
11081   case Intrinsic::arm_neon_vld3:
11082   case Intrinsic::arm_neon_vld4:
11083   case Intrinsic::arm_neon_vld2lane:
11084   case Intrinsic::arm_neon_vld3lane:
11085   case Intrinsic::arm_neon_vld4lane: {
11086     Info.opc = ISD::INTRINSIC_W_CHAIN;
11087     // Conservatively set memVT to the entire set of vectors loaded.
11088     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
11089     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11090     Info.ptrVal = I.getArgOperand(0);
11091     Info.offset = 0;
11092     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11093     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11094     Info.vol = false; // volatile loads with NEON intrinsics not supported
11095     Info.readMem = true;
11096     Info.writeMem = false;
11097     return true;
11098   }
11099   case Intrinsic::arm_neon_vst1:
11100   case Intrinsic::arm_neon_vst2:
11101   case Intrinsic::arm_neon_vst3:
11102   case Intrinsic::arm_neon_vst4:
11103   case Intrinsic::arm_neon_vst2lane:
11104   case Intrinsic::arm_neon_vst3lane:
11105   case Intrinsic::arm_neon_vst4lane: {
11106     Info.opc = ISD::INTRINSIC_VOID;
11107     // Conservatively set memVT to the entire set of vectors stored.
11108     unsigned NumElts = 0;
11109     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11110       Type *ArgTy = I.getArgOperand(ArgI)->getType();
11111       if (!ArgTy->isVectorTy())
11112         break;
11113       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
11114     }
11115     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11116     Info.ptrVal = I.getArgOperand(0);
11117     Info.offset = 0;
11118     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11119     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11120     Info.vol = false; // volatile stores with NEON intrinsics not supported
11121     Info.readMem = false;
11122     Info.writeMem = true;
11123     return true;
11124   }
11125   case Intrinsic::arm_ldaex:
11126   case Intrinsic::arm_ldrex: {
11127     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11128     Info.opc = ISD::INTRINSIC_W_CHAIN;
11129     Info.memVT = MVT::getVT(PtrTy->getElementType());
11130     Info.ptrVal = I.getArgOperand(0);
11131     Info.offset = 0;
11132     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11133     Info.vol = true;
11134     Info.readMem = true;
11135     Info.writeMem = false;
11136     return true;
11137   }
11138   case Intrinsic::arm_stlex:
11139   case Intrinsic::arm_strex: {
11140     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11141     Info.opc = ISD::INTRINSIC_W_CHAIN;
11142     Info.memVT = MVT::getVT(PtrTy->getElementType());
11143     Info.ptrVal = I.getArgOperand(1);
11144     Info.offset = 0;
11145     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11146     Info.vol = true;
11147     Info.readMem = false;
11148     Info.writeMem = true;
11149     return true;
11150   }
11151   case Intrinsic::arm_stlexd:
11152   case Intrinsic::arm_strexd: {
11153     Info.opc = ISD::INTRINSIC_W_CHAIN;
11154     Info.memVT = MVT::i64;
11155     Info.ptrVal = I.getArgOperand(2);
11156     Info.offset = 0;
11157     Info.align = 8;
11158     Info.vol = true;
11159     Info.readMem = false;
11160     Info.writeMem = true;
11161     return true;
11162   }
11163   case Intrinsic::arm_ldaexd:
11164   case Intrinsic::arm_ldrexd: {
11165     Info.opc = ISD::INTRINSIC_W_CHAIN;
11166     Info.memVT = MVT::i64;
11167     Info.ptrVal = I.getArgOperand(0);
11168     Info.offset = 0;
11169     Info.align = 8;
11170     Info.vol = true;
11171     Info.readMem = true;
11172     Info.writeMem = false;
11173     return true;
11174   }
11175   default:
11176     break;
11177   }
11178
11179   return false;
11180 }
11181
11182 /// \brief Returns true if it is beneficial to convert a load of a constant
11183 /// to just the constant itself.
11184 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11185                                                           Type *Ty) const {
11186   assert(Ty->isIntegerTy());
11187
11188   unsigned Bits = Ty->getPrimitiveSizeInBits();
11189   if (Bits == 0 || Bits > 32)
11190     return false;
11191   return true;
11192 }
11193
11194 bool ARMTargetLowering::hasLoadLinkedStoreConditional() const { return true; }
11195
11196 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
11197                                         ARM_MB::MemBOpt Domain) const {
11198   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11199
11200   // First, if the target has no DMB, see what fallback we can use.
11201   if (!Subtarget->hasDataBarrier()) {
11202     // Some ARMv6 cpus can support data barriers with an mcr instruction.
11203     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
11204     // here.
11205     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
11206       Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
11207       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
11208                         Builder.getInt32(0), Builder.getInt32(7),
11209                         Builder.getInt32(10), Builder.getInt32(5)};
11210       return Builder.CreateCall(MCR, args);
11211     } else {
11212       // Instead of using barriers, atomic accesses on these subtargets use
11213       // libcalls.
11214       llvm_unreachable("makeDMB on a target so old that it has no barriers");
11215     }
11216   } else {
11217     Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
11218     // Only a full system barrier exists in the M-class architectures.
11219     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
11220     Constant *CDomain = Builder.getInt32(Domain);
11221     return Builder.CreateCall(DMB, CDomain);
11222   }
11223 }
11224
11225 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11226 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11227                                          AtomicOrdering Ord, bool IsStore,
11228                                          bool IsLoad) const {
11229   if (!getInsertFencesForAtomic())
11230     return nullptr;
11231
11232   switch (Ord) {
11233   case NotAtomic:
11234   case Unordered:
11235     llvm_unreachable("Invalid fence: unordered/non-atomic");
11236   case Monotonic:
11237   case Acquire:
11238     return nullptr; // Nothing to do
11239   case SequentiallyConsistent:
11240     if (!IsStore)
11241       return nullptr; // Nothing to do
11242     /*FALLTHROUGH*/
11243   case Release:
11244   case AcquireRelease:
11245     if (Subtarget->isSwift())
11246       return makeDMB(Builder, ARM_MB::ISHST);
11247     // FIXME: add a comment with a link to documentation justifying this.
11248     else
11249       return makeDMB(Builder, ARM_MB::ISH);
11250   }
11251   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
11252 }
11253
11254 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11255                                           AtomicOrdering Ord, bool IsStore,
11256                                           bool IsLoad) const {
11257   if (!getInsertFencesForAtomic())
11258     return nullptr;
11259
11260   switch (Ord) {
11261   case NotAtomic:
11262   case Unordered:
11263     llvm_unreachable("Invalid fence: unordered/not-atomic");
11264   case Monotonic:
11265   case Release:
11266     return nullptr; // Nothing to do
11267   case Acquire:
11268   case AcquireRelease:
11269   case SequentiallyConsistent:
11270     return makeDMB(Builder, ARM_MB::ISH);
11271   }
11272   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
11273 }
11274
11275 // Loads and stores less than 64-bits are already atomic; ones above that
11276 // are doomed anyway, so defer to the default libcall and blame the OS when
11277 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11278 // anything for those.
11279 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11280   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11281   return (Size == 64) && !Subtarget->isMClass();
11282 }
11283
11284 // Loads and stores less than 64-bits are already atomic; ones above that
11285 // are doomed anyway, so defer to the default libcall and blame the OS when
11286 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11287 // anything for those.
11288 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
11289 // guarantee, see DDI0406C ARM architecture reference manual,
11290 // sections A8.8.72-74 LDRD)
11291 bool ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11292   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11293   return (Size == 64) && !Subtarget->isMClass();
11294 }
11295
11296 // For the real atomic operations, we have ldrex/strex up to 32 bits,
11297 // and up to 64 bits on the non-M profiles
11298 TargetLoweringBase::AtomicRMWExpansionKind
11299 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11300   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11301   return (Size <= (Subtarget->isMClass() ? 32U : 64U))
11302              ? AtomicRMWExpansionKind::LLSC
11303              : AtomicRMWExpansionKind::None;
11304 }
11305
11306 // This has so far only been implemented for MachO.
11307 bool ARMTargetLowering::useLoadStackGuardNode() const {
11308   return Subtarget->isTargetMachO();
11309 }
11310
11311 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
11312                                                   unsigned &Cost) const {
11313   // If we do not have NEON, vector types are not natively supported.
11314   if (!Subtarget->hasNEON())
11315     return false;
11316
11317   // Floating point values and vector values map to the same register file.
11318   // Therefore, althought we could do a store extract of a vector type, this is
11319   // better to leave at float as we have more freedom in the addressing mode for
11320   // those.
11321   if (VectorTy->isFPOrFPVectorTy())
11322     return false;
11323
11324   // If the index is unknown at compile time, this is very expensive to lower
11325   // and it is not possible to combine the store with the extract.
11326   if (!isa<ConstantInt>(Idx))
11327     return false;
11328
11329   assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
11330   unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
11331   // We can do a store + vector extract on any vector that fits perfectly in a D
11332   // or Q register.
11333   if (BitWidth == 64 || BitWidth == 128) {
11334     Cost = 0;
11335     return true;
11336   }
11337   return false;
11338 }
11339
11340 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11341                                          AtomicOrdering Ord) const {
11342   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11343   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11344   bool IsAcquire = isAtLeastAcquire(Ord);
11345
11346   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
11347   // intrinsic must return {i32, i32} and we have to recombine them into a
11348   // single i64 here.
11349   if (ValTy->getPrimitiveSizeInBits() == 64) {
11350     Intrinsic::ID Int =
11351         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
11352     Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
11353
11354     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11355     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
11356
11357     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11358     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11359     if (!Subtarget->isLittle())
11360       std::swap (Lo, Hi);
11361     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11362     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11363     return Builder.CreateOr(
11364         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
11365   }
11366
11367   Type *Tys[] = { Addr->getType() };
11368   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
11369   Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
11370
11371   return Builder.CreateTruncOrBitCast(
11372       Builder.CreateCall(Ldrex, Addr),
11373       cast<PointerType>(Addr->getType())->getElementType());
11374 }
11375
11376 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
11377                                                Value *Addr,
11378                                                AtomicOrdering Ord) const {
11379   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11380   bool IsRelease = isAtLeastRelease(Ord);
11381
11382   // Since the intrinsics must have legal type, the i64 intrinsics take two
11383   // parameters: "i32, i32". We must marshal Val into the appropriate form
11384   // before the call.
11385   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
11386     Intrinsic::ID Int =
11387         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
11388     Function *Strex = Intrinsic::getDeclaration(M, Int);
11389     Type *Int32Ty = Type::getInt32Ty(M->getContext());
11390
11391     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
11392     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
11393     if (!Subtarget->isLittle())
11394       std::swap (Lo, Hi);
11395     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11396     return Builder.CreateCall(Strex, {Lo, Hi, Addr});
11397   }
11398
11399   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
11400   Type *Tys[] = { Addr->getType() };
11401   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
11402
11403   return Builder.CreateCall(
11404       Strex, {Builder.CreateZExtOrBitCast(
11405                   Val, Strex->getFunctionType()->getParamType(0)),
11406               Addr});
11407 }
11408
11409 enum HABaseType {
11410   HA_UNKNOWN = 0,
11411   HA_FLOAT,
11412   HA_DOUBLE,
11413   HA_VECT64,
11414   HA_VECT128
11415 };
11416
11417 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
11418                                    uint64_t &Members) {
11419   if (const StructType *ST = dyn_cast<StructType>(Ty)) {
11420     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
11421       uint64_t SubMembers = 0;
11422       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
11423         return false;
11424       Members += SubMembers;
11425     }
11426   } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
11427     uint64_t SubMembers = 0;
11428     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
11429       return false;
11430     Members += SubMembers * AT->getNumElements();
11431   } else if (Ty->isFloatTy()) {
11432     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
11433       return false;
11434     Members = 1;
11435     Base = HA_FLOAT;
11436   } else if (Ty->isDoubleTy()) {
11437     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
11438       return false;
11439     Members = 1;
11440     Base = HA_DOUBLE;
11441   } else if (const VectorType *VT = dyn_cast<VectorType>(Ty)) {
11442     Members = 1;
11443     switch (Base) {
11444     case HA_FLOAT:
11445     case HA_DOUBLE:
11446       return false;
11447     case HA_VECT64:
11448       return VT->getBitWidth() == 64;
11449     case HA_VECT128:
11450       return VT->getBitWidth() == 128;
11451     case HA_UNKNOWN:
11452       switch (VT->getBitWidth()) {
11453       case 64:
11454         Base = HA_VECT64;
11455         return true;
11456       case 128:
11457         Base = HA_VECT128;
11458         return true;
11459       default:
11460         return false;
11461       }
11462     }
11463   }
11464
11465   return (Members > 0 && Members <= 4);
11466 }
11467
11468 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
11469 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
11470 /// passing according to AAPCS rules.
11471 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
11472     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11473   if (getEffectiveCallingConv(CallConv, isVarArg) !=
11474       CallingConv::ARM_AAPCS_VFP)
11475     return false;
11476
11477   HABaseType Base = HA_UNKNOWN;
11478   uint64_t Members = 0;
11479   bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
11480   DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
11481
11482   bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
11483   return IsHA || IsIntArray;
11484 }