[ARM] generate VMAXNM/VMINNM for a compare followed by a select, in safe math mode too
[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() && !TM.Options.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 (!TM.Options.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   if (Subtarget->hasNEON()) {
430     addDRTypeForNEON(MVT::v2f32);
431     addDRTypeForNEON(MVT::v8i8);
432     addDRTypeForNEON(MVT::v4i16);
433     addDRTypeForNEON(MVT::v2i32);
434     addDRTypeForNEON(MVT::v1i64);
435
436     addQRTypeForNEON(MVT::v4f32);
437     addQRTypeForNEON(MVT::v2f64);
438     addQRTypeForNEON(MVT::v16i8);
439     addQRTypeForNEON(MVT::v8i16);
440     addQRTypeForNEON(MVT::v4i32);
441     addQRTypeForNEON(MVT::v2i64);
442
443     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
444     // neither Neon nor VFP support any arithmetic operations on it.
445     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
446     // supported for v4f32.
447     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
448     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
449     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
450     // FIXME: Code duplication: FDIV and FREM are expanded always, see
451     // ARMTargetLowering::addTypeForNEON method for details.
452     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
453     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
454     // FIXME: Create unittest.
455     // In another words, find a way when "copysign" appears in DAG with vector
456     // operands.
457     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
458     // FIXME: Code duplication: SETCC has custom operation action, see
459     // ARMTargetLowering::addTypeForNEON method for details.
460     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
461     // FIXME: Create unittest for FNEG and for FABS.
462     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
463     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
464     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
465     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
466     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
467     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
468     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
469     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
470     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
471     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
472     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
473     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
474     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
475     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
476     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
477     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
478     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
479     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
480     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
481
482     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
483     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
484     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
485     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
486     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
487     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
488     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
489     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
490     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
491     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
492     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
493     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
494     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
495     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
496     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
497
498     // Mark v2f32 intrinsics.
499     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
500     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
501     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
502     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
503     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
504     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
505     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
506     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
507     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
508     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
509     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
510     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
511     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
512     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
513     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
514
515     // Neon does not support some operations on v1i64 and v2i64 types.
516     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
517     // Custom handling for some quad-vector types to detect VMULL.
518     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
519     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
520     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
521     // Custom handling for some vector types to avoid expensive expansions
522     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
523     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
524     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
525     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
526     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
527     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
528     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
529     // a destination type that is wider than the source, and nor does
530     // it have a FP_TO_[SU]INT instruction with a narrower destination than
531     // source.
532     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
533     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
534     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
535     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
536
537     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
538     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
539
540     // NEON does not have single instruction CTPOP for vectors with element
541     // types wider than 8-bits.  However, custom lowering can leverage the
542     // v8i8/v16i8 vcnt instruction.
543     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
544     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
545     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
546     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
547
548     // NEON only has FMA instructions as of VFP4.
549     if (!Subtarget->hasVFP4()) {
550       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
551       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
552     }
553
554     setTargetDAGCombine(ISD::INTRINSIC_VOID);
555     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
556     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
557     setTargetDAGCombine(ISD::SHL);
558     setTargetDAGCombine(ISD::SRL);
559     setTargetDAGCombine(ISD::SRA);
560     setTargetDAGCombine(ISD::SIGN_EXTEND);
561     setTargetDAGCombine(ISD::ZERO_EXTEND);
562     setTargetDAGCombine(ISD::ANY_EXTEND);
563     setTargetDAGCombine(ISD::SELECT_CC);
564     setTargetDAGCombine(ISD::BUILD_VECTOR);
565     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
566     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
567     setTargetDAGCombine(ISD::STORE);
568     setTargetDAGCombine(ISD::FP_TO_SINT);
569     setTargetDAGCombine(ISD::FP_TO_UINT);
570     setTargetDAGCombine(ISD::FDIV);
571     setTargetDAGCombine(ISD::LOAD);
572
573     // It is legal to extload from v4i8 to v4i16 or v4i32.
574     for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
575                    MVT::v2i32}) {
576       for (MVT VT : MVT::integer_vector_valuetypes()) {
577         setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
578         setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
579         setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
580       }
581     }
582   }
583
584   // ARM and Thumb2 support UMLAL/SMLAL.
585   if (!Subtarget->isThumb1Only())
586     setTargetDAGCombine(ISD::ADDC);
587
588   if (Subtarget->isFPOnlySP()) {
589     // When targetting a floating-point unit with only single-precision
590     // operations, f64 is legal for the few double-precision instructions which
591     // are present However, no double-precision operations other than moves,
592     // loads and stores are provided by the hardware.
593     setOperationAction(ISD::FADD,       MVT::f64, Expand);
594     setOperationAction(ISD::FSUB,       MVT::f64, Expand);
595     setOperationAction(ISD::FMUL,       MVT::f64, Expand);
596     setOperationAction(ISD::FMA,        MVT::f64, Expand);
597     setOperationAction(ISD::FDIV,       MVT::f64, Expand);
598     setOperationAction(ISD::FREM,       MVT::f64, Expand);
599     setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
600     setOperationAction(ISD::FGETSIGN,   MVT::f64, Expand);
601     setOperationAction(ISD::FNEG,       MVT::f64, Expand);
602     setOperationAction(ISD::FABS,       MVT::f64, Expand);
603     setOperationAction(ISD::FSQRT,      MVT::f64, Expand);
604     setOperationAction(ISD::FSIN,       MVT::f64, Expand);
605     setOperationAction(ISD::FCOS,       MVT::f64, Expand);
606     setOperationAction(ISD::FPOWI,      MVT::f64, Expand);
607     setOperationAction(ISD::FPOW,       MVT::f64, Expand);
608     setOperationAction(ISD::FLOG,       MVT::f64, Expand);
609     setOperationAction(ISD::FLOG2,      MVT::f64, Expand);
610     setOperationAction(ISD::FLOG10,     MVT::f64, Expand);
611     setOperationAction(ISD::FEXP,       MVT::f64, Expand);
612     setOperationAction(ISD::FEXP2,      MVT::f64, Expand);
613     setOperationAction(ISD::FCEIL,      MVT::f64, Expand);
614     setOperationAction(ISD::FTRUNC,     MVT::f64, Expand);
615     setOperationAction(ISD::FRINT,      MVT::f64, Expand);
616     setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
617     setOperationAction(ISD::FFLOOR,     MVT::f64, Expand);
618     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
619     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
620     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
621     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
622     setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
623     setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
624     setOperationAction(ISD::FP_ROUND,   MVT::f32, Custom);
625     setOperationAction(ISD::FP_EXTEND,  MVT::f64, Custom);
626   }
627
628   computeRegisterProperties(Subtarget->getRegisterInfo());
629
630   // ARM does not have floating-point extending loads.
631   for (MVT VT : MVT::fp_valuetypes()) {
632     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
633     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
634   }
635
636   // ... or truncating stores
637   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
638   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
639   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
640
641   // ARM does not have i1 sign extending load.
642   for (MVT VT : MVT::integer_valuetypes())
643     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
644
645   // ARM supports all 4 flavors of integer indexed load / store.
646   if (!Subtarget->isThumb1Only()) {
647     for (unsigned im = (unsigned)ISD::PRE_INC;
648          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
649       setIndexedLoadAction(im,  MVT::i1,  Legal);
650       setIndexedLoadAction(im,  MVT::i8,  Legal);
651       setIndexedLoadAction(im,  MVT::i16, Legal);
652       setIndexedLoadAction(im,  MVT::i32, Legal);
653       setIndexedStoreAction(im, MVT::i1,  Legal);
654       setIndexedStoreAction(im, MVT::i8,  Legal);
655       setIndexedStoreAction(im, MVT::i16, Legal);
656       setIndexedStoreAction(im, MVT::i32, Legal);
657     }
658   }
659
660   setOperationAction(ISD::SADDO, MVT::i32, Custom);
661   setOperationAction(ISD::UADDO, MVT::i32, Custom);
662   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
663   setOperationAction(ISD::USUBO, MVT::i32, Custom);
664
665   // i64 operation support.
666   setOperationAction(ISD::MUL,     MVT::i64, Expand);
667   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
668   if (Subtarget->isThumb1Only()) {
669     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
670     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
671   }
672   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
673       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
674     setOperationAction(ISD::MULHS, MVT::i32, Expand);
675
676   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
677   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
678   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
679   setOperationAction(ISD::SRL,       MVT::i64, Custom);
680   setOperationAction(ISD::SRA,       MVT::i64, Custom);
681
682   if (!Subtarget->isThumb1Only()) {
683     // FIXME: We should do this for Thumb1 as well.
684     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
685     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
686     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
687     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
688   }
689
690   // ARM does not have ROTL.
691   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
692   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
693   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
694   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
695     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
696
697   // These just redirect to CTTZ and CTLZ on ARM.
698   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
699   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
700
701   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
702
703   // Only ARMv6 has BSWAP.
704   if (!Subtarget->hasV6Ops())
705     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
706
707   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
708       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
709     // These are expanded into libcalls if the cpu doesn't have HW divider.
710     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
711     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
712   }
713
714   // FIXME: Also set divmod for SREM on EABI
715   setOperationAction(ISD::SREM,  MVT::i32, Expand);
716   setOperationAction(ISD::UREM,  MVT::i32, Expand);
717   // Register based DivRem for AEABI (RTABI 4.2)
718   if (Subtarget->isTargetAEABI()) {
719     setLibcallName(RTLIB::SDIVREM_I8,  "__aeabi_idivmod");
720     setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
721     setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
722     setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
723     setLibcallName(RTLIB::UDIVREM_I8,  "__aeabi_uidivmod");
724     setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
725     setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
726     setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
727
728     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
729     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
730     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
731     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
732     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
733     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
734     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
735     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
736
737     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
738     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
739   } else {
740     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
741     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
742   }
743
744   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
745   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
746   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
747   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
748   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
749
750   setOperationAction(ISD::TRAP, MVT::Other, Legal);
751
752   // Use the default implementation.
753   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
754   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
755   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
756   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
757   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
758   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
759
760   if (!Subtarget->isTargetMachO()) {
761     // Non-MachO platforms may return values in these registers via the
762     // personality function.
763     setExceptionPointerRegister(ARM::R0);
764     setExceptionSelectorRegister(ARM::R1);
765   }
766
767   if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
768     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
769   else
770     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
771
772   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
773   // the default expansion. If we are targeting a single threaded system,
774   // then set them all for expand so we can lower them later into their
775   // non-atomic form.
776   if (TM.Options.ThreadModel == ThreadModel::Single)
777     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
778   else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
779     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
780     // to ldrex/strex loops already.
781     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
782
783     // On v8, we have particularly efficient implementations of atomic fences
784     // if they can be combined with nearby atomic loads and stores.
785     if (!Subtarget->hasV8Ops()) {
786       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
787       setInsertFencesForAtomic(true);
788     }
789   } else {
790     // If there's anything we can use as a barrier, go through custom lowering
791     // for ATOMIC_FENCE.
792     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
793                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
794
795     // Set them all for expansion, which will force libcalls.
796     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
797     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
798     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
799     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
800     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
801     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
802     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
803     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
804     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
805     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
806     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
807     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
808     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
809     // Unordered/Monotonic case.
810     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
811     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
812   }
813
814   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
815
816   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
817   if (!Subtarget->hasV6Ops()) {
818     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
819     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
820   }
821   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
822
823   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
824       !Subtarget->isThumb1Only()) {
825     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
826     // iff target supports vfp2.
827     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
828     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
829   }
830
831   // We want to custom lower some of our intrinsics.
832   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
833   if (Subtarget->isTargetDarwin()) {
834     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
835     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
836     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
837   }
838
839   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
840   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
841   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
842   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
843   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
844   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
845   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
846   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
847   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
848
849   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
850   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
851   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
852   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
853   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
854
855   // We don't support sin/cos/fmod/copysign/pow
856   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
857   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
858   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
859   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
860   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
861   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
862   setOperationAction(ISD::FREM,      MVT::f64, Expand);
863   setOperationAction(ISD::FREM,      MVT::f32, Expand);
864   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
865       !Subtarget->isThumb1Only()) {
866     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
867     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
868   }
869   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
870   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
871
872   if (!Subtarget->hasVFP4()) {
873     setOperationAction(ISD::FMA, MVT::f64, Expand);
874     setOperationAction(ISD::FMA, MVT::f32, Expand);
875   }
876
877   // Various VFP goodness
878   if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
879     // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
880     if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
881       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
882       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
883     }
884
885     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
886     if (!Subtarget->hasFP16()) {
887       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
888       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
889     }
890   }
891
892   // Combine sin / cos into one node or libcall if possible.
893   if (Subtarget->hasSinCos()) {
894     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
895     setLibcallName(RTLIB::SINCOS_F64, "sincos");
896     if (Subtarget->getTargetTriple().isiOS()) {
897       // For iOS, we don't want to the normal expansion of a libcall to
898       // sincos. We want to issue a libcall to __sincos_stret.
899       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
900       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
901     }
902   }
903
904   // FP-ARMv8 implements a lot of rounding-like FP operations.
905   if (Subtarget->hasFPARMv8()) {
906     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
907     setOperationAction(ISD::FCEIL, MVT::f32, Legal);
908     setOperationAction(ISD::FROUND, MVT::f32, Legal);
909     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
910     setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
911     setOperationAction(ISD::FRINT, MVT::f32, Legal);
912     if (!Subtarget->isFPOnlySP()) {
913       setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
914       setOperationAction(ISD::FCEIL, MVT::f64, Legal);
915       setOperationAction(ISD::FROUND, MVT::f64, Legal);
916       setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
917       setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
918       setOperationAction(ISD::FRINT, MVT::f64, Legal);
919     }
920   }
921   // We have target-specific dag combine patterns for the following nodes:
922   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
923   setTargetDAGCombine(ISD::ADD);
924   setTargetDAGCombine(ISD::SUB);
925   setTargetDAGCombine(ISD::MUL);
926   setTargetDAGCombine(ISD::AND);
927   setTargetDAGCombine(ISD::OR);
928   setTargetDAGCombine(ISD::XOR);
929
930   if (Subtarget->hasV6Ops())
931     setTargetDAGCombine(ISD::SRL);
932
933   setStackPointerRegisterToSaveRestore(ARM::SP);
934
935   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
936       !Subtarget->hasVFP2())
937     setSchedulingPreference(Sched::RegPressure);
938   else
939     setSchedulingPreference(Sched::Hybrid);
940
941   //// temporary - rewrite interface to use type
942   MaxStoresPerMemset = 8;
943   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
944   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
945   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
946   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
947   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
948
949   // On ARM arguments smaller than 4 bytes are extended, so all arguments
950   // are at least 4 bytes aligned.
951   setMinStackArgumentAlignment(4);
952
953   // Prefer likely predicted branches to selects on out-of-order cores.
954   PredictableSelectIsExpensive = Subtarget->isLikeA9();
955
956   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
957 }
958
959 // FIXME: It might make sense to define the representative register class as the
960 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
961 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
962 // SPR's representative would be DPR_VFP2. This should work well if register
963 // pressure tracking were modified such that a register use would increment the
964 // pressure of the register class's representative and all of it's super
965 // classes' representatives transitively. We have not implemented this because
966 // of the difficulty prior to coalescing of modeling operand register classes
967 // due to the common occurrence of cross class copies and subregister insertions
968 // and extractions.
969 std::pair<const TargetRegisterClass *, uint8_t>
970 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
971                                            MVT VT) const {
972   const TargetRegisterClass *RRC = nullptr;
973   uint8_t Cost = 1;
974   switch (VT.SimpleTy) {
975   default:
976     return TargetLowering::findRepresentativeClass(TRI, VT);
977   // Use DPR as representative register class for all floating point
978   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
979   // the cost is 1 for both f32 and f64.
980   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
981   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
982     RRC = &ARM::DPRRegClass;
983     // When NEON is used for SP, only half of the register file is available
984     // because operations that define both SP and DP results will be constrained
985     // to the VFP2 class (D0-D15). We currently model this constraint prior to
986     // coalescing by double-counting the SP regs. See the FIXME above.
987     if (Subtarget->useNEONForSinglePrecisionFP())
988       Cost = 2;
989     break;
990   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
991   case MVT::v4f32: case MVT::v2f64:
992     RRC = &ARM::DPRRegClass;
993     Cost = 2;
994     break;
995   case MVT::v4i64:
996     RRC = &ARM::DPRRegClass;
997     Cost = 4;
998     break;
999   case MVT::v8i64:
1000     RRC = &ARM::DPRRegClass;
1001     Cost = 8;
1002     break;
1003   }
1004   return std::make_pair(RRC, Cost);
1005 }
1006
1007 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1008   switch (Opcode) {
1009   default: return nullptr;
1010   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1011   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1012   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1013   case ARMISD::CALL:          return "ARMISD::CALL";
1014   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1015   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1016   case ARMISD::tCALL:         return "ARMISD::tCALL";
1017   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1018   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1019   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1020   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1021   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1022   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1023   case ARMISD::CMP:           return "ARMISD::CMP";
1024   case ARMISD::CMN:           return "ARMISD::CMN";
1025   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1026   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1027   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1028   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1029   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1030
1031   case ARMISD::CMOV:          return "ARMISD::CMOV";
1032
1033   case ARMISD::RBIT:          return "ARMISD::RBIT";
1034
1035   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1036   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1037   case ARMISD::RRX:           return "ARMISD::RRX";
1038
1039   case ARMISD::ADDC:          return "ARMISD::ADDC";
1040   case ARMISD::ADDE:          return "ARMISD::ADDE";
1041   case ARMISD::SUBC:          return "ARMISD::SUBC";
1042   case ARMISD::SUBE:          return "ARMISD::SUBE";
1043
1044   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1045   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1046
1047   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1048   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
1049
1050   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1051
1052   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1053
1054   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1055
1056   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1057
1058   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1059
1060   case ARMISD::WIN__CHKSTK:   return "ARMISD:::WIN__CHKSTK";
1061
1062   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1063   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1064   case ARMISD::VCGE:          return "ARMISD::VCGE";
1065   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1066   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1067   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1068   case ARMISD::VCGT:          return "ARMISD::VCGT";
1069   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1070   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1071   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1072   case ARMISD::VTST:          return "ARMISD::VTST";
1073
1074   case ARMISD::VSHL:          return "ARMISD::VSHL";
1075   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1076   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1077   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1078   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1079   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1080   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1081   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1082   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1083   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1084   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1085   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1086   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1087   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1088   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1089   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1090   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1091   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1092   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1093   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1094   case ARMISD::VDUP:          return "ARMISD::VDUP";
1095   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1096   case ARMISD::VEXT:          return "ARMISD::VEXT";
1097   case ARMISD::VREV64:        return "ARMISD::VREV64";
1098   case ARMISD::VREV32:        return "ARMISD::VREV32";
1099   case ARMISD::VREV16:        return "ARMISD::VREV16";
1100   case ARMISD::VZIP:          return "ARMISD::VZIP";
1101   case ARMISD::VUZP:          return "ARMISD::VUZP";
1102   case ARMISD::VTRN:          return "ARMISD::VTRN";
1103   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1104   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1105   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1106   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1107   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1108   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1109   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1110   case ARMISD::FMAX:          return "ARMISD::FMAX";
1111   case ARMISD::FMIN:          return "ARMISD::FMIN";
1112   case ARMISD::VMAXNM:        return "ARMISD::VMAX";
1113   case ARMISD::VMINNM:        return "ARMISD::VMIN";
1114   case ARMISD::BFI:           return "ARMISD::BFI";
1115   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1116   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1117   case ARMISD::VBSL:          return "ARMISD::VBSL";
1118   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1119   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1120   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1121   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1122   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1123   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1124   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1125   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1126   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1127   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1128   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1129   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1130   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1131   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1132   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1133   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1134   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1135   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1136   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1137   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1138   }
1139 }
1140
1141 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1142   if (!VT.isVector()) return getPointerTy();
1143   return VT.changeVectorElementTypeToInteger();
1144 }
1145
1146 /// getRegClassFor - Return the register class that should be used for the
1147 /// specified value type.
1148 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1149   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1150   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1151   // load / store 4 to 8 consecutive D registers.
1152   if (Subtarget->hasNEON()) {
1153     if (VT == MVT::v4i64)
1154       return &ARM::QQPRRegClass;
1155     if (VT == MVT::v8i64)
1156       return &ARM::QQQQPRRegClass;
1157   }
1158   return TargetLowering::getRegClassFor(VT);
1159 }
1160
1161 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1162 // source/dest is aligned and the copy size is large enough. We therefore want
1163 // to align such objects passed to memory intrinsics.
1164 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1165                                                unsigned &PrefAlign) const {
1166   if (!isa<MemIntrinsic>(CI))
1167     return false;
1168   MinSize = 8;
1169   // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1170   // cycle faster than 4-byte aligned LDM.
1171   PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1172   return true;
1173 }
1174
1175 // Create a fast isel object.
1176 FastISel *
1177 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1178                                   const TargetLibraryInfo *libInfo) const {
1179   return ARM::createFastISel(funcInfo, libInfo);
1180 }
1181
1182 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1183   unsigned NumVals = N->getNumValues();
1184   if (!NumVals)
1185     return Sched::RegPressure;
1186
1187   for (unsigned i = 0; i != NumVals; ++i) {
1188     EVT VT = N->getValueType(i);
1189     if (VT == MVT::Glue || VT == MVT::Other)
1190       continue;
1191     if (VT.isFloatingPoint() || VT.isVector())
1192       return Sched::ILP;
1193   }
1194
1195   if (!N->isMachineOpcode())
1196     return Sched::RegPressure;
1197
1198   // Load are scheduled for latency even if there instruction itinerary
1199   // is not available.
1200   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1201   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1202
1203   if (MCID.getNumDefs() == 0)
1204     return Sched::RegPressure;
1205   if (!Itins->isEmpty() &&
1206       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1207     return Sched::ILP;
1208
1209   return Sched::RegPressure;
1210 }
1211
1212 //===----------------------------------------------------------------------===//
1213 // Lowering Code
1214 //===----------------------------------------------------------------------===//
1215
1216 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1217 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1218   switch (CC) {
1219   default: llvm_unreachable("Unknown condition code!");
1220   case ISD::SETNE:  return ARMCC::NE;
1221   case ISD::SETEQ:  return ARMCC::EQ;
1222   case ISD::SETGT:  return ARMCC::GT;
1223   case ISD::SETGE:  return ARMCC::GE;
1224   case ISD::SETLT:  return ARMCC::LT;
1225   case ISD::SETLE:  return ARMCC::LE;
1226   case ISD::SETUGT: return ARMCC::HI;
1227   case ISD::SETUGE: return ARMCC::HS;
1228   case ISD::SETULT: return ARMCC::LO;
1229   case ISD::SETULE: return ARMCC::LS;
1230   }
1231 }
1232
1233 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1234 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1235                         ARMCC::CondCodes &CondCode2) {
1236   CondCode2 = ARMCC::AL;
1237   switch (CC) {
1238   default: llvm_unreachable("Unknown FP condition!");
1239   case ISD::SETEQ:
1240   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1241   case ISD::SETGT:
1242   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1243   case ISD::SETGE:
1244   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1245   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1246   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1247   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1248   case ISD::SETO:   CondCode = ARMCC::VC; break;
1249   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1250   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1251   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1252   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1253   case ISD::SETLT:
1254   case ISD::SETULT: CondCode = ARMCC::LT; break;
1255   case ISD::SETLE:
1256   case ISD::SETULE: CondCode = ARMCC::LE; break;
1257   case ISD::SETNE:
1258   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1259   }
1260 }
1261
1262 //===----------------------------------------------------------------------===//
1263 //                      Calling Convention Implementation
1264 //===----------------------------------------------------------------------===//
1265
1266 #include "ARMGenCallingConv.inc"
1267
1268 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1269 /// account presence of floating point hardware and calling convention
1270 /// limitations, such as support for variadic functions.
1271 CallingConv::ID
1272 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1273                                            bool isVarArg) const {
1274   switch (CC) {
1275   default:
1276     llvm_unreachable("Unsupported calling convention");
1277   case CallingConv::ARM_AAPCS:
1278   case CallingConv::ARM_APCS:
1279   case CallingConv::GHC:
1280     return CC;
1281   case CallingConv::ARM_AAPCS_VFP:
1282     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1283   case CallingConv::C:
1284     if (!Subtarget->isAAPCS_ABI())
1285       return CallingConv::ARM_APCS;
1286     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1287              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1288              !isVarArg)
1289       return CallingConv::ARM_AAPCS_VFP;
1290     else
1291       return CallingConv::ARM_AAPCS;
1292   case CallingConv::Fast:
1293     if (!Subtarget->isAAPCS_ABI()) {
1294       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1295         return CallingConv::Fast;
1296       return CallingConv::ARM_APCS;
1297     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1298       return CallingConv::ARM_AAPCS_VFP;
1299     else
1300       return CallingConv::ARM_AAPCS;
1301   }
1302 }
1303
1304 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1305 /// CallingConvention.
1306 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1307                                                  bool Return,
1308                                                  bool isVarArg) const {
1309   switch (getEffectiveCallingConv(CC, isVarArg)) {
1310   default:
1311     llvm_unreachable("Unsupported calling convention");
1312   case CallingConv::ARM_APCS:
1313     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1314   case CallingConv::ARM_AAPCS:
1315     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1316   case CallingConv::ARM_AAPCS_VFP:
1317     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1318   case CallingConv::Fast:
1319     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1320   case CallingConv::GHC:
1321     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1322   }
1323 }
1324
1325 /// LowerCallResult - Lower the result values of a call into the
1326 /// appropriate copies out of appropriate physical registers.
1327 SDValue
1328 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1329                                    CallingConv::ID CallConv, bool isVarArg,
1330                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1331                                    SDLoc dl, SelectionDAG &DAG,
1332                                    SmallVectorImpl<SDValue> &InVals,
1333                                    bool isThisReturn, SDValue ThisVal) const {
1334
1335   // Assign locations to each value returned by this call.
1336   SmallVector<CCValAssign, 16> RVLocs;
1337   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1338                     *DAG.getContext(), Call);
1339   CCInfo.AnalyzeCallResult(Ins,
1340                            CCAssignFnForNode(CallConv, /* Return*/ true,
1341                                              isVarArg));
1342
1343   // Copy all of the result registers out of their specified physreg.
1344   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1345     CCValAssign VA = RVLocs[i];
1346
1347     // Pass 'this' value directly from the argument to return value, to avoid
1348     // reg unit interference
1349     if (i == 0 && isThisReturn) {
1350       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1351              "unexpected return calling convention register assignment");
1352       InVals.push_back(ThisVal);
1353       continue;
1354     }
1355
1356     SDValue Val;
1357     if (VA.needsCustom()) {
1358       // Handle f64 or half of a v2f64.
1359       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1360                                       InFlag);
1361       Chain = Lo.getValue(1);
1362       InFlag = Lo.getValue(2);
1363       VA = RVLocs[++i]; // skip ahead to next loc
1364       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1365                                       InFlag);
1366       Chain = Hi.getValue(1);
1367       InFlag = Hi.getValue(2);
1368       if (!Subtarget->isLittle())
1369         std::swap (Lo, Hi);
1370       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1371
1372       if (VA.getLocVT() == MVT::v2f64) {
1373         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1374         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1375                           DAG.getConstant(0, dl, MVT::i32));
1376
1377         VA = RVLocs[++i]; // skip ahead to next loc
1378         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1379         Chain = Lo.getValue(1);
1380         InFlag = Lo.getValue(2);
1381         VA = RVLocs[++i]; // skip ahead to next loc
1382         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1383         Chain = Hi.getValue(1);
1384         InFlag = Hi.getValue(2);
1385         if (!Subtarget->isLittle())
1386           std::swap (Lo, Hi);
1387         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1388         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1389                           DAG.getConstant(1, dl, MVT::i32));
1390       }
1391     } else {
1392       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1393                                InFlag);
1394       Chain = Val.getValue(1);
1395       InFlag = Val.getValue(2);
1396     }
1397
1398     switch (VA.getLocInfo()) {
1399     default: llvm_unreachable("Unknown loc info!");
1400     case CCValAssign::Full: break;
1401     case CCValAssign::BCvt:
1402       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1403       break;
1404     }
1405
1406     InVals.push_back(Val);
1407   }
1408
1409   return Chain;
1410 }
1411
1412 /// LowerMemOpCallTo - Store the argument to the stack.
1413 SDValue
1414 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1415                                     SDValue StackPtr, SDValue Arg,
1416                                     SDLoc dl, SelectionDAG &DAG,
1417                                     const CCValAssign &VA,
1418                                     ISD::ArgFlagsTy Flags) const {
1419   unsigned LocMemOffset = VA.getLocMemOffset();
1420   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1421   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1422   return DAG.getStore(Chain, dl, Arg, PtrOff,
1423                       MachinePointerInfo::getStack(LocMemOffset),
1424                       false, false, 0);
1425 }
1426
1427 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1428                                          SDValue Chain, SDValue &Arg,
1429                                          RegsToPassVector &RegsToPass,
1430                                          CCValAssign &VA, CCValAssign &NextVA,
1431                                          SDValue &StackPtr,
1432                                          SmallVectorImpl<SDValue> &MemOpChains,
1433                                          ISD::ArgFlagsTy Flags) const {
1434
1435   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1436                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1437   unsigned id = Subtarget->isLittle() ? 0 : 1;
1438   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1439
1440   if (NextVA.isRegLoc())
1441     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1442   else {
1443     assert(NextVA.isMemLoc());
1444     if (!StackPtr.getNode())
1445       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1446
1447     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1448                                            dl, DAG, NextVA,
1449                                            Flags));
1450   }
1451 }
1452
1453 /// LowerCall - Lowering a call into a callseq_start <-
1454 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1455 /// nodes.
1456 SDValue
1457 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1458                              SmallVectorImpl<SDValue> &InVals) const {
1459   SelectionDAG &DAG                     = CLI.DAG;
1460   SDLoc &dl                             = CLI.DL;
1461   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1462   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1463   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1464   SDValue Chain                         = CLI.Chain;
1465   SDValue Callee                        = CLI.Callee;
1466   bool &isTailCall                      = CLI.IsTailCall;
1467   CallingConv::ID CallConv              = CLI.CallConv;
1468   bool doesNotRet                       = CLI.DoesNotReturn;
1469   bool isVarArg                         = CLI.IsVarArg;
1470
1471   MachineFunction &MF = DAG.getMachineFunction();
1472   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1473   bool isThisReturn   = false;
1474   bool isSibCall      = false;
1475
1476   // Disable tail calls if they're not supported.
1477   if (!Subtarget->supportsTailCall() || MF.getTarget().Options.DisableTailCalls)
1478     isTailCall = false;
1479
1480   if (isTailCall) {
1481     // Check if it's really possible to do a tail call.
1482     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1483                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1484                                                    Outs, OutVals, Ins, DAG);
1485     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1486       report_fatal_error("failed to perform tail call elimination on a call "
1487                          "site marked musttail");
1488     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1489     // detected sibcalls.
1490     if (isTailCall) {
1491       ++NumTailCalls;
1492       isSibCall = true;
1493     }
1494   }
1495
1496   // Analyze operands of the call, assigning locations to each operand.
1497   SmallVector<CCValAssign, 16> ArgLocs;
1498   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1499                     *DAG.getContext(), Call);
1500   CCInfo.AnalyzeCallOperands(Outs,
1501                              CCAssignFnForNode(CallConv, /* Return*/ false,
1502                                                isVarArg));
1503
1504   // Get a count of how many bytes are to be pushed on the stack.
1505   unsigned NumBytes = CCInfo.getNextStackOffset();
1506
1507   // For tail calls, memory operands are available in our caller's stack.
1508   if (isSibCall)
1509     NumBytes = 0;
1510
1511   // Adjust the stack pointer for the new arguments...
1512   // These operations are automatically eliminated by the prolog/epilog pass
1513   if (!isSibCall)
1514     Chain = DAG.getCALLSEQ_START(Chain,
1515                                  DAG.getIntPtrConstant(NumBytes, dl, true), dl);
1516
1517   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1518
1519   RegsToPassVector RegsToPass;
1520   SmallVector<SDValue, 8> MemOpChains;
1521
1522   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1523   // of tail call optimization, arguments are handled later.
1524   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1525        i != e;
1526        ++i, ++realArgIdx) {
1527     CCValAssign &VA = ArgLocs[i];
1528     SDValue Arg = OutVals[realArgIdx];
1529     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1530     bool isByVal = Flags.isByVal();
1531
1532     // Promote the value if needed.
1533     switch (VA.getLocInfo()) {
1534     default: llvm_unreachable("Unknown loc info!");
1535     case CCValAssign::Full: break;
1536     case CCValAssign::SExt:
1537       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1538       break;
1539     case CCValAssign::ZExt:
1540       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1541       break;
1542     case CCValAssign::AExt:
1543       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1544       break;
1545     case CCValAssign::BCvt:
1546       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1547       break;
1548     }
1549
1550     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1551     if (VA.needsCustom()) {
1552       if (VA.getLocVT() == MVT::v2f64) {
1553         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1554                                   DAG.getConstant(0, dl, MVT::i32));
1555         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1556                                   DAG.getConstant(1, dl, MVT::i32));
1557
1558         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1559                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1560
1561         VA = ArgLocs[++i]; // skip ahead to next loc
1562         if (VA.isRegLoc()) {
1563           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1564                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1565         } else {
1566           assert(VA.isMemLoc());
1567
1568           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1569                                                  dl, DAG, VA, Flags));
1570         }
1571       } else {
1572         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1573                          StackPtr, MemOpChains, Flags);
1574       }
1575     } else if (VA.isRegLoc()) {
1576       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1577         assert(VA.getLocVT() == MVT::i32 &&
1578                "unexpected calling convention register assignment");
1579         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1580                "unexpected use of 'returned'");
1581         isThisReturn = true;
1582       }
1583       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1584     } else if (isByVal) {
1585       assert(VA.isMemLoc());
1586       unsigned offset = 0;
1587
1588       // True if this byval aggregate will be split between registers
1589       // and memory.
1590       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1591       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1592
1593       if (CurByValIdx < ByValArgsCount) {
1594
1595         unsigned RegBegin, RegEnd;
1596         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1597
1598         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1599         unsigned int i, j;
1600         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1601           SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1602           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1603           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1604                                      MachinePointerInfo(),
1605                                      false, false, false,
1606                                      DAG.InferPtrAlignment(AddArg));
1607           MemOpChains.push_back(Load.getValue(1));
1608           RegsToPass.push_back(std::make_pair(j, Load));
1609         }
1610
1611         // If parameter size outsides register area, "offset" value
1612         // helps us to calculate stack slot for remained part properly.
1613         offset = RegEnd - RegBegin;
1614
1615         CCInfo.nextInRegsParam();
1616       }
1617
1618       if (Flags.getByValSize() > 4*offset) {
1619         unsigned LocMemOffset = VA.getLocMemOffset();
1620         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1621         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1622                                   StkPtrOff);
1623         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1624         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1625         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1626                                            MVT::i32);
1627         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1628                                             MVT::i32);
1629
1630         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1631         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1632         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1633                                           Ops));
1634       }
1635     } else if (!isSibCall) {
1636       assert(VA.isMemLoc());
1637
1638       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1639                                              dl, DAG, VA, Flags));
1640     }
1641   }
1642
1643   if (!MemOpChains.empty())
1644     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1645
1646   // Build a sequence of copy-to-reg nodes chained together with token chain
1647   // and flag operands which copy the outgoing args into the appropriate regs.
1648   SDValue InFlag;
1649   // Tail call byval lowering might overwrite argument registers so in case of
1650   // tail call optimization the copies to registers are lowered later.
1651   if (!isTailCall)
1652     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1653       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1654                                RegsToPass[i].second, InFlag);
1655       InFlag = Chain.getValue(1);
1656     }
1657
1658   // For tail calls lower the arguments to the 'real' stack slot.
1659   if (isTailCall) {
1660     // Force all the incoming stack arguments to be loaded from the stack
1661     // before any new outgoing arguments are stored to the stack, because the
1662     // outgoing stack slots may alias the incoming argument stack slots, and
1663     // the alias isn't otherwise explicit. This is slightly more conservative
1664     // than necessary, because it means that each store effectively depends
1665     // on every argument instead of just those arguments it would clobber.
1666
1667     // Do not flag preceding copytoreg stuff together with the following stuff.
1668     InFlag = SDValue();
1669     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1670       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1671                                RegsToPass[i].second, InFlag);
1672       InFlag = Chain.getValue(1);
1673     }
1674     InFlag = SDValue();
1675   }
1676
1677   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1678   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1679   // node so that legalize doesn't hack it.
1680   bool isDirect = false;
1681   bool isARMFunc = false;
1682   bool isLocalARMFunc = false;
1683   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1684
1685   if (EnableARMLongCalls) {
1686     assert((Subtarget->isTargetWindows() ||
1687             getTargetMachine().getRelocationModel() == Reloc::Static) &&
1688            "long-calls with non-static relocation model!");
1689     // Handle a global address or an external symbol. If it's not one of
1690     // those, the target's already in a register, so we don't need to do
1691     // anything extra.
1692     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1693       const GlobalValue *GV = G->getGlobal();
1694       // Create a constant pool entry for the callee address
1695       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1696       ARMConstantPoolValue *CPV =
1697         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1698
1699       // Get the address of the callee into a register
1700       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1701       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1702       Callee = DAG.getLoad(getPointerTy(), dl,
1703                            DAG.getEntryNode(), CPAddr,
1704                            MachinePointerInfo::getConstantPool(),
1705                            false, false, false, 0);
1706     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1707       const char *Sym = S->getSymbol();
1708
1709       // Create a constant pool entry for the callee address
1710       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1711       ARMConstantPoolValue *CPV =
1712         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1713                                       ARMPCLabelIndex, 0);
1714       // Get the address of the callee into a register
1715       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1716       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1717       Callee = DAG.getLoad(getPointerTy(), dl,
1718                            DAG.getEntryNode(), CPAddr,
1719                            MachinePointerInfo::getConstantPool(),
1720                            false, false, false, 0);
1721     }
1722   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1723     const GlobalValue *GV = G->getGlobal();
1724     isDirect = true;
1725     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1726     bool isStub = (isExt && Subtarget->isTargetMachO()) &&
1727                    getTargetMachine().getRelocationModel() != Reloc::Static;
1728     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1729     // ARM call to a local ARM function is predicable.
1730     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1731     // tBX takes a register source operand.
1732     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1733       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1734       Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1735                            DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
1736                                                       0, ARMII::MO_NONLAZY));
1737       Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
1738                            MachinePointerInfo::getGOT(), false, false, true, 0);
1739     } else if (Subtarget->isTargetCOFF()) {
1740       assert(Subtarget->isTargetWindows() &&
1741              "Windows is the only supported COFF target");
1742       unsigned TargetFlags = GV->hasDLLImportStorageClass()
1743                                  ? ARMII::MO_DLLIMPORT
1744                                  : ARMII::MO_NO_FLAG;
1745       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), /*Offset=*/0,
1746                                           TargetFlags);
1747       if (GV->hasDLLImportStorageClass())
1748         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
1749                              DAG.getNode(ARMISD::Wrapper, dl, getPointerTy(),
1750                                          Callee), MachinePointerInfo::getGOT(),
1751                              false, false, false, 0);
1752     } else {
1753       // On ELF targets for PIC code, direct calls should go through the PLT
1754       unsigned OpFlags = 0;
1755       if (Subtarget->isTargetELF() &&
1756           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1757         OpFlags = ARMII::MO_PLT;
1758       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1759     }
1760   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1761     isDirect = true;
1762     bool isStub = Subtarget->isTargetMachO() &&
1763                   getTargetMachine().getRelocationModel() != Reloc::Static;
1764     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1765     // tBX takes a register source operand.
1766     const char *Sym = S->getSymbol();
1767     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1768       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1769       ARMConstantPoolValue *CPV =
1770         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1771                                       ARMPCLabelIndex, 4);
1772       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1773       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1774       Callee = DAG.getLoad(getPointerTy(), dl,
1775                            DAG.getEntryNode(), CPAddr,
1776                            MachinePointerInfo::getConstantPool(),
1777                            false, false, false, 0);
1778       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
1779       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1780                            getPointerTy(), Callee, PICLabel);
1781     } else {
1782       unsigned OpFlags = 0;
1783       // On ELF targets for PIC code, direct calls should go through the PLT
1784       if (Subtarget->isTargetELF() &&
1785                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1786         OpFlags = ARMII::MO_PLT;
1787       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1788     }
1789   }
1790
1791   // FIXME: handle tail calls differently.
1792   unsigned CallOpc;
1793   bool HasMinSizeAttr = MF.getFunction()->hasFnAttribute(Attribute::MinSize);
1794   if (Subtarget->isThumb()) {
1795     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1796       CallOpc = ARMISD::CALL_NOLINK;
1797     else
1798       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1799   } else {
1800     if (!isDirect && !Subtarget->hasV5TOps())
1801       CallOpc = ARMISD::CALL_NOLINK;
1802     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1803                // Emit regular call when code size is the priority
1804                !HasMinSizeAttr)
1805       // "mov lr, pc; b _foo" to avoid confusing the RSP
1806       CallOpc = ARMISD::CALL_NOLINK;
1807     else
1808       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1809   }
1810
1811   std::vector<SDValue> Ops;
1812   Ops.push_back(Chain);
1813   Ops.push_back(Callee);
1814
1815   // Add argument registers to the end of the list so that they are known live
1816   // into the call.
1817   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1818     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1819                                   RegsToPass[i].second.getValueType()));
1820
1821   // Add a register mask operand representing the call-preserved registers.
1822   if (!isTailCall) {
1823     const uint32_t *Mask;
1824     const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
1825     if (isThisReturn) {
1826       // For 'this' returns, use the R0-preserving mask if applicable
1827       Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
1828       if (!Mask) {
1829         // Set isThisReturn to false if the calling convention is not one that
1830         // allows 'returned' to be modeled in this way, so LowerCallResult does
1831         // not try to pass 'this' straight through
1832         isThisReturn = false;
1833         Mask = ARI->getCallPreservedMask(MF, CallConv);
1834       }
1835     } else
1836       Mask = ARI->getCallPreservedMask(MF, CallConv);
1837
1838     assert(Mask && "Missing call preserved mask for calling convention");
1839     Ops.push_back(DAG.getRegisterMask(Mask));
1840   }
1841
1842   if (InFlag.getNode())
1843     Ops.push_back(InFlag);
1844
1845   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1846   if (isTailCall)
1847     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1848
1849   // Returns a chain and a flag for retval copy to use.
1850   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1851   InFlag = Chain.getValue(1);
1852
1853   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
1854                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
1855   if (!Ins.empty())
1856     InFlag = Chain.getValue(1);
1857
1858   // Handle result values, copying them out of physregs into vregs that we
1859   // return.
1860   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1861                          InVals, isThisReturn,
1862                          isThisReturn ? OutVals[0] : SDValue());
1863 }
1864
1865 /// HandleByVal - Every parameter *after* a byval parameter is passed
1866 /// on the stack.  Remember the next parameter register to allocate,
1867 /// and then confiscate the rest of the parameter registers to insure
1868 /// this.
1869 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
1870                                     unsigned Align) const {
1871   assert((State->getCallOrPrologue() == Prologue ||
1872           State->getCallOrPrologue() == Call) &&
1873          "unhandled ParmContext");
1874
1875   // Byval (as with any stack) slots are always at least 4 byte aligned.
1876   Align = std::max(Align, 4U);
1877
1878   unsigned Reg = State->AllocateReg(GPRArgRegs);
1879   if (!Reg)
1880     return;
1881
1882   unsigned AlignInRegs = Align / 4;
1883   unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
1884   for (unsigned i = 0; i < Waste; ++i)
1885     Reg = State->AllocateReg(GPRArgRegs);
1886
1887   if (!Reg)
1888     return;
1889
1890   unsigned Excess = 4 * (ARM::R4 - Reg);
1891
1892   // Special case when NSAA != SP and parameter size greater than size of
1893   // all remained GPR regs. In that case we can't split parameter, we must
1894   // send it to stack. We also must set NCRN to R4, so waste all
1895   // remained registers.
1896   const unsigned NSAAOffset = State->getNextStackOffset();
1897   if (NSAAOffset != 0 && Size > Excess) {
1898     while (State->AllocateReg(GPRArgRegs))
1899       ;
1900     return;
1901   }
1902
1903   // First register for byval parameter is the first register that wasn't
1904   // allocated before this method call, so it would be "reg".
1905   // If parameter is small enough to be saved in range [reg, r4), then
1906   // the end (first after last) register would be reg + param-size-in-regs,
1907   // else parameter would be splitted between registers and stack,
1908   // end register would be r4 in this case.
1909   unsigned ByValRegBegin = Reg;
1910   unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
1911   State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1912   // Note, first register is allocated in the beginning of function already,
1913   // allocate remained amount of registers we need.
1914   for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
1915     State->AllocateReg(GPRArgRegs);
1916   // A byval parameter that is split between registers and memory needs its
1917   // size truncated here.
1918   // In the case where the entire structure fits in registers, we set the
1919   // size in memory to zero.
1920   Size = std::max<int>(Size - Excess, 0);
1921 }
1922
1923
1924 /// MatchingStackOffset - Return true if the given stack call argument is
1925 /// already available in the same position (relatively) of the caller's
1926 /// incoming argument stack.
1927 static
1928 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1929                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1930                          const TargetInstrInfo *TII) {
1931   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1932   int FI = INT_MAX;
1933   if (Arg.getOpcode() == ISD::CopyFromReg) {
1934     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1935     if (!TargetRegisterInfo::isVirtualRegister(VR))
1936       return false;
1937     MachineInstr *Def = MRI->getVRegDef(VR);
1938     if (!Def)
1939       return false;
1940     if (!Flags.isByVal()) {
1941       if (!TII->isLoadFromStackSlot(Def, FI))
1942         return false;
1943     } else {
1944       return false;
1945     }
1946   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1947     if (Flags.isByVal())
1948       // ByVal argument is passed in as a pointer but it's now being
1949       // dereferenced. e.g.
1950       // define @foo(%struct.X* %A) {
1951       //   tail call @bar(%struct.X* byval %A)
1952       // }
1953       return false;
1954     SDValue Ptr = Ld->getBasePtr();
1955     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1956     if (!FINode)
1957       return false;
1958     FI = FINode->getIndex();
1959   } else
1960     return false;
1961
1962   assert(FI != INT_MAX);
1963   if (!MFI->isFixedObjectIndex(FI))
1964     return false;
1965   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1966 }
1967
1968 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1969 /// for tail call optimization. Targets which want to do tail call
1970 /// optimization should implement this function.
1971 bool
1972 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1973                                                      CallingConv::ID CalleeCC,
1974                                                      bool isVarArg,
1975                                                      bool isCalleeStructRet,
1976                                                      bool isCallerStructRet,
1977                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1978                                     const SmallVectorImpl<SDValue> &OutVals,
1979                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1980                                                      SelectionDAG& DAG) const {
1981   const Function *CallerF = DAG.getMachineFunction().getFunction();
1982   CallingConv::ID CallerCC = CallerF->getCallingConv();
1983   bool CCMatch = CallerCC == CalleeCC;
1984
1985   // Look for obvious safe cases to perform tail call optimization that do not
1986   // require ABI changes. This is what gcc calls sibcall.
1987
1988   // Do not sibcall optimize vararg calls unless the call site is not passing
1989   // any arguments.
1990   if (isVarArg && !Outs.empty())
1991     return false;
1992
1993   // Exception-handling functions need a special set of instructions to indicate
1994   // a return to the hardware. Tail-calling another function would probably
1995   // break this.
1996   if (CallerF->hasFnAttribute("interrupt"))
1997     return false;
1998
1999   // Also avoid sibcall optimization if either caller or callee uses struct
2000   // return semantics.
2001   if (isCalleeStructRet || isCallerStructRet)
2002     return false;
2003
2004   // FIXME: Completely disable sibcall for Thumb1 since ThumbRegisterInfo::
2005   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
2006   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
2007   // support in the assembler and linker to be used. This would need to be
2008   // fixed to fully support tail calls in Thumb1.
2009   //
2010   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
2011   // LR.  This means if we need to reload LR, it takes an extra instructions,
2012   // which outweighs the value of the tail call; but here we don't know yet
2013   // whether LR is going to be used.  Probably the right approach is to
2014   // generate the tail call here and turn it back into CALL/RET in
2015   // emitEpilogue if LR is used.
2016
2017   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
2018   // but we need to make sure there are enough registers; the only valid
2019   // registers are the 4 used for parameters.  We don't currently do this
2020   // case.
2021   if (Subtarget->isThumb1Only())
2022     return false;
2023
2024   // Externally-defined functions with weak linkage should not be
2025   // tail-called on ARM when the OS does not support dynamic
2026   // pre-emption of symbols, as the AAELF spec requires normal calls
2027   // to undefined weak functions to be replaced with a NOP or jump to the
2028   // next instruction. The behaviour of branch instructions in this
2029   // situation (as used for tail calls) is implementation-defined, so we
2030   // cannot rely on the linker replacing the tail call with a return.
2031   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2032     const GlobalValue *GV = G->getGlobal();
2033     const Triple TT(getTargetMachine().getTargetTriple());
2034     if (GV->hasExternalWeakLinkage() &&
2035         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2036       return false;
2037   }
2038
2039   // If the calling conventions do not match, then we'd better make sure the
2040   // results are returned in the same way as what the caller expects.
2041   if (!CCMatch) {
2042     SmallVector<CCValAssign, 16> RVLocs1;
2043     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2044                        *DAG.getContext(), Call);
2045     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2046
2047     SmallVector<CCValAssign, 16> RVLocs2;
2048     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2049                        *DAG.getContext(), Call);
2050     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2051
2052     if (RVLocs1.size() != RVLocs2.size())
2053       return false;
2054     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2055       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2056         return false;
2057       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2058         return false;
2059       if (RVLocs1[i].isRegLoc()) {
2060         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2061           return false;
2062       } else {
2063         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2064           return false;
2065       }
2066     }
2067   }
2068
2069   // If Caller's vararg or byval argument has been split between registers and
2070   // stack, do not perform tail call, since part of the argument is in caller's
2071   // local frame.
2072   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2073                                       getInfo<ARMFunctionInfo>();
2074   if (AFI_Caller->getArgRegsSaveSize())
2075     return false;
2076
2077   // If the callee takes no arguments then go on to check the results of the
2078   // call.
2079   if (!Outs.empty()) {
2080     // Check if stack adjustment is needed. For now, do not do this if any
2081     // argument is passed on the stack.
2082     SmallVector<CCValAssign, 16> ArgLocs;
2083     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2084                       *DAG.getContext(), Call);
2085     CCInfo.AnalyzeCallOperands(Outs,
2086                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2087     if (CCInfo.getNextStackOffset()) {
2088       MachineFunction &MF = DAG.getMachineFunction();
2089
2090       // Check if the arguments are already laid out in the right way as
2091       // the caller's fixed stack objects.
2092       MachineFrameInfo *MFI = MF.getFrameInfo();
2093       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2094       const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2095       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2096            i != e;
2097            ++i, ++realArgIdx) {
2098         CCValAssign &VA = ArgLocs[i];
2099         EVT RegVT = VA.getLocVT();
2100         SDValue Arg = OutVals[realArgIdx];
2101         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2102         if (VA.getLocInfo() == CCValAssign::Indirect)
2103           return false;
2104         if (VA.needsCustom()) {
2105           // f64 and vector types are split into multiple registers or
2106           // register/stack-slot combinations.  The types will not match
2107           // the registers; give up on memory f64 refs until we figure
2108           // out what to do about this.
2109           if (!VA.isRegLoc())
2110             return false;
2111           if (!ArgLocs[++i].isRegLoc())
2112             return false;
2113           if (RegVT == MVT::v2f64) {
2114             if (!ArgLocs[++i].isRegLoc())
2115               return false;
2116             if (!ArgLocs[++i].isRegLoc())
2117               return false;
2118           }
2119         } else if (!VA.isRegLoc()) {
2120           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2121                                    MFI, MRI, TII))
2122             return false;
2123         }
2124       }
2125     }
2126   }
2127
2128   return true;
2129 }
2130
2131 bool
2132 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2133                                   MachineFunction &MF, bool isVarArg,
2134                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2135                                   LLVMContext &Context) const {
2136   SmallVector<CCValAssign, 16> RVLocs;
2137   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2138   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2139                                                     isVarArg));
2140 }
2141
2142 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2143                                     SDLoc DL, SelectionDAG &DAG) {
2144   const MachineFunction &MF = DAG.getMachineFunction();
2145   const Function *F = MF.getFunction();
2146
2147   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2148
2149   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2150   // version of the "preferred return address". These offsets affect the return
2151   // instruction if this is a return from PL1 without hypervisor extensions.
2152   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2153   //    SWI:     0      "subs pc, lr, #0"
2154   //    ABORT:   +4     "subs pc, lr, #4"
2155   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2156   // UNDEF varies depending on where the exception came from ARM or Thumb
2157   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2158
2159   int64_t LROffset;
2160   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2161       IntKind == "ABORT")
2162     LROffset = 4;
2163   else if (IntKind == "SWI" || IntKind == "UNDEF")
2164     LROffset = 0;
2165   else
2166     report_fatal_error("Unsupported interrupt attribute. If present, value "
2167                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2168
2169   RetOps.insert(RetOps.begin() + 1,
2170                 DAG.getConstant(LROffset, DL, MVT::i32, false));
2171
2172   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2173 }
2174
2175 SDValue
2176 ARMTargetLowering::LowerReturn(SDValue Chain,
2177                                CallingConv::ID CallConv, bool isVarArg,
2178                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2179                                const SmallVectorImpl<SDValue> &OutVals,
2180                                SDLoc dl, SelectionDAG &DAG) const {
2181
2182   // CCValAssign - represent the assignment of the return value to a location.
2183   SmallVector<CCValAssign, 16> RVLocs;
2184
2185   // CCState - Info about the registers and stack slots.
2186   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2187                     *DAG.getContext(), Call);
2188
2189   // Analyze outgoing return values.
2190   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2191                                                isVarArg));
2192
2193   SDValue Flag;
2194   SmallVector<SDValue, 4> RetOps;
2195   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2196   bool isLittleEndian = Subtarget->isLittle();
2197
2198   MachineFunction &MF = DAG.getMachineFunction();
2199   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2200   AFI->setReturnRegsCount(RVLocs.size());
2201
2202   // Copy the result values into the output registers.
2203   for (unsigned i = 0, realRVLocIdx = 0;
2204        i != RVLocs.size();
2205        ++i, ++realRVLocIdx) {
2206     CCValAssign &VA = RVLocs[i];
2207     assert(VA.isRegLoc() && "Can only return in registers!");
2208
2209     SDValue Arg = OutVals[realRVLocIdx];
2210
2211     switch (VA.getLocInfo()) {
2212     default: llvm_unreachable("Unknown loc info!");
2213     case CCValAssign::Full: break;
2214     case CCValAssign::BCvt:
2215       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2216       break;
2217     }
2218
2219     if (VA.needsCustom()) {
2220       if (VA.getLocVT() == MVT::v2f64) {
2221         // Extract the first half and return it in two registers.
2222         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2223                                    DAG.getConstant(0, dl, MVT::i32));
2224         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2225                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2226
2227         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2228                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2229                                  Flag);
2230         Flag = Chain.getValue(1);
2231         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2232         VA = RVLocs[++i]; // skip ahead to next loc
2233         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2234                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2235                                  Flag);
2236         Flag = Chain.getValue(1);
2237         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2238         VA = RVLocs[++i]; // skip ahead to next loc
2239
2240         // Extract the 2nd half and fall through to handle it as an f64 value.
2241         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2242                           DAG.getConstant(1, dl, MVT::i32));
2243       }
2244       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2245       // available.
2246       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2247                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2248       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2249                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2250                                Flag);
2251       Flag = Chain.getValue(1);
2252       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2253       VA = RVLocs[++i]; // skip ahead to next loc
2254       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2255                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2256                                Flag);
2257     } else
2258       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2259
2260     // Guarantee that all emitted copies are
2261     // stuck together, avoiding something bad.
2262     Flag = Chain.getValue(1);
2263     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2264   }
2265
2266   // Update chain and glue.
2267   RetOps[0] = Chain;
2268   if (Flag.getNode())
2269     RetOps.push_back(Flag);
2270
2271   // CPUs which aren't M-class use a special sequence to return from
2272   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2273   // though we use "subs pc, lr, #N").
2274   //
2275   // M-class CPUs actually use a normal return sequence with a special
2276   // (hardware-provided) value in LR, so the normal code path works.
2277   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2278       !Subtarget->isMClass()) {
2279     if (Subtarget->isThumb1Only())
2280       report_fatal_error("interrupt attribute is not supported in Thumb1");
2281     return LowerInterruptReturn(RetOps, dl, DAG);
2282   }
2283
2284   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2285 }
2286
2287 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2288   if (N->getNumValues() != 1)
2289     return false;
2290   if (!N->hasNUsesOfValue(1, 0))
2291     return false;
2292
2293   SDValue TCChain = Chain;
2294   SDNode *Copy = *N->use_begin();
2295   if (Copy->getOpcode() == ISD::CopyToReg) {
2296     // If the copy has a glue operand, we conservatively assume it isn't safe to
2297     // perform a tail call.
2298     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2299       return false;
2300     TCChain = Copy->getOperand(0);
2301   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2302     SDNode *VMov = Copy;
2303     // f64 returned in a pair of GPRs.
2304     SmallPtrSet<SDNode*, 2> Copies;
2305     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2306          UI != UE; ++UI) {
2307       if (UI->getOpcode() != ISD::CopyToReg)
2308         return false;
2309       Copies.insert(*UI);
2310     }
2311     if (Copies.size() > 2)
2312       return false;
2313
2314     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2315          UI != UE; ++UI) {
2316       SDValue UseChain = UI->getOperand(0);
2317       if (Copies.count(UseChain.getNode()))
2318         // Second CopyToReg
2319         Copy = *UI;
2320       else {
2321         // We are at the top of this chain.
2322         // If the copy has a glue operand, we conservatively assume it
2323         // isn't safe to perform a tail call.
2324         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2325           return false;
2326         // First CopyToReg
2327         TCChain = UseChain;
2328       }
2329     }
2330   } else if (Copy->getOpcode() == ISD::BITCAST) {
2331     // f32 returned in a single GPR.
2332     if (!Copy->hasOneUse())
2333       return false;
2334     Copy = *Copy->use_begin();
2335     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2336       return false;
2337     // If the copy has a glue operand, we conservatively assume it isn't safe to
2338     // perform a tail call.
2339     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2340       return false;
2341     TCChain = Copy->getOperand(0);
2342   } else {
2343     return false;
2344   }
2345
2346   bool HasRet = false;
2347   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2348        UI != UE; ++UI) {
2349     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2350         UI->getOpcode() != ARMISD::INTRET_FLAG)
2351       return false;
2352     HasRet = true;
2353   }
2354
2355   if (!HasRet)
2356     return false;
2357
2358   Chain = TCChain;
2359   return true;
2360 }
2361
2362 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2363   if (!Subtarget->supportsTailCall())
2364     return false;
2365
2366   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2367     return false;
2368
2369   return !Subtarget->isThumb1Only();
2370 }
2371
2372 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2373 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2374 // one of the above mentioned nodes. It has to be wrapped because otherwise
2375 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2376 // be used to form addressing mode. These wrapped nodes will be selected
2377 // into MOVi.
2378 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2379   EVT PtrVT = Op.getValueType();
2380   // FIXME there is no actual debug info here
2381   SDLoc dl(Op);
2382   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2383   SDValue Res;
2384   if (CP->isMachineConstantPoolEntry())
2385     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2386                                     CP->getAlignment());
2387   else
2388     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2389                                     CP->getAlignment());
2390   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2391 }
2392
2393 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2394   return MachineJumpTableInfo::EK_Inline;
2395 }
2396
2397 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2398                                              SelectionDAG &DAG) const {
2399   MachineFunction &MF = DAG.getMachineFunction();
2400   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2401   unsigned ARMPCLabelIndex = 0;
2402   SDLoc DL(Op);
2403   EVT PtrVT = getPointerTy();
2404   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2405   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2406   SDValue CPAddr;
2407   if (RelocM == Reloc::Static) {
2408     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2409   } else {
2410     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2411     ARMPCLabelIndex = AFI->createPICLabelUId();
2412     ARMConstantPoolValue *CPV =
2413       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2414                                       ARMCP::CPBlockAddress, PCAdj);
2415     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2416   }
2417   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2418   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2419                                MachinePointerInfo::getConstantPool(),
2420                                false, false, false, 0);
2421   if (RelocM == Reloc::Static)
2422     return Result;
2423   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2424   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2425 }
2426
2427 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2428 SDValue
2429 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2430                                                  SelectionDAG &DAG) const {
2431   SDLoc dl(GA);
2432   EVT PtrVT = getPointerTy();
2433   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2434   MachineFunction &MF = DAG.getMachineFunction();
2435   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2436   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2437   ARMConstantPoolValue *CPV =
2438     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2439                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2440   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2441   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2442   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2443                          MachinePointerInfo::getConstantPool(),
2444                          false, false, false, 0);
2445   SDValue Chain = Argument.getValue(1);
2446
2447   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2448   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2449
2450   // call __tls_get_addr.
2451   ArgListTy Args;
2452   ArgListEntry Entry;
2453   Entry.Node = Argument;
2454   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2455   Args.push_back(Entry);
2456
2457   // FIXME: is there useful debug info available here?
2458   TargetLowering::CallLoweringInfo CLI(DAG);
2459   CLI.setDebugLoc(dl).setChain(Chain)
2460     .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2461                DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2462                0);
2463
2464   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2465   return CallResult.first;
2466 }
2467
2468 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2469 // "local exec" model.
2470 SDValue
2471 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2472                                         SelectionDAG &DAG,
2473                                         TLSModel::Model model) const {
2474   const GlobalValue *GV = GA->getGlobal();
2475   SDLoc dl(GA);
2476   SDValue Offset;
2477   SDValue Chain = DAG.getEntryNode();
2478   EVT PtrVT = getPointerTy();
2479   // Get the Thread Pointer
2480   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2481
2482   if (model == TLSModel::InitialExec) {
2483     MachineFunction &MF = DAG.getMachineFunction();
2484     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2485     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2486     // Initial exec model.
2487     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2488     ARMConstantPoolValue *CPV =
2489       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2490                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2491                                       true);
2492     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2493     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2494     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2495                          MachinePointerInfo::getConstantPool(),
2496                          false, false, false, 0);
2497     Chain = Offset.getValue(1);
2498
2499     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2500     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2501
2502     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2503                          MachinePointerInfo::getConstantPool(),
2504                          false, false, false, 0);
2505   } else {
2506     // local exec model
2507     assert(model == TLSModel::LocalExec);
2508     ARMConstantPoolValue *CPV =
2509       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2510     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2511     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2512     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2513                          MachinePointerInfo::getConstantPool(),
2514                          false, false, false, 0);
2515   }
2516
2517   // The address of the thread local variable is the add of the thread
2518   // pointer with the offset of the variable.
2519   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2520 }
2521
2522 SDValue
2523 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2524   // TODO: implement the "local dynamic" model
2525   assert(Subtarget->isTargetELF() &&
2526          "TLS not implemented for non-ELF targets");
2527   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2528
2529   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2530
2531   switch (model) {
2532     case TLSModel::GeneralDynamic:
2533     case TLSModel::LocalDynamic:
2534       return LowerToTLSGeneralDynamicModel(GA, DAG);
2535     case TLSModel::InitialExec:
2536     case TLSModel::LocalExec:
2537       return LowerToTLSExecModels(GA, DAG, model);
2538   }
2539   llvm_unreachable("bogus TLS model");
2540 }
2541
2542 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2543                                                  SelectionDAG &DAG) const {
2544   EVT PtrVT = getPointerTy();
2545   SDLoc dl(Op);
2546   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2547   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2548     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2549     ARMConstantPoolValue *CPV =
2550       ARMConstantPoolConstant::Create(GV,
2551                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2552     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2553     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2554     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2555                                  CPAddr,
2556                                  MachinePointerInfo::getConstantPool(),
2557                                  false, false, false, 0);
2558     SDValue Chain = Result.getValue(1);
2559     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2560     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2561     if (!UseGOTOFF)
2562       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2563                            MachinePointerInfo::getGOT(),
2564                            false, false, false, 0);
2565     return Result;
2566   }
2567
2568   // If we have T2 ops, we can materialize the address directly via movt/movw
2569   // pair. This is always cheaper.
2570   if (Subtarget->useMovt(DAG.getMachineFunction())) {
2571     ++NumMovwMovt;
2572     // FIXME: Once remat is capable of dealing with instructions with register
2573     // operands, expand this into two nodes.
2574     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2575                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2576   } else {
2577     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2578     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2579     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2580                        MachinePointerInfo::getConstantPool(),
2581                        false, false, false, 0);
2582   }
2583 }
2584
2585 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2586                                                     SelectionDAG &DAG) const {
2587   EVT PtrVT = getPointerTy();
2588   SDLoc dl(Op);
2589   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2590   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2591
2592   if (Subtarget->useMovt(DAG.getMachineFunction()))
2593     ++NumMovwMovt;
2594
2595   // FIXME: Once remat is capable of dealing with instructions with register
2596   // operands, expand this into multiple nodes
2597   unsigned Wrapper =
2598       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2599
2600   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2601   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2602
2603   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2604     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2605                          MachinePointerInfo::getGOT(), false, false, false, 0);
2606   return Result;
2607 }
2608
2609 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2610                                                      SelectionDAG &DAG) const {
2611   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2612   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2613          "Windows on ARM expects to use movw/movt");
2614
2615   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2616   const ARMII::TOF TargetFlags =
2617     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2618   EVT PtrVT = getPointerTy();
2619   SDValue Result;
2620   SDLoc DL(Op);
2621
2622   ++NumMovwMovt;
2623
2624   // FIXME: Once remat is capable of dealing with instructions with register
2625   // operands, expand this into two nodes.
2626   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2627                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2628                                                   TargetFlags));
2629   if (GV->hasDLLImportStorageClass())
2630     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2631                          MachinePointerInfo::getGOT(), false, false, false, 0);
2632   return Result;
2633 }
2634
2635 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2636                                                     SelectionDAG &DAG) const {
2637   assert(Subtarget->isTargetELF() &&
2638          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2639   MachineFunction &MF = DAG.getMachineFunction();
2640   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2641   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2642   EVT PtrVT = getPointerTy();
2643   SDLoc dl(Op);
2644   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2645   ARMConstantPoolValue *CPV =
2646     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2647                                   ARMPCLabelIndex, PCAdj);
2648   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2649   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2650   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2651                                MachinePointerInfo::getConstantPool(),
2652                                false, false, false, 0);
2653   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2654   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2655 }
2656
2657 SDValue
2658 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2659   SDLoc dl(Op);
2660   SDValue Val = DAG.getConstant(0, dl, MVT::i32);
2661   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2662                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2663                      Op.getOperand(1), Val);
2664 }
2665
2666 SDValue
2667 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2668   SDLoc dl(Op);
2669   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2670                      Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
2671 }
2672
2673 SDValue
2674 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2675                                           const ARMSubtarget *Subtarget) const {
2676   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2677   SDLoc dl(Op);
2678   switch (IntNo) {
2679   default: return SDValue();    // Don't custom lower most intrinsics.
2680   case Intrinsic::arm_rbit: {
2681     assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2682            "RBIT intrinsic must have i32 type!");
2683     return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1));
2684   }
2685   case Intrinsic::arm_thread_pointer: {
2686     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2687     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2688   }
2689   case Intrinsic::eh_sjlj_lsda: {
2690     MachineFunction &MF = DAG.getMachineFunction();
2691     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2692     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2693     EVT PtrVT = getPointerTy();
2694     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2695     SDValue CPAddr;
2696     unsigned PCAdj = (RelocM != Reloc::PIC_)
2697       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2698     ARMConstantPoolValue *CPV =
2699       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2700                                       ARMCP::CPLSDA, PCAdj);
2701     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2702     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2703     SDValue Result =
2704       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2705                   MachinePointerInfo::getConstantPool(),
2706                   false, false, false, 0);
2707
2708     if (RelocM == Reloc::PIC_) {
2709       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2710       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2711     }
2712     return Result;
2713   }
2714   case Intrinsic::arm_neon_vmulls:
2715   case Intrinsic::arm_neon_vmullu: {
2716     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2717       ? ARMISD::VMULLs : ARMISD::VMULLu;
2718     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2719                        Op.getOperand(1), Op.getOperand(2));
2720   }
2721   }
2722 }
2723
2724 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2725                                  const ARMSubtarget *Subtarget) {
2726   // FIXME: handle "fence singlethread" more efficiently.
2727   SDLoc dl(Op);
2728   if (!Subtarget->hasDataBarrier()) {
2729     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2730     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2731     // here.
2732     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2733            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2734     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2735                        DAG.getConstant(0, dl, MVT::i32));
2736   }
2737
2738   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2739   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2740   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
2741   if (Subtarget->isMClass()) {
2742     // Only a full system barrier exists in the M-class architectures.
2743     Domain = ARM_MB::SY;
2744   } else if (Subtarget->isSwift() && Ord == Release) {
2745     // Swift happens to implement ISHST barriers in a way that's compatible with
2746     // Release semantics but weaker than ISH so we'd be fools not to use
2747     // it. Beware: other processors probably don't!
2748     Domain = ARM_MB::ISHST;
2749   }
2750
2751   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2752                      DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
2753                      DAG.getConstant(Domain, dl, MVT::i32));
2754 }
2755
2756 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2757                              const ARMSubtarget *Subtarget) {
2758   // ARM pre v5TE and Thumb1 does not have preload instructions.
2759   if (!(Subtarget->isThumb2() ||
2760         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2761     // Just preserve the chain.
2762     return Op.getOperand(0);
2763
2764   SDLoc dl(Op);
2765   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2766   if (!isRead &&
2767       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2768     // ARMv7 with MP extension has PLDW.
2769     return Op.getOperand(0);
2770
2771   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2772   if (Subtarget->isThumb()) {
2773     // Invert the bits.
2774     isRead = ~isRead & 1;
2775     isData = ~isData & 1;
2776   }
2777
2778   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2779                      Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
2780                      DAG.getConstant(isData, dl, MVT::i32));
2781 }
2782
2783 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2784   MachineFunction &MF = DAG.getMachineFunction();
2785   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2786
2787   // vastart just stores the address of the VarArgsFrameIndex slot into the
2788   // memory location argument.
2789   SDLoc dl(Op);
2790   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2791   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2792   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2793   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2794                       MachinePointerInfo(SV), false, false, 0);
2795 }
2796
2797 SDValue
2798 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2799                                         SDValue &Root, SelectionDAG &DAG,
2800                                         SDLoc dl) const {
2801   MachineFunction &MF = DAG.getMachineFunction();
2802   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2803
2804   const TargetRegisterClass *RC;
2805   if (AFI->isThumb1OnlyFunction())
2806     RC = &ARM::tGPRRegClass;
2807   else
2808     RC = &ARM::GPRRegClass;
2809
2810   // Transform the arguments stored in physical registers into virtual ones.
2811   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2812   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2813
2814   SDValue ArgValue2;
2815   if (NextVA.isMemLoc()) {
2816     MachineFrameInfo *MFI = MF.getFrameInfo();
2817     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2818
2819     // Create load node to retrieve arguments from the stack.
2820     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2821     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2822                             MachinePointerInfo::getFixedStack(FI),
2823                             false, false, false, 0);
2824   } else {
2825     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2826     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2827   }
2828   if (!Subtarget->isLittle())
2829     std::swap (ArgValue, ArgValue2);
2830   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2831 }
2832
2833 // The remaining GPRs hold either the beginning of variable-argument
2834 // data, or the beginning of an aggregate passed by value (usually
2835 // byval).  Either way, we allocate stack slots adjacent to the data
2836 // provided by our caller, and store the unallocated registers there.
2837 // If this is a variadic function, the va_list pointer will begin with
2838 // these values; otherwise, this reassembles a (byval) structure that
2839 // was split between registers and memory.
2840 // Return: The frame index registers were stored into.
2841 int
2842 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2843                                   SDLoc dl, SDValue &Chain,
2844                                   const Value *OrigArg,
2845                                   unsigned InRegsParamRecordIdx,
2846                                   int ArgOffset,
2847                                   unsigned ArgSize) const {
2848   // Currently, two use-cases possible:
2849   // Case #1. Non-var-args function, and we meet first byval parameter.
2850   //          Setup first unallocated register as first byval register;
2851   //          eat all remained registers
2852   //          (these two actions are performed by HandleByVal method).
2853   //          Then, here, we initialize stack frame with
2854   //          "store-reg" instructions.
2855   // Case #2. Var-args function, that doesn't contain byval parameters.
2856   //          The same: eat all remained unallocated registers,
2857   //          initialize stack frame.
2858
2859   MachineFunction &MF = DAG.getMachineFunction();
2860   MachineFrameInfo *MFI = MF.getFrameInfo();
2861   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2862   unsigned RBegin, REnd;
2863   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2864     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2865   } else {
2866     unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
2867     RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
2868     REnd = ARM::R4;
2869   }
2870
2871   if (REnd != RBegin)
2872     ArgOffset = -4 * (ARM::R4 - RBegin);
2873
2874   int FrameIndex = MFI->CreateFixedObject(ArgSize, ArgOffset, false);
2875   SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2876
2877   SmallVector<SDValue, 4> MemOps;
2878   const TargetRegisterClass *RC =
2879       AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
2880
2881   for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
2882     unsigned VReg = MF.addLiveIn(Reg, RC);
2883     SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2884     SDValue Store =
2885         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2886                      MachinePointerInfo(OrigArg, 4 * i), false, false, 0);
2887     MemOps.push_back(Store);
2888     FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2889                       DAG.getConstant(4, dl, getPointerTy()));
2890   }
2891
2892   if (!MemOps.empty())
2893     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2894   return FrameIndex;
2895 }
2896
2897 // Setup stack frame, the va_list pointer will start from.
2898 void
2899 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2900                                         SDLoc dl, SDValue &Chain,
2901                                         unsigned ArgOffset,
2902                                         unsigned TotalArgRegsSaveSize,
2903                                         bool ForceMutable) const {
2904   MachineFunction &MF = DAG.getMachineFunction();
2905   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2906
2907   // Try to store any remaining integer argument regs
2908   // to their spots on the stack so that they may be loaded by deferencing
2909   // the result of va_next.
2910   // If there is no regs to be stored, just point address after last
2911   // argument passed via stack.
2912   int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
2913                                   CCInfo.getInRegsParamsCount(),
2914                                   CCInfo.getNextStackOffset(), 4);
2915   AFI->setVarArgsFrameIndex(FrameIndex);
2916 }
2917
2918 SDValue
2919 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2920                                         CallingConv::ID CallConv, bool isVarArg,
2921                                         const SmallVectorImpl<ISD::InputArg>
2922                                           &Ins,
2923                                         SDLoc dl, SelectionDAG &DAG,
2924                                         SmallVectorImpl<SDValue> &InVals)
2925                                           const {
2926   MachineFunction &MF = DAG.getMachineFunction();
2927   MachineFrameInfo *MFI = MF.getFrameInfo();
2928
2929   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2930
2931   // Assign locations to all of the incoming arguments.
2932   SmallVector<CCValAssign, 16> ArgLocs;
2933   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2934                     *DAG.getContext(), Prologue);
2935   CCInfo.AnalyzeFormalArguments(Ins,
2936                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2937                                                   isVarArg));
2938
2939   SmallVector<SDValue, 16> ArgValues;
2940   SDValue ArgValue;
2941   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2942   unsigned CurArgIdx = 0;
2943
2944   // Initially ArgRegsSaveSize is zero.
2945   // Then we increase this value each time we meet byval parameter.
2946   // We also increase this value in case of varargs function.
2947   AFI->setArgRegsSaveSize(0);
2948
2949   // Calculate the amount of stack space that we need to allocate to store
2950   // byval and variadic arguments that are passed in registers.
2951   // We need to know this before we allocate the first byval or variadic
2952   // argument, as they will be allocated a stack slot below the CFA (Canonical
2953   // Frame Address, the stack pointer at entry to the function).
2954   unsigned ArgRegBegin = ARM::R4;
2955   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2956     if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
2957       break;
2958
2959     CCValAssign &VA = ArgLocs[i];
2960     unsigned Index = VA.getValNo();
2961     ISD::ArgFlagsTy Flags = Ins[Index].Flags;
2962     if (!Flags.isByVal())
2963       continue;
2964
2965     assert(VA.isMemLoc() && "unexpected byval pointer in reg");
2966     unsigned RBegin, REnd;
2967     CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
2968     ArgRegBegin = std::min(ArgRegBegin, RBegin);
2969
2970     CCInfo.nextInRegsParam();
2971   }
2972   CCInfo.rewindByValRegsInfo();
2973
2974   int lastInsIndex = -1;
2975   if (isVarArg && MFI->hasVAStart()) {
2976     unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
2977     if (RegIdx != array_lengthof(GPRArgRegs))
2978       ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
2979   }
2980
2981   unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
2982   AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
2983
2984   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2985     CCValAssign &VA = ArgLocs[i];
2986     if (Ins[VA.getValNo()].isOrigArg()) {
2987       std::advance(CurOrigArg,
2988                    Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
2989       CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
2990     }
2991     // Arguments stored in registers.
2992     if (VA.isRegLoc()) {
2993       EVT RegVT = VA.getLocVT();
2994
2995       if (VA.needsCustom()) {
2996         // f64 and vector types are split up into multiple registers or
2997         // combinations of registers and stack slots.
2998         if (VA.getLocVT() == MVT::v2f64) {
2999           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3000                                                    Chain, DAG, dl);
3001           VA = ArgLocs[++i]; // skip ahead to next loc
3002           SDValue ArgValue2;
3003           if (VA.isMemLoc()) {
3004             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3005             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3006             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3007                                     MachinePointerInfo::getFixedStack(FI),
3008                                     false, false, false, 0);
3009           } else {
3010             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3011                                              Chain, DAG, dl);
3012           }
3013           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3014           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3015                                  ArgValue, ArgValue1,
3016                                  DAG.getIntPtrConstant(0, dl));
3017           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3018                                  ArgValue, ArgValue2,
3019                                  DAG.getIntPtrConstant(1, dl));
3020         } else
3021           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3022
3023       } else {
3024         const TargetRegisterClass *RC;
3025
3026         if (RegVT == MVT::f32)
3027           RC = &ARM::SPRRegClass;
3028         else if (RegVT == MVT::f64)
3029           RC = &ARM::DPRRegClass;
3030         else if (RegVT == MVT::v2f64)
3031           RC = &ARM::QPRRegClass;
3032         else if (RegVT == MVT::i32)
3033           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3034                                            : &ARM::GPRRegClass;
3035         else
3036           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3037
3038         // Transform the arguments in physical registers into virtual ones.
3039         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3040         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3041       }
3042
3043       // If this is an 8 or 16-bit value, it is really passed promoted
3044       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3045       // truncate to the right size.
3046       switch (VA.getLocInfo()) {
3047       default: llvm_unreachable("Unknown loc info!");
3048       case CCValAssign::Full: break;
3049       case CCValAssign::BCvt:
3050         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3051         break;
3052       case CCValAssign::SExt:
3053         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3054                                DAG.getValueType(VA.getValVT()));
3055         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3056         break;
3057       case CCValAssign::ZExt:
3058         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3059                                DAG.getValueType(VA.getValVT()));
3060         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3061         break;
3062       }
3063
3064       InVals.push_back(ArgValue);
3065
3066     } else { // VA.isRegLoc()
3067
3068       // sanity check
3069       assert(VA.isMemLoc());
3070       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3071
3072       int index = VA.getValNo();
3073
3074       // Some Ins[] entries become multiple ArgLoc[] entries.
3075       // Process them only once.
3076       if (index != lastInsIndex)
3077         {
3078           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3079           // FIXME: For now, all byval parameter objects are marked mutable.
3080           // This can be changed with more analysis.
3081           // In case of tail call optimization mark all arguments mutable.
3082           // Since they could be overwritten by lowering of arguments in case of
3083           // a tail call.
3084           if (Flags.isByVal()) {
3085             assert(Ins[index].isOrigArg() &&
3086                    "Byval arguments cannot be implicit");
3087             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3088
3089             int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, CurOrigArg,
3090                                             CurByValIndex, VA.getLocMemOffset(),
3091                                             Flags.getByValSize());
3092             InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3093             CCInfo.nextInRegsParam();
3094           } else {
3095             unsigned FIOffset = VA.getLocMemOffset();
3096             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3097                                             FIOffset, true);
3098
3099             // Create load nodes to retrieve arguments from the stack.
3100             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3101             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3102                                          MachinePointerInfo::getFixedStack(FI),
3103                                          false, false, false, 0));
3104           }
3105           lastInsIndex = index;
3106         }
3107     }
3108   }
3109
3110   // varargs
3111   if (isVarArg && MFI->hasVAStart())
3112     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3113                          CCInfo.getNextStackOffset(),
3114                          TotalArgRegsSaveSize);
3115
3116   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3117
3118   return Chain;
3119 }
3120
3121 /// isFloatingPointZero - Return true if this is +0.0.
3122 static bool isFloatingPointZero(SDValue Op) {
3123   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3124     return CFP->getValueAPF().isPosZero();
3125   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3126     // Maybe this has already been legalized into the constant pool?
3127     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3128       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3129       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3130         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3131           return CFP->getValueAPF().isPosZero();
3132     }
3133   } else if (Op->getOpcode() == ISD::BITCAST &&
3134              Op->getValueType(0) == MVT::f64) {
3135     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3136     // created by LowerConstantFP().
3137     SDValue BitcastOp = Op->getOperand(0);
3138     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM) {
3139       SDValue MoveOp = BitcastOp->getOperand(0);
3140       if (MoveOp->getOpcode() == ISD::TargetConstant &&
3141           cast<ConstantSDNode>(MoveOp)->getZExtValue() == 0) {
3142         return true;
3143       }
3144     }
3145   }
3146   return false;
3147 }
3148
3149 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3150 /// the given operands.
3151 SDValue
3152 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3153                              SDValue &ARMcc, SelectionDAG &DAG,
3154                              SDLoc dl) const {
3155   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3156     unsigned C = RHSC->getZExtValue();
3157     if (!isLegalICmpImmediate(C)) {
3158       // Constant does not fit, try adjusting it by one?
3159       switch (CC) {
3160       default: break;
3161       case ISD::SETLT:
3162       case ISD::SETGE:
3163         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3164           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3165           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3166         }
3167         break;
3168       case ISD::SETULT:
3169       case ISD::SETUGE:
3170         if (C != 0 && isLegalICmpImmediate(C-1)) {
3171           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3172           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3173         }
3174         break;
3175       case ISD::SETLE:
3176       case ISD::SETGT:
3177         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3178           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3179           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3180         }
3181         break;
3182       case ISD::SETULE:
3183       case ISD::SETUGT:
3184         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3185           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3186           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3187         }
3188         break;
3189       }
3190     }
3191   }
3192
3193   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3194   ARMISD::NodeType CompareType;
3195   switch (CondCode) {
3196   default:
3197     CompareType = ARMISD::CMP;
3198     break;
3199   case ARMCC::EQ:
3200   case ARMCC::NE:
3201     // Uses only Z Flag
3202     CompareType = ARMISD::CMPZ;
3203     break;
3204   }
3205   ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3206   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3207 }
3208
3209 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3210 SDValue
3211 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3212                              SDLoc dl) const {
3213   assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3214   SDValue Cmp;
3215   if (!isFloatingPointZero(RHS))
3216     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3217   else
3218     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3219   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3220 }
3221
3222 /// duplicateCmp - Glue values can have only one use, so this function
3223 /// duplicates a comparison node.
3224 SDValue
3225 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3226   unsigned Opc = Cmp.getOpcode();
3227   SDLoc DL(Cmp);
3228   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3229     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3230
3231   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3232   Cmp = Cmp.getOperand(0);
3233   Opc = Cmp.getOpcode();
3234   if (Opc == ARMISD::CMPFP)
3235     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3236   else {
3237     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3238     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3239   }
3240   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3241 }
3242
3243 std::pair<SDValue, SDValue>
3244 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3245                                  SDValue &ARMcc) const {
3246   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3247
3248   SDValue Value, OverflowCmp;
3249   SDValue LHS = Op.getOperand(0);
3250   SDValue RHS = Op.getOperand(1);
3251   SDLoc dl(Op);
3252
3253   // FIXME: We are currently always generating CMPs because we don't support
3254   // generating CMN through the backend. This is not as good as the natural
3255   // CMP case because it causes a register dependency and cannot be folded
3256   // later.
3257
3258   switch (Op.getOpcode()) {
3259   default:
3260     llvm_unreachable("Unknown overflow instruction!");
3261   case ISD::SADDO:
3262     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3263     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3264     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3265     break;
3266   case ISD::UADDO:
3267     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3268     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3269     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3270     break;
3271   case ISD::SSUBO:
3272     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3273     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3274     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3275     break;
3276   case ISD::USUBO:
3277     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3278     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3279     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3280     break;
3281   } // switch (...)
3282
3283   return std::make_pair(Value, OverflowCmp);
3284 }
3285
3286
3287 SDValue
3288 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3289   // Let legalize expand this if it isn't a legal type yet.
3290   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3291     return SDValue();
3292
3293   SDValue Value, OverflowCmp;
3294   SDValue ARMcc;
3295   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3296   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3297   SDLoc dl(Op);
3298   // We use 0 and 1 as false and true values.
3299   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3300   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3301   EVT VT = Op.getValueType();
3302
3303   SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
3304                                  ARMcc, CCR, OverflowCmp);
3305
3306   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3307   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
3308 }
3309
3310
3311 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3312   SDValue Cond = Op.getOperand(0);
3313   SDValue SelectTrue = Op.getOperand(1);
3314   SDValue SelectFalse = Op.getOperand(2);
3315   SDLoc dl(Op);
3316   unsigned Opc = Cond.getOpcode();
3317
3318   if (Cond.getResNo() == 1 &&
3319       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3320        Opc == ISD::USUBO)) {
3321     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3322       return SDValue();
3323
3324     SDValue Value, OverflowCmp;
3325     SDValue ARMcc;
3326     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3327     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3328     EVT VT = Op.getValueType();
3329
3330     return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
3331                    OverflowCmp, DAG);
3332   }
3333
3334   // Convert:
3335   //
3336   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3337   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3338   //
3339   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3340     const ConstantSDNode *CMOVTrue =
3341       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3342     const ConstantSDNode *CMOVFalse =
3343       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3344
3345     if (CMOVTrue && CMOVFalse) {
3346       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3347       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3348
3349       SDValue True;
3350       SDValue False;
3351       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3352         True = SelectTrue;
3353         False = SelectFalse;
3354       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3355         True = SelectFalse;
3356         False = SelectTrue;
3357       }
3358
3359       if (True.getNode() && False.getNode()) {
3360         EVT VT = Op.getValueType();
3361         SDValue ARMcc = Cond.getOperand(2);
3362         SDValue CCR = Cond.getOperand(3);
3363         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3364         assert(True.getValueType() == VT);
3365         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3366       }
3367     }
3368   }
3369
3370   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3371   // undefined bits before doing a full-word comparison with zero.
3372   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3373                      DAG.getConstant(1, dl, Cond.getValueType()));
3374
3375   return DAG.getSelectCC(dl, Cond,
3376                          DAG.getConstant(0, dl, Cond.getValueType()),
3377                          SelectTrue, SelectFalse, ISD::SETNE);
3378 }
3379
3380 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3381                                  bool &swpCmpOps, bool &swpVselOps) {
3382   // Start by selecting the GE condition code for opcodes that return true for
3383   // 'equality'
3384   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3385       CC == ISD::SETULE)
3386     CondCode = ARMCC::GE;
3387
3388   // and GT for opcodes that return false for 'equality'.
3389   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3390            CC == ISD::SETULT)
3391     CondCode = ARMCC::GT;
3392
3393   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3394   // to swap the compare operands.
3395   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3396       CC == ISD::SETULT)
3397     swpCmpOps = true;
3398
3399   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3400   // If we have an unordered opcode, we need to swap the operands to the VSEL
3401   // instruction (effectively negating the condition).
3402   //
3403   // This also has the effect of swapping which one of 'less' or 'greater'
3404   // returns true, so we also swap the compare operands. It also switches
3405   // whether we return true for 'equality', so we compensate by picking the
3406   // opposite condition code to our original choice.
3407   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3408       CC == ISD::SETUGT) {
3409     swpCmpOps = !swpCmpOps;
3410     swpVselOps = !swpVselOps;
3411     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3412   }
3413
3414   // 'ordered' is 'anything but unordered', so use the VS condition code and
3415   // swap the VSEL operands.
3416   if (CC == ISD::SETO) {
3417     CondCode = ARMCC::VS;
3418     swpVselOps = true;
3419   }
3420
3421   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3422   // code and swap the VSEL operands.
3423   if (CC == ISD::SETUNE) {
3424     CondCode = ARMCC::EQ;
3425     swpVselOps = true;
3426   }
3427 }
3428
3429 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3430                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3431                                    SDValue Cmp, SelectionDAG &DAG) const {
3432   if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3433     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3434                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3435     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3436                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3437
3438     SDValue TrueLow = TrueVal.getValue(0);
3439     SDValue TrueHigh = TrueVal.getValue(1);
3440     SDValue FalseLow = FalseVal.getValue(0);
3441     SDValue FalseHigh = FalseVal.getValue(1);
3442
3443     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3444                               ARMcc, CCR, Cmp);
3445     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3446                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
3447
3448     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3449   } else {
3450     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3451                        Cmp);
3452   }
3453 }
3454
3455 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3456   EVT VT = Op.getValueType();
3457   SDValue LHS = Op.getOperand(0);
3458   SDValue RHS = Op.getOperand(1);
3459   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3460   SDValue TrueVal = Op.getOperand(2);
3461   SDValue FalseVal = Op.getOperand(3);
3462   SDLoc dl(Op);
3463
3464   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3465     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3466                                                     dl);
3467
3468     // If softenSetCCOperands only returned one value, we should compare it to
3469     // zero.
3470     if (!RHS.getNode()) {
3471       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3472       CC = ISD::SETNE;
3473     }
3474   }
3475
3476   if (LHS.getValueType() == MVT::i32) {
3477     // Try to generate VSEL on ARMv8.
3478     // The VSEL instruction can't use all the usual ARM condition
3479     // codes: it only has two bits to select the condition code, so it's
3480     // constrained to use only GE, GT, VS and EQ.
3481     //
3482     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3483     // swap the operands of the previous compare instruction (effectively
3484     // inverting the compare condition, swapping 'less' and 'greater') and
3485     // sometimes need to swap the operands to the VSEL (which inverts the
3486     // condition in the sense of firing whenever the previous condition didn't)
3487     if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3488                                     TrueVal.getValueType() == MVT::f64)) {
3489       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3490       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3491           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3492         CC = ISD::getSetCCInverse(CC, true);
3493         std::swap(TrueVal, FalseVal);
3494       }
3495     }
3496
3497     SDValue ARMcc;
3498     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3499     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3500     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3501   }
3502
3503   ARMCC::CondCodes CondCode, CondCode2;
3504   FPCCToARMCC(CC, CondCode, CondCode2);
3505
3506   // Try to generate VMAXNM/VMINNM on ARMv8.
3507   if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3508                                   TrueVal.getValueType() == MVT::f64)) {
3509     // We can use VMAXNM/VMINNM for a compare followed by a select with the
3510     // same operands, as follows:
3511     //   c = fcmp [?gt, ?ge, ?lt, ?le] a, b
3512     //   select c, a, b
3513     // In NoNaNsFPMath the CC will have been changed from, e.g., 'ogt' to 'gt'.
3514     // FIXME: There is similar code that allows some extensions in
3515     // AArch64TargetLowering::LowerSELECT_CC that should be shared with this
3516     // code.
3517     bool swapSides = false;
3518     if (!getTargetMachine().Options.NoNaNsFPMath) {
3519       // transformability may depend on which way around we compare
3520       switch (CC) {
3521       default:
3522         break;
3523       case ISD::SETOGT:
3524       case ISD::SETOGE:
3525       case ISD::SETOLT:
3526       case ISD::SETOLE:
3527         // the non-NaN should be RHS
3528         swapSides = DAG.isKnownNeverNaN(LHS) && !DAG.isKnownNeverNaN(RHS);
3529         break;
3530       case ISD::SETUGT:
3531       case ISD::SETUGE:
3532       case ISD::SETULT:
3533       case ISD::SETULE:
3534         // the non-NaN should be LHS
3535         swapSides = DAG.isKnownNeverNaN(RHS) && !DAG.isKnownNeverNaN(LHS);
3536         break;
3537       }
3538     }
3539     swapSides = swapSides || (LHS == FalseVal && RHS == TrueVal);
3540     if (swapSides) {
3541       CC = ISD::getSetCCSwappedOperands(CC);
3542       std::swap(LHS, RHS);
3543     }
3544     if (LHS == TrueVal && RHS == FalseVal) {
3545       bool canTransform = true;
3546       // FIXME: FastMathFlags::noSignedZeros() doesn't appear reachable from here
3547       if (!getTargetMachine().Options.UnsafeFPMath &&
3548           !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
3549         const ConstantFPSDNode *Zero;
3550         switch (CC) {
3551         default:
3552           break;
3553         case ISD::SETOGT:
3554         case ISD::SETUGT:
3555         case ISD::SETGT:
3556           // RHS must not be -0
3557           canTransform = (Zero = dyn_cast<ConstantFPSDNode>(RHS)) &&
3558                          !Zero->isNegative();
3559           break;
3560         case ISD::SETOGE:
3561         case ISD::SETUGE:
3562         case ISD::SETGE:
3563           // LHS must not be -0
3564           canTransform = (Zero = dyn_cast<ConstantFPSDNode>(LHS)) &&
3565                          !Zero->isNegative();
3566           break;
3567         case ISD::SETOLT:
3568         case ISD::SETULT:
3569         case ISD::SETLT:
3570           // RHS must not be +0
3571           canTransform = (Zero = dyn_cast<ConstantFPSDNode>(RHS)) &&
3572                           Zero->isNegative();
3573           break;
3574         case ISD::SETOLE:
3575         case ISD::SETULE:
3576         case ISD::SETLE:
3577           // LHS must not be +0
3578           canTransform = (Zero = dyn_cast<ConstantFPSDNode>(LHS)) &&
3579                           Zero->isNegative();
3580           break;
3581         }
3582       }
3583       if (canTransform) {
3584         // Note: If one of the elements in a pair is a number and the other
3585         // element is NaN, the corresponding result element is the number.
3586         // This is consistent with the IEEE 754-2008 standard.
3587         // Therefore, a > b ? a : b <=> vmax(a,b), if b is constant and a is NaN
3588         switch (CC) {
3589         default:
3590           break;
3591         case ISD::SETOGT:
3592         case ISD::SETOGE:
3593           if (!DAG.isKnownNeverNaN(RHS))
3594             break;
3595           return DAG.getNode(ARMISD::VMAXNM, dl, VT, LHS, RHS);
3596         case ISD::SETUGT:
3597         case ISD::SETUGE:
3598           if (!DAG.isKnownNeverNaN(LHS))
3599             break;
3600         case ISD::SETGT:
3601         case ISD::SETGE:
3602           return DAG.getNode(ARMISD::VMAXNM, dl, VT, LHS, RHS);
3603         case ISD::SETOLT:
3604         case ISD::SETOLE:
3605           if (!DAG.isKnownNeverNaN(RHS))
3606             break;
3607           return DAG.getNode(ARMISD::VMINNM, dl, VT, LHS, RHS);
3608         case ISD::SETULT:
3609         case ISD::SETULE:
3610           if (!DAG.isKnownNeverNaN(LHS))
3611             break;
3612         case ISD::SETLT:
3613         case ISD::SETLE:
3614           return DAG.getNode(ARMISD::VMINNM, dl, VT, LHS, RHS);
3615         }
3616       }
3617     }
3618
3619     bool swpCmpOps = false;
3620     bool swpVselOps = false;
3621     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3622
3623     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3624         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3625       if (swpCmpOps)
3626         std::swap(LHS, RHS);
3627       if (swpVselOps)
3628         std::swap(TrueVal, FalseVal);
3629     }
3630   }
3631
3632   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3633   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3634   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3635   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3636   if (CondCode2 != ARMCC::AL) {
3637     SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
3638     // FIXME: Needs another CMP because flag can have but one use.
3639     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3640     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3641   }
3642   return Result;
3643 }
3644
3645 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3646 /// to morph to an integer compare sequence.
3647 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3648                            const ARMSubtarget *Subtarget) {
3649   SDNode *N = Op.getNode();
3650   if (!N->hasOneUse())
3651     // Otherwise it requires moving the value from fp to integer registers.
3652     return false;
3653   if (!N->getNumValues())
3654     return false;
3655   EVT VT = Op.getValueType();
3656   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3657     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3658     // vmrs are very slow, e.g. cortex-a8.
3659     return false;
3660
3661   if (isFloatingPointZero(Op)) {
3662     SeenZero = true;
3663     return true;
3664   }
3665   return ISD::isNormalLoad(N);
3666 }
3667
3668 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3669   if (isFloatingPointZero(Op))
3670     return DAG.getConstant(0, SDLoc(Op), MVT::i32);
3671
3672   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3673     return DAG.getLoad(MVT::i32, SDLoc(Op),
3674                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3675                        Ld->isVolatile(), Ld->isNonTemporal(),
3676                        Ld->isInvariant(), Ld->getAlignment());
3677
3678   llvm_unreachable("Unknown VFP cmp argument!");
3679 }
3680
3681 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3682                            SDValue &RetVal1, SDValue &RetVal2) {
3683   SDLoc dl(Op);
3684
3685   if (isFloatingPointZero(Op)) {
3686     RetVal1 = DAG.getConstant(0, dl, MVT::i32);
3687     RetVal2 = DAG.getConstant(0, dl, MVT::i32);
3688     return;
3689   }
3690
3691   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3692     SDValue Ptr = Ld->getBasePtr();
3693     RetVal1 = DAG.getLoad(MVT::i32, dl,
3694                           Ld->getChain(), Ptr,
3695                           Ld->getPointerInfo(),
3696                           Ld->isVolatile(), Ld->isNonTemporal(),
3697                           Ld->isInvariant(), Ld->getAlignment());
3698
3699     EVT PtrType = Ptr.getValueType();
3700     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3701     SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
3702                                  PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
3703     RetVal2 = DAG.getLoad(MVT::i32, dl,
3704                           Ld->getChain(), NewPtr,
3705                           Ld->getPointerInfo().getWithOffset(4),
3706                           Ld->isVolatile(), Ld->isNonTemporal(),
3707                           Ld->isInvariant(), NewAlign);
3708     return;
3709   }
3710
3711   llvm_unreachable("Unknown VFP cmp argument!");
3712 }
3713
3714 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3715 /// f32 and even f64 comparisons to integer ones.
3716 SDValue
3717 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3718   SDValue Chain = Op.getOperand(0);
3719   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3720   SDValue LHS = Op.getOperand(2);
3721   SDValue RHS = Op.getOperand(3);
3722   SDValue Dest = Op.getOperand(4);
3723   SDLoc dl(Op);
3724
3725   bool LHSSeenZero = false;
3726   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3727   bool RHSSeenZero = false;
3728   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3729   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3730     // If unsafe fp math optimization is enabled and there are no other uses of
3731     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3732     // to an integer comparison.
3733     if (CC == ISD::SETOEQ)
3734       CC = ISD::SETEQ;
3735     else if (CC == ISD::SETUNE)
3736       CC = ISD::SETNE;
3737
3738     SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
3739     SDValue ARMcc;
3740     if (LHS.getValueType() == MVT::f32) {
3741       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3742                         bitcastf32Toi32(LHS, DAG), Mask);
3743       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3744                         bitcastf32Toi32(RHS, DAG), Mask);
3745       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3746       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3747       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3748                          Chain, Dest, ARMcc, CCR, Cmp);
3749     }
3750
3751     SDValue LHS1, LHS2;
3752     SDValue RHS1, RHS2;
3753     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3754     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3755     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3756     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3757     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3758     ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3759     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3760     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3761     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3762   }
3763
3764   return SDValue();
3765 }
3766
3767 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3768   SDValue Chain = Op.getOperand(0);
3769   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3770   SDValue LHS = Op.getOperand(2);
3771   SDValue RHS = Op.getOperand(3);
3772   SDValue Dest = Op.getOperand(4);
3773   SDLoc dl(Op);
3774
3775   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3776     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3777                                                     dl);
3778
3779     // If softenSetCCOperands only returned one value, we should compare it to
3780     // zero.
3781     if (!RHS.getNode()) {
3782       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3783       CC = ISD::SETNE;
3784     }
3785   }
3786
3787   if (LHS.getValueType() == MVT::i32) {
3788     SDValue ARMcc;
3789     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3790     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3791     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3792                        Chain, Dest, ARMcc, CCR, Cmp);
3793   }
3794
3795   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3796
3797   if (getTargetMachine().Options.UnsafeFPMath &&
3798       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3799        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3800     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3801     if (Result.getNode())
3802       return Result;
3803   }
3804
3805   ARMCC::CondCodes CondCode, CondCode2;
3806   FPCCToARMCC(CC, CondCode, CondCode2);
3807
3808   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3809   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3810   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3811   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3812   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3813   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3814   if (CondCode2 != ARMCC::AL) {
3815     ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
3816     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3817     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3818   }
3819   return Res;
3820 }
3821
3822 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3823   SDValue Chain = Op.getOperand(0);
3824   SDValue Table = Op.getOperand(1);
3825   SDValue Index = Op.getOperand(2);
3826   SDLoc dl(Op);
3827
3828   EVT PTy = getPointerTy();
3829   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3830   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3831   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), dl, PTy);
3832   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3833   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3834   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
3835   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3836   if (Subtarget->isThumb2()) {
3837     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3838     // which does another jump to the destination. This also makes it easier
3839     // to translate it to TBB / TBH later.
3840     // FIXME: This might not work if the function is extremely large.
3841     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3842                        Addr, Op.getOperand(2), JTI, UId);
3843   }
3844   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3845     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3846                        MachinePointerInfo::getJumpTable(),
3847                        false, false, false, 0);
3848     Chain = Addr.getValue(1);
3849     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3850     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3851   } else {
3852     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3853                        MachinePointerInfo::getJumpTable(),
3854                        false, false, false, 0);
3855     Chain = Addr.getValue(1);
3856     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3857   }
3858 }
3859
3860 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3861   EVT VT = Op.getValueType();
3862   SDLoc dl(Op);
3863
3864   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3865     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3866       return Op;
3867     return DAG.UnrollVectorOp(Op.getNode());
3868   }
3869
3870   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3871          "Invalid type for custom lowering!");
3872   if (VT != MVT::v4i16)
3873     return DAG.UnrollVectorOp(Op.getNode());
3874
3875   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3876   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3877 }
3878
3879 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3880   EVT VT = Op.getValueType();
3881   if (VT.isVector())
3882     return LowerVectorFP_TO_INT(Op, DAG);
3883   if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3884     RTLIB::Libcall LC;
3885     if (Op.getOpcode() == ISD::FP_TO_SINT)
3886       LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
3887                               Op.getValueType());
3888     else
3889       LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
3890                               Op.getValueType());
3891     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3892                        /*isSigned*/ false, SDLoc(Op)).first;
3893   }
3894
3895   return Op;
3896 }
3897
3898 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3899   EVT VT = Op.getValueType();
3900   SDLoc dl(Op);
3901
3902   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3903     if (VT.getVectorElementType() == MVT::f32)
3904       return Op;
3905     return DAG.UnrollVectorOp(Op.getNode());
3906   }
3907
3908   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3909          "Invalid type for custom lowering!");
3910   if (VT != MVT::v4f32)
3911     return DAG.UnrollVectorOp(Op.getNode());
3912
3913   unsigned CastOpc;
3914   unsigned Opc;
3915   switch (Op.getOpcode()) {
3916   default: llvm_unreachable("Invalid opcode!");
3917   case ISD::SINT_TO_FP:
3918     CastOpc = ISD::SIGN_EXTEND;
3919     Opc = ISD::SINT_TO_FP;
3920     break;
3921   case ISD::UINT_TO_FP:
3922     CastOpc = ISD::ZERO_EXTEND;
3923     Opc = ISD::UINT_TO_FP;
3924     break;
3925   }
3926
3927   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3928   return DAG.getNode(Opc, dl, VT, Op);
3929 }
3930
3931 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
3932   EVT VT = Op.getValueType();
3933   if (VT.isVector())
3934     return LowerVectorINT_TO_FP(Op, DAG);
3935   if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
3936     RTLIB::Libcall LC;
3937     if (Op.getOpcode() == ISD::SINT_TO_FP)
3938       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
3939                               Op.getValueType());
3940     else
3941       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
3942                               Op.getValueType());
3943     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3944                        /*isSigned*/ false, SDLoc(Op)).first;
3945   }
3946
3947   return Op;
3948 }
3949
3950 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3951   // Implement fcopysign with a fabs and a conditional fneg.
3952   SDValue Tmp0 = Op.getOperand(0);
3953   SDValue Tmp1 = Op.getOperand(1);
3954   SDLoc dl(Op);
3955   EVT VT = Op.getValueType();
3956   EVT SrcVT = Tmp1.getValueType();
3957   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3958     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3959   bool UseNEON = !InGPR && Subtarget->hasNEON();
3960
3961   if (UseNEON) {
3962     // Use VBSL to copy the sign bit.
3963     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3964     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3965                                DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
3966     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3967     if (VT == MVT::f64)
3968       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3969                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3970                          DAG.getConstant(32, dl, MVT::i32));
3971     else /*if (VT == MVT::f32)*/
3972       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3973     if (SrcVT == MVT::f32) {
3974       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3975       if (VT == MVT::f64)
3976         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3977                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3978                            DAG.getConstant(32, dl, MVT::i32));
3979     } else if (VT == MVT::f32)
3980       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3981                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3982                          DAG.getConstant(32, dl, MVT::i32));
3983     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3984     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3985
3986     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3987                                             dl, MVT::i32);
3988     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3989     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3990                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3991
3992     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3993                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3994                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3995     if (VT == MVT::f32) {
3996       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3997       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3998                         DAG.getConstant(0, dl, MVT::i32));
3999     } else {
4000       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4001     }
4002
4003     return Res;
4004   }
4005
4006   // Bitcast operand 1 to i32.
4007   if (SrcVT == MVT::f64)
4008     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4009                        Tmp1).getValue(1);
4010   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4011
4012   // Or in the signbit with integer operations.
4013   SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
4014   SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4015   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4016   if (VT == MVT::f32) {
4017     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4018                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4019     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4020                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4021   }
4022
4023   // f64: Or the high part with signbit and then combine two parts.
4024   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4025                      Tmp0);
4026   SDValue Lo = Tmp0.getValue(0);
4027   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4028   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4029   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4030 }
4031
4032 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4033   MachineFunction &MF = DAG.getMachineFunction();
4034   MachineFrameInfo *MFI = MF.getFrameInfo();
4035   MFI->setReturnAddressIsTaken(true);
4036
4037   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4038     return SDValue();
4039
4040   EVT VT = Op.getValueType();
4041   SDLoc dl(Op);
4042   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4043   if (Depth) {
4044     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4045     SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
4046     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4047                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4048                        MachinePointerInfo(), false, false, false, 0);
4049   }
4050
4051   // Return LR, which contains the return address. Mark it an implicit live-in.
4052   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4053   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4054 }
4055
4056 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4057   const ARMBaseRegisterInfo &ARI =
4058     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4059   MachineFunction &MF = DAG.getMachineFunction();
4060   MachineFrameInfo *MFI = MF.getFrameInfo();
4061   MFI->setFrameAddressIsTaken(true);
4062
4063   EVT VT = Op.getValueType();
4064   SDLoc dl(Op);  // FIXME probably not meaningful
4065   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4066   unsigned FrameReg = ARI.getFrameRegister(MF);
4067   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4068   while (Depth--)
4069     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4070                             MachinePointerInfo(),
4071                             false, false, false, 0);
4072   return FrameAddr;
4073 }
4074
4075 // FIXME? Maybe this could be a TableGen attribute on some registers and
4076 // this table could be generated automatically from RegInfo.
4077 unsigned ARMTargetLowering::getRegisterByName(const char* RegName,
4078                                               EVT VT) const {
4079   unsigned Reg = StringSwitch<unsigned>(RegName)
4080                        .Case("sp", ARM::SP)
4081                        .Default(0);
4082   if (Reg)
4083     return Reg;
4084   report_fatal_error("Invalid register name global variable");
4085 }
4086
4087 /// ExpandBITCAST - If the target supports VFP, this function is called to
4088 /// expand a bit convert where either the source or destination type is i64 to
4089 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
4090 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4091 /// vectors), since the legalizer won't know what to do with that.
4092 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4093   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4094   SDLoc dl(N);
4095   SDValue Op = N->getOperand(0);
4096
4097   // This function is only supposed to be called for i64 types, either as the
4098   // source or destination of the bit convert.
4099   EVT SrcVT = Op.getValueType();
4100   EVT DstVT = N->getValueType(0);
4101   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4102          "ExpandBITCAST called for non-i64 type");
4103
4104   // Turn i64->f64 into VMOVDRR.
4105   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4106     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4107                              DAG.getConstant(0, dl, MVT::i32));
4108     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4109                              DAG.getConstant(1, dl, MVT::i32));
4110     return DAG.getNode(ISD::BITCAST, dl, DstVT,
4111                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4112   }
4113
4114   // Turn f64->i64 into VMOVRRD.
4115   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4116     SDValue Cvt;
4117     if (TLI.isBigEndian() && SrcVT.isVector() &&
4118         SrcVT.getVectorNumElements() > 1)
4119       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4120                         DAG.getVTList(MVT::i32, MVT::i32),
4121                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4122     else
4123       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4124                         DAG.getVTList(MVT::i32, MVT::i32), Op);
4125     // Merge the pieces into a single i64 value.
4126     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4127   }
4128
4129   return SDValue();
4130 }
4131
4132 /// getZeroVector - Returns a vector of specified type with all zero elements.
4133 /// Zero vectors are used to represent vector negation and in those cases
4134 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
4135 /// not support i64 elements, so sometimes the zero vectors will need to be
4136 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
4137 /// zero vector.
4138 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4139   assert(VT.isVector() && "Expected a vector type");
4140   // The canonical modified immediate encoding of a zero vector is....0!
4141   SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
4142   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4143   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4144   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4145 }
4146
4147 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4148 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4149 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4150                                                 SelectionDAG &DAG) const {
4151   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4152   EVT VT = Op.getValueType();
4153   unsigned VTBits = VT.getSizeInBits();
4154   SDLoc dl(Op);
4155   SDValue ShOpLo = Op.getOperand(0);
4156   SDValue ShOpHi = Op.getOperand(1);
4157   SDValue ShAmt  = Op.getOperand(2);
4158   SDValue ARMcc;
4159   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4160
4161   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4162
4163   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4164                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4165   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4166   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4167                                    DAG.getConstant(VTBits, dl, MVT::i32));
4168   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4169   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4170   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4171
4172   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4173   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4174                           ISD::SETGE, ARMcc, DAG, dl);
4175   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4176   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4177                            CCR, Cmp);
4178
4179   SDValue Ops[2] = { Lo, Hi };
4180   return DAG.getMergeValues(Ops, dl);
4181 }
4182
4183 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4184 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4185 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4186                                                SelectionDAG &DAG) const {
4187   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4188   EVT VT = Op.getValueType();
4189   unsigned VTBits = VT.getSizeInBits();
4190   SDLoc dl(Op);
4191   SDValue ShOpLo = Op.getOperand(0);
4192   SDValue ShOpHi = Op.getOperand(1);
4193   SDValue ShAmt  = Op.getOperand(2);
4194   SDValue ARMcc;
4195
4196   assert(Op.getOpcode() == ISD::SHL_PARTS);
4197   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4198                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4199   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4200   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4201                                    DAG.getConstant(VTBits, dl, MVT::i32));
4202   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4203   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4204
4205   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4206   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4207   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4208                           ISD::SETGE, ARMcc, DAG, dl);
4209   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4210   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4211                            CCR, Cmp);
4212
4213   SDValue Ops[2] = { Lo, Hi };
4214   return DAG.getMergeValues(Ops, dl);
4215 }
4216
4217 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4218                                             SelectionDAG &DAG) const {
4219   // The rounding mode is in bits 23:22 of the FPSCR.
4220   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4221   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4222   // so that the shift + and get folded into a bitfield extract.
4223   SDLoc dl(Op);
4224   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4225                               DAG.getConstant(Intrinsic::arm_get_fpscr, dl,
4226                                               MVT::i32));
4227   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4228                                   DAG.getConstant(1U << 22, dl, MVT::i32));
4229   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4230                               DAG.getConstant(22, dl, MVT::i32));
4231   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4232                      DAG.getConstant(3, dl, MVT::i32));
4233 }
4234
4235 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4236                          const ARMSubtarget *ST) {
4237   EVT VT = N->getValueType(0);
4238   SDLoc dl(N);
4239
4240   if (!ST->hasV6T2Ops())
4241     return SDValue();
4242
4243   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4244   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4245 }
4246
4247 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4248 /// for each 16-bit element from operand, repeated.  The basic idea is to
4249 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4250 ///
4251 /// Trace for v4i16:
4252 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
4253 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4254 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4255 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4256 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
4257 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
4258 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4259 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
4260 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4261   EVT VT = N->getValueType(0);
4262   SDLoc DL(N);
4263
4264   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4265   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4266   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4267   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4268   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4269   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4270 }
4271
4272 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4273 /// bit-count for each 16-bit element from the operand.  We need slightly
4274 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4275 /// 64/128-bit registers.
4276 ///
4277 /// Trace for v4i16:
4278 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
4279 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4280 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
4281 /// v4i16:Extracted = [k0    k1    k2    k3    ]
4282 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4283   EVT VT = N->getValueType(0);
4284   SDLoc DL(N);
4285
4286   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4287   if (VT.is64BitVector()) {
4288     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4289     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4290                        DAG.getIntPtrConstant(0, DL));
4291   } else {
4292     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4293                                     BitCounts, DAG.getIntPtrConstant(0, DL));
4294     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4295   }
4296 }
4297
4298 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4299 /// bit-count for each 32-bit element from the operand.  The idea here is
4300 /// to split the vector into 16-bit elements, leverage the 16-bit count
4301 /// routine, and then combine the results.
4302 ///
4303 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4304 /// input    = [v0    v1    ] (vi: 32-bit elements)
4305 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4306 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4307 /// vrev: N0 = [k1 k0 k3 k2 ]
4308 ///            [k0 k1 k2 k3 ]
4309 ///       N1 =+[k1 k0 k3 k2 ]
4310 ///            [k0 k2 k1 k3 ]
4311 ///       N2 =+[k1 k3 k0 k2 ]
4312 ///            [k0    k2    k1    k3    ]
4313 /// Extended =+[k1    k3    k0    k2    ]
4314 ///            [k0    k2    ]
4315 /// Extracted=+[k1    k3    ]
4316 ///
4317 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4318   EVT VT = N->getValueType(0);
4319   SDLoc DL(N);
4320
4321   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4322
4323   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4324   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4325   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4326   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4327   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4328
4329   if (VT.is64BitVector()) {
4330     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4331     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4332                        DAG.getIntPtrConstant(0, DL));
4333   } else {
4334     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4335                                     DAG.getIntPtrConstant(0, DL));
4336     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4337   }
4338 }
4339
4340 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4341                           const ARMSubtarget *ST) {
4342   EVT VT = N->getValueType(0);
4343
4344   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4345   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4346           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4347          "Unexpected type for custom ctpop lowering");
4348
4349   if (VT.getVectorElementType() == MVT::i32)
4350     return lowerCTPOP32BitElements(N, DAG);
4351   else
4352     return lowerCTPOP16BitElements(N, DAG);
4353 }
4354
4355 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4356                           const ARMSubtarget *ST) {
4357   EVT VT = N->getValueType(0);
4358   SDLoc dl(N);
4359
4360   if (!VT.isVector())
4361     return SDValue();
4362
4363   // Lower vector shifts on NEON to use VSHL.
4364   assert(ST->hasNEON() && "unexpected vector shift");
4365
4366   // Left shifts translate directly to the vshiftu intrinsic.
4367   if (N->getOpcode() == ISD::SHL)
4368     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4369                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
4370                                        MVT::i32),
4371                        N->getOperand(0), N->getOperand(1));
4372
4373   assert((N->getOpcode() == ISD::SRA ||
4374           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4375
4376   // NEON uses the same intrinsics for both left and right shifts.  For
4377   // right shifts, the shift amounts are negative, so negate the vector of
4378   // shift amounts.
4379   EVT ShiftVT = N->getOperand(1).getValueType();
4380   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4381                                      getZeroVector(ShiftVT, DAG, dl),
4382                                      N->getOperand(1));
4383   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4384                              Intrinsic::arm_neon_vshifts :
4385                              Intrinsic::arm_neon_vshiftu);
4386   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4387                      DAG.getConstant(vshiftInt, dl, MVT::i32),
4388                      N->getOperand(0), NegatedCount);
4389 }
4390
4391 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4392                                 const ARMSubtarget *ST) {
4393   EVT VT = N->getValueType(0);
4394   SDLoc dl(N);
4395
4396   // We can get here for a node like i32 = ISD::SHL i32, i64
4397   if (VT != MVT::i64)
4398     return SDValue();
4399
4400   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4401          "Unknown shift to lower!");
4402
4403   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4404   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4405       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4406     return SDValue();
4407
4408   // If we are in thumb mode, we don't have RRX.
4409   if (ST->isThumb1Only()) return SDValue();
4410
4411   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4412   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4413                            DAG.getConstant(0, dl, MVT::i32));
4414   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4415                            DAG.getConstant(1, dl, MVT::i32));
4416
4417   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4418   // captures the result into a carry flag.
4419   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4420   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4421
4422   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4423   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4424
4425   // Merge the pieces into a single i64 value.
4426  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4427 }
4428
4429 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4430   SDValue TmpOp0, TmpOp1;
4431   bool Invert = false;
4432   bool Swap = false;
4433   unsigned Opc = 0;
4434
4435   SDValue Op0 = Op.getOperand(0);
4436   SDValue Op1 = Op.getOperand(1);
4437   SDValue CC = Op.getOperand(2);
4438   EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
4439   EVT VT = Op.getValueType();
4440   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4441   SDLoc dl(Op);
4442
4443   if (Op1.getValueType().isFloatingPoint()) {
4444     switch (SetCCOpcode) {
4445     default: llvm_unreachable("Illegal FP comparison");
4446     case ISD::SETUNE:
4447     case ISD::SETNE:  Invert = true; // Fallthrough
4448     case ISD::SETOEQ:
4449     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4450     case ISD::SETOLT:
4451     case ISD::SETLT: Swap = true; // Fallthrough
4452     case ISD::SETOGT:
4453     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4454     case ISD::SETOLE:
4455     case ISD::SETLE:  Swap = true; // Fallthrough
4456     case ISD::SETOGE:
4457     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4458     case ISD::SETUGE: Swap = true; // Fallthrough
4459     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4460     case ISD::SETUGT: Swap = true; // Fallthrough
4461     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4462     case ISD::SETUEQ: Invert = true; // Fallthrough
4463     case ISD::SETONE:
4464       // Expand this to (OLT | OGT).
4465       TmpOp0 = Op0;
4466       TmpOp1 = Op1;
4467       Opc = ISD::OR;
4468       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4469       Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
4470       break;
4471     case ISD::SETUO: Invert = true; // Fallthrough
4472     case ISD::SETO:
4473       // Expand this to (OLT | OGE).
4474       TmpOp0 = Op0;
4475       TmpOp1 = Op1;
4476       Opc = ISD::OR;
4477       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4478       Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
4479       break;
4480     }
4481   } else {
4482     // Integer comparisons.
4483     switch (SetCCOpcode) {
4484     default: llvm_unreachable("Illegal integer comparison");
4485     case ISD::SETNE:  Invert = true;
4486     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4487     case ISD::SETLT:  Swap = true;
4488     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4489     case ISD::SETLE:  Swap = true;
4490     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4491     case ISD::SETULT: Swap = true;
4492     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4493     case ISD::SETULE: Swap = true;
4494     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4495     }
4496
4497     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4498     if (Opc == ARMISD::VCEQ) {
4499
4500       SDValue AndOp;
4501       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4502         AndOp = Op0;
4503       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4504         AndOp = Op1;
4505
4506       // Ignore bitconvert.
4507       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4508         AndOp = AndOp.getOperand(0);
4509
4510       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4511         Opc = ARMISD::VTST;
4512         Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
4513         Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
4514         Invert = !Invert;
4515       }
4516     }
4517   }
4518
4519   if (Swap)
4520     std::swap(Op0, Op1);
4521
4522   // If one of the operands is a constant vector zero, attempt to fold the
4523   // comparison to a specialized compare-against-zero form.
4524   SDValue SingleOp;
4525   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4526     SingleOp = Op0;
4527   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4528     if (Opc == ARMISD::VCGE)
4529       Opc = ARMISD::VCLEZ;
4530     else if (Opc == ARMISD::VCGT)
4531       Opc = ARMISD::VCLTZ;
4532     SingleOp = Op1;
4533   }
4534
4535   SDValue Result;
4536   if (SingleOp.getNode()) {
4537     switch (Opc) {
4538     case ARMISD::VCEQ:
4539       Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
4540     case ARMISD::VCGE:
4541       Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
4542     case ARMISD::VCLEZ:
4543       Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
4544     case ARMISD::VCGT:
4545       Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
4546     case ARMISD::VCLTZ:
4547       Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
4548     default:
4549       Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4550     }
4551   } else {
4552      Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4553   }
4554
4555   Result = DAG.getSExtOrTrunc(Result, dl, VT);
4556
4557   if (Invert)
4558     Result = DAG.getNOT(dl, Result, VT);
4559
4560   return Result;
4561 }
4562
4563 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4564 /// valid vector constant for a NEON instruction with a "modified immediate"
4565 /// operand (e.g., VMOV).  If so, return the encoded value.
4566 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4567                                  unsigned SplatBitSize, SelectionDAG &DAG,
4568                                  SDLoc dl, EVT &VT, bool is128Bits,
4569                                  NEONModImmType type) {
4570   unsigned OpCmode, Imm;
4571
4572   // SplatBitSize is set to the smallest size that splats the vector, so a
4573   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4574   // immediate instructions others than VMOV do not support the 8-bit encoding
4575   // of a zero vector, and the default encoding of zero is supposed to be the
4576   // 32-bit version.
4577   if (SplatBits == 0)
4578     SplatBitSize = 32;
4579
4580   switch (SplatBitSize) {
4581   case 8:
4582     if (type != VMOVModImm)
4583       return SDValue();
4584     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4585     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4586     OpCmode = 0xe;
4587     Imm = SplatBits;
4588     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4589     break;
4590
4591   case 16:
4592     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4593     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4594     if ((SplatBits & ~0xff) == 0) {
4595       // Value = 0x00nn: Op=x, Cmode=100x.
4596       OpCmode = 0x8;
4597       Imm = SplatBits;
4598       break;
4599     }
4600     if ((SplatBits & ~0xff00) == 0) {
4601       // Value = 0xnn00: Op=x, Cmode=101x.
4602       OpCmode = 0xa;
4603       Imm = SplatBits >> 8;
4604       break;
4605     }
4606     return SDValue();
4607
4608   case 32:
4609     // NEON's 32-bit VMOV supports splat values where:
4610     // * only one byte is nonzero, or
4611     // * the least significant byte is 0xff and the second byte is nonzero, or
4612     // * the least significant 2 bytes are 0xff and the third is nonzero.
4613     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4614     if ((SplatBits & ~0xff) == 0) {
4615       // Value = 0x000000nn: Op=x, Cmode=000x.
4616       OpCmode = 0;
4617       Imm = SplatBits;
4618       break;
4619     }
4620     if ((SplatBits & ~0xff00) == 0) {
4621       // Value = 0x0000nn00: Op=x, Cmode=001x.
4622       OpCmode = 0x2;
4623       Imm = SplatBits >> 8;
4624       break;
4625     }
4626     if ((SplatBits & ~0xff0000) == 0) {
4627       // Value = 0x00nn0000: Op=x, Cmode=010x.
4628       OpCmode = 0x4;
4629       Imm = SplatBits >> 16;
4630       break;
4631     }
4632     if ((SplatBits & ~0xff000000) == 0) {
4633       // Value = 0xnn000000: Op=x, Cmode=011x.
4634       OpCmode = 0x6;
4635       Imm = SplatBits >> 24;
4636       break;
4637     }
4638
4639     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4640     if (type == OtherModImm) return SDValue();
4641
4642     if ((SplatBits & ~0xffff) == 0 &&
4643         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4644       // Value = 0x0000nnff: Op=x, Cmode=1100.
4645       OpCmode = 0xc;
4646       Imm = SplatBits >> 8;
4647       break;
4648     }
4649
4650     if ((SplatBits & ~0xffffff) == 0 &&
4651         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4652       // Value = 0x00nnffff: Op=x, Cmode=1101.
4653       OpCmode = 0xd;
4654       Imm = SplatBits >> 16;
4655       break;
4656     }
4657
4658     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4659     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4660     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4661     // and fall through here to test for a valid 64-bit splat.  But, then the
4662     // caller would also need to check and handle the change in size.
4663     return SDValue();
4664
4665   case 64: {
4666     if (type != VMOVModImm)
4667       return SDValue();
4668     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4669     uint64_t BitMask = 0xff;
4670     uint64_t Val = 0;
4671     unsigned ImmMask = 1;
4672     Imm = 0;
4673     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4674       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4675         Val |= BitMask;
4676         Imm |= ImmMask;
4677       } else if ((SplatBits & BitMask) != 0) {
4678         return SDValue();
4679       }
4680       BitMask <<= 8;
4681       ImmMask <<= 1;
4682     }
4683
4684     if (DAG.getTargetLoweringInfo().isBigEndian())
4685       // swap higher and lower 32 bit word
4686       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4687
4688     // Op=1, Cmode=1110.
4689     OpCmode = 0x1e;
4690     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4691     break;
4692   }
4693
4694   default:
4695     llvm_unreachable("unexpected size for isNEONModifiedImm");
4696   }
4697
4698   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4699   return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
4700 }
4701
4702 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4703                                            const ARMSubtarget *ST) const {
4704   if (!ST->hasVFP3())
4705     return SDValue();
4706
4707   bool IsDouble = Op.getValueType() == MVT::f64;
4708   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4709
4710   // Use the default (constant pool) lowering for double constants when we have
4711   // an SP-only FPU
4712   if (IsDouble && Subtarget->isFPOnlySP())
4713     return SDValue();
4714
4715   // Try splatting with a VMOV.f32...
4716   APFloat FPVal = CFP->getValueAPF();
4717   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4718
4719   if (ImmVal != -1) {
4720     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4721       // We have code in place to select a valid ConstantFP already, no need to
4722       // do any mangling.
4723       return Op;
4724     }
4725
4726     // It's a float and we are trying to use NEON operations where
4727     // possible. Lower it to a splat followed by an extract.
4728     SDLoc DL(Op);
4729     SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
4730     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4731                                       NewVal);
4732     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4733                        DAG.getConstant(0, DL, MVT::i32));
4734   }
4735
4736   // The rest of our options are NEON only, make sure that's allowed before
4737   // proceeding..
4738   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4739     return SDValue();
4740
4741   EVT VMovVT;
4742   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4743
4744   // It wouldn't really be worth bothering for doubles except for one very
4745   // important value, which does happen to match: 0.0. So make sure we don't do
4746   // anything stupid.
4747   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4748     return SDValue();
4749
4750   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4751   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
4752                                      VMovVT, false, VMOVModImm);
4753   if (NewVal != SDValue()) {
4754     SDLoc DL(Op);
4755     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4756                                       NewVal);
4757     if (IsDouble)
4758       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4759
4760     // It's a float: cast and extract a vector element.
4761     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4762                                        VecConstant);
4763     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4764                        DAG.getConstant(0, DL, MVT::i32));
4765   }
4766
4767   // Finally, try a VMVN.i32
4768   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
4769                              false, VMVNModImm);
4770   if (NewVal != SDValue()) {
4771     SDLoc DL(Op);
4772     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4773
4774     if (IsDouble)
4775       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4776
4777     // It's a float: cast and extract a vector element.
4778     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4779                                        VecConstant);
4780     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4781                        DAG.getConstant(0, DL, MVT::i32));
4782   }
4783
4784   return SDValue();
4785 }
4786
4787 // check if an VEXT instruction can handle the shuffle mask when the
4788 // vector sources of the shuffle are the same.
4789 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4790   unsigned NumElts = VT.getVectorNumElements();
4791
4792   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4793   if (M[0] < 0)
4794     return false;
4795
4796   Imm = M[0];
4797
4798   // If this is a VEXT shuffle, the immediate value is the index of the first
4799   // element.  The other shuffle indices must be the successive elements after
4800   // the first one.
4801   unsigned ExpectedElt = Imm;
4802   for (unsigned i = 1; i < NumElts; ++i) {
4803     // Increment the expected index.  If it wraps around, just follow it
4804     // back to index zero and keep going.
4805     ++ExpectedElt;
4806     if (ExpectedElt == NumElts)
4807       ExpectedElt = 0;
4808
4809     if (M[i] < 0) continue; // ignore UNDEF indices
4810     if (ExpectedElt != static_cast<unsigned>(M[i]))
4811       return false;
4812   }
4813
4814   return true;
4815 }
4816
4817
4818 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4819                        bool &ReverseVEXT, unsigned &Imm) {
4820   unsigned NumElts = VT.getVectorNumElements();
4821   ReverseVEXT = false;
4822
4823   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4824   if (M[0] < 0)
4825     return false;
4826
4827   Imm = M[0];
4828
4829   // If this is a VEXT shuffle, the immediate value is the index of the first
4830   // element.  The other shuffle indices must be the successive elements after
4831   // the first one.
4832   unsigned ExpectedElt = Imm;
4833   for (unsigned i = 1; i < NumElts; ++i) {
4834     // Increment the expected index.  If it wraps around, it may still be
4835     // a VEXT but the source vectors must be swapped.
4836     ExpectedElt += 1;
4837     if (ExpectedElt == NumElts * 2) {
4838       ExpectedElt = 0;
4839       ReverseVEXT = true;
4840     }
4841
4842     if (M[i] < 0) continue; // ignore UNDEF indices
4843     if (ExpectedElt != static_cast<unsigned>(M[i]))
4844       return false;
4845   }
4846
4847   // Adjust the index value if the source operands will be swapped.
4848   if (ReverseVEXT)
4849     Imm -= NumElts;
4850
4851   return true;
4852 }
4853
4854 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4855 /// instruction with the specified blocksize.  (The order of the elements
4856 /// within each block of the vector is reversed.)
4857 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4858   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4859          "Only possible block sizes for VREV are: 16, 32, 64");
4860
4861   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4862   if (EltSz == 64)
4863     return false;
4864
4865   unsigned NumElts = VT.getVectorNumElements();
4866   unsigned BlockElts = M[0] + 1;
4867   // If the first shuffle index is UNDEF, be optimistic.
4868   if (M[0] < 0)
4869     BlockElts = BlockSize / EltSz;
4870
4871   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4872     return false;
4873
4874   for (unsigned i = 0; i < NumElts; ++i) {
4875     if (M[i] < 0) continue; // ignore UNDEF indices
4876     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4877       return false;
4878   }
4879
4880   return true;
4881 }
4882
4883 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4884   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4885   // range, then 0 is placed into the resulting vector. So pretty much any mask
4886   // of 8 elements can work here.
4887   return VT == MVT::v8i8 && M.size() == 8;
4888 }
4889
4890 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4891   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4892   if (EltSz == 64)
4893     return false;
4894
4895   unsigned NumElts = VT.getVectorNumElements();
4896   WhichResult = (M[0] == 0 ? 0 : 1);
4897   for (unsigned i = 0; i < NumElts; i += 2) {
4898     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4899         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4900       return false;
4901   }
4902   return true;
4903 }
4904
4905 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4906 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4907 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4908 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4909   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4910   if (EltSz == 64)
4911     return false;
4912
4913   unsigned NumElts = VT.getVectorNumElements();
4914   WhichResult = (M[0] == 0 ? 0 : 1);
4915   for (unsigned i = 0; i < NumElts; i += 2) {
4916     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4917         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4918       return false;
4919   }
4920   return true;
4921 }
4922
4923 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4924   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4925   if (EltSz == 64)
4926     return false;
4927
4928   unsigned NumElts = VT.getVectorNumElements();
4929   WhichResult = (M[0] == 0 ? 0 : 1);
4930   for (unsigned i = 0; i != NumElts; ++i) {
4931     if (M[i] < 0) continue; // ignore UNDEF indices
4932     if ((unsigned) M[i] != 2 * i + WhichResult)
4933       return false;
4934   }
4935
4936   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4937   if (VT.is64BitVector() && EltSz == 32)
4938     return false;
4939
4940   return true;
4941 }
4942
4943 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4944 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4945 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4946 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4947   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4948   if (EltSz == 64)
4949     return false;
4950
4951   unsigned Half = VT.getVectorNumElements() / 2;
4952   WhichResult = (M[0] == 0 ? 0 : 1);
4953   for (unsigned j = 0; j != 2; ++j) {
4954     unsigned Idx = WhichResult;
4955     for (unsigned i = 0; i != Half; ++i) {
4956       int MIdx = M[i + j * Half];
4957       if (MIdx >= 0 && (unsigned) MIdx != Idx)
4958         return false;
4959       Idx += 2;
4960     }
4961   }
4962
4963   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4964   if (VT.is64BitVector() && EltSz == 32)
4965     return false;
4966
4967   return true;
4968 }
4969
4970 static bool isVZIPMask(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   unsigned Idx = WhichResult * NumElts / 2;
4978   for (unsigned i = 0; i != NumElts; i += 2) {
4979     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4980         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4981       return false;
4982     Idx += 1;
4983   }
4984
4985   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4986   if (VT.is64BitVector() && EltSz == 32)
4987     return false;
4988
4989   return true;
4990 }
4991
4992 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4993 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4994 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4995 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4996   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4997   if (EltSz == 64)
4998     return false;
4999
5000   unsigned NumElts = VT.getVectorNumElements();
5001   WhichResult = (M[0] == 0 ? 0 : 1);
5002   unsigned Idx = WhichResult * NumElts / 2;
5003   for (unsigned i = 0; i != NumElts; i += 2) {
5004     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
5005         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
5006       return false;
5007     Idx += 1;
5008   }
5009
5010   // VZIP.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 /// \return true if this is a reverse operation on an vector.
5018 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5019   unsigned NumElts = VT.getVectorNumElements();
5020   // Make sure the mask has the right size.
5021   if (NumElts != M.size())
5022       return false;
5023
5024   // Look for <15, ..., 3, -1, 1, 0>.
5025   for (unsigned i = 0; i != NumElts; ++i)
5026     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5027       return false;
5028
5029   return true;
5030 }
5031
5032 // If N is an integer constant that can be moved into a register in one
5033 // instruction, return an SDValue of such a constant (will become a MOV
5034 // instruction).  Otherwise return null.
5035 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5036                                      const ARMSubtarget *ST, SDLoc dl) {
5037   uint64_t Val;
5038   if (!isa<ConstantSDNode>(N))
5039     return SDValue();
5040   Val = cast<ConstantSDNode>(N)->getZExtValue();
5041
5042   if (ST->isThumb1Only()) {
5043     if (Val <= 255 || ~Val <= 255)
5044       return DAG.getConstant(Val, dl, MVT::i32);
5045   } else {
5046     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5047       return DAG.getConstant(Val, dl, MVT::i32);
5048   }
5049   return SDValue();
5050 }
5051
5052 // If this is a case we can't handle, return null and let the default
5053 // expansion code take care of it.
5054 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5055                                              const ARMSubtarget *ST) const {
5056   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5057   SDLoc dl(Op);
5058   EVT VT = Op.getValueType();
5059
5060   APInt SplatBits, SplatUndef;
5061   unsigned SplatBitSize;
5062   bool HasAnyUndefs;
5063   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5064     if (SplatBitSize <= 64) {
5065       // Check if an immediate VMOV works.
5066       EVT VmovVT;
5067       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5068                                       SplatUndef.getZExtValue(), SplatBitSize,
5069                                       DAG, dl, VmovVT, VT.is128BitVector(),
5070                                       VMOVModImm);
5071       if (Val.getNode()) {
5072         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5073         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5074       }
5075
5076       // Try an immediate VMVN.
5077       uint64_t NegatedImm = (~SplatBits).getZExtValue();
5078       Val = isNEONModifiedImm(NegatedImm,
5079                                       SplatUndef.getZExtValue(), SplatBitSize,
5080                                       DAG, dl, VmovVT, VT.is128BitVector(),
5081                                       VMVNModImm);
5082       if (Val.getNode()) {
5083         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5084         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5085       }
5086
5087       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5088       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5089         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5090         if (ImmVal != -1) {
5091           SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
5092           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5093         }
5094       }
5095     }
5096   }
5097
5098   // Scan through the operands to see if only one value is used.
5099   //
5100   // As an optimisation, even if more than one value is used it may be more
5101   // profitable to splat with one value then change some lanes.
5102   //
5103   // Heuristically we decide to do this if the vector has a "dominant" value,
5104   // defined as splatted to more than half of the lanes.
5105   unsigned NumElts = VT.getVectorNumElements();
5106   bool isOnlyLowElement = true;
5107   bool usesOnlyOneValue = true;
5108   bool hasDominantValue = false;
5109   bool isConstant = true;
5110
5111   // Map of the number of times a particular SDValue appears in the
5112   // element list.
5113   DenseMap<SDValue, unsigned> ValueCounts;
5114   SDValue Value;
5115   for (unsigned i = 0; i < NumElts; ++i) {
5116     SDValue V = Op.getOperand(i);
5117     if (V.getOpcode() == ISD::UNDEF)
5118       continue;
5119     if (i > 0)
5120       isOnlyLowElement = false;
5121     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5122       isConstant = false;
5123
5124     ValueCounts.insert(std::make_pair(V, 0));
5125     unsigned &Count = ValueCounts[V];
5126
5127     // Is this value dominant? (takes up more than half of the lanes)
5128     if (++Count > (NumElts / 2)) {
5129       hasDominantValue = true;
5130       Value = V;
5131     }
5132   }
5133   if (ValueCounts.size() != 1)
5134     usesOnlyOneValue = false;
5135   if (!Value.getNode() && ValueCounts.size() > 0)
5136     Value = ValueCounts.begin()->first;
5137
5138   if (ValueCounts.size() == 0)
5139     return DAG.getUNDEF(VT);
5140
5141   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5142   // Keep going if we are hitting this case.
5143   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5144     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5145
5146   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5147
5148   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
5149   // i32 and try again.
5150   if (hasDominantValue && EltSize <= 32) {
5151     if (!isConstant) {
5152       SDValue N;
5153
5154       // If we are VDUPing a value that comes directly from a vector, that will
5155       // cause an unnecessary move to and from a GPR, where instead we could
5156       // just use VDUPLANE. We can only do this if the lane being extracted
5157       // is at a constant index, as the VDUP from lane instructions only have
5158       // constant-index forms.
5159       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5160           isa<ConstantSDNode>(Value->getOperand(1))) {
5161         // We need to create a new undef vector to use for the VDUPLANE if the
5162         // size of the vector from which we get the value is different than the
5163         // size of the vector that we need to create. We will insert the element
5164         // such that the register coalescer will remove unnecessary copies.
5165         if (VT != Value->getOperand(0).getValueType()) {
5166           ConstantSDNode *constIndex;
5167           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5168           assert(constIndex && "The index is not a constant!");
5169           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5170                              VT.getVectorNumElements();
5171           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5172                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5173                         Value, DAG.getConstant(index, dl, MVT::i32)),
5174                            DAG.getConstant(index, dl, MVT::i32));
5175         } else
5176           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5177                         Value->getOperand(0), Value->getOperand(1));
5178       } else
5179         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5180
5181       if (!usesOnlyOneValue) {
5182         // The dominant value was splatted as 'N', but we now have to insert
5183         // all differing elements.
5184         for (unsigned I = 0; I < NumElts; ++I) {
5185           if (Op.getOperand(I) == Value)
5186             continue;
5187           SmallVector<SDValue, 3> Ops;
5188           Ops.push_back(N);
5189           Ops.push_back(Op.getOperand(I));
5190           Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
5191           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5192         }
5193       }
5194       return N;
5195     }
5196     if (VT.getVectorElementType().isFloatingPoint()) {
5197       SmallVector<SDValue, 8> Ops;
5198       for (unsigned i = 0; i < NumElts; ++i)
5199         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5200                                   Op.getOperand(i)));
5201       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5202       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5203       Val = LowerBUILD_VECTOR(Val, DAG, ST);
5204       if (Val.getNode())
5205         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5206     }
5207     if (usesOnlyOneValue) {
5208       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5209       if (isConstant && Val.getNode())
5210         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5211     }
5212   }
5213
5214   // If all elements are constants and the case above didn't get hit, fall back
5215   // to the default expansion, which will generate a load from the constant
5216   // pool.
5217   if (isConstant)
5218     return SDValue();
5219
5220   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5221   if (NumElts >= 4) {
5222     SDValue shuffle = ReconstructShuffle(Op, DAG);
5223     if (shuffle != SDValue())
5224       return shuffle;
5225   }
5226
5227   // Vectors with 32- or 64-bit elements can be built by directly assigning
5228   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
5229   // will be legalized.
5230   if (EltSize >= 32) {
5231     // Do the expansion with floating-point types, since that is what the VFP
5232     // registers are defined to use, and since i64 is not legal.
5233     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5234     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5235     SmallVector<SDValue, 8> Ops;
5236     for (unsigned i = 0; i < NumElts; ++i)
5237       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5238     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5239     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5240   }
5241
5242   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5243   // know the default expansion would otherwise fall back on something even
5244   // worse. For a vector with one or two non-undef values, that's
5245   // scalar_to_vector for the elements followed by a shuffle (provided the
5246   // shuffle is valid for the target) and materialization element by element
5247   // on the stack followed by a load for everything else.
5248   if (!isConstant && !usesOnlyOneValue) {
5249     SDValue Vec = DAG.getUNDEF(VT);
5250     for (unsigned i = 0 ; i < NumElts; ++i) {
5251       SDValue V = Op.getOperand(i);
5252       if (V.getOpcode() == ISD::UNDEF)
5253         continue;
5254       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
5255       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5256     }
5257     return Vec;
5258   }
5259
5260   return SDValue();
5261 }
5262
5263 // Gather data to see if the operation can be modelled as a
5264 // shuffle in combination with VEXTs.
5265 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5266                                               SelectionDAG &DAG) const {
5267   SDLoc dl(Op);
5268   EVT VT = Op.getValueType();
5269   unsigned NumElts = VT.getVectorNumElements();
5270
5271   SmallVector<SDValue, 2> SourceVecs;
5272   SmallVector<unsigned, 2> MinElts;
5273   SmallVector<unsigned, 2> MaxElts;
5274
5275   for (unsigned i = 0; i < NumElts; ++i) {
5276     SDValue V = Op.getOperand(i);
5277     if (V.getOpcode() == ISD::UNDEF)
5278       continue;
5279     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5280       // A shuffle can only come from building a vector from various
5281       // elements of other vectors.
5282       return SDValue();
5283     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5284                VT.getVectorElementType()) {
5285       // This code doesn't know how to handle shuffles where the vector
5286       // element types do not match (this happens because type legalization
5287       // promotes the return type of EXTRACT_VECTOR_ELT).
5288       // FIXME: It might be appropriate to extend this code to handle
5289       // mismatched types.
5290       return SDValue();
5291     }
5292
5293     // Record this extraction against the appropriate vector if possible...
5294     SDValue SourceVec = V.getOperand(0);
5295     // If the element number isn't a constant, we can't effectively
5296     // analyze what's going on.
5297     if (!isa<ConstantSDNode>(V.getOperand(1)))
5298       return SDValue();
5299     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5300     bool FoundSource = false;
5301     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5302       if (SourceVecs[j] == SourceVec) {
5303         if (MinElts[j] > EltNo)
5304           MinElts[j] = EltNo;
5305         if (MaxElts[j] < EltNo)
5306           MaxElts[j] = EltNo;
5307         FoundSource = true;
5308         break;
5309       }
5310     }
5311
5312     // Or record a new source if not...
5313     if (!FoundSource) {
5314       SourceVecs.push_back(SourceVec);
5315       MinElts.push_back(EltNo);
5316       MaxElts.push_back(EltNo);
5317     }
5318   }
5319
5320   // Currently only do something sane when at most two source vectors
5321   // involved.
5322   if (SourceVecs.size() > 2)
5323     return SDValue();
5324
5325   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5326   int VEXTOffsets[2] = {0, 0};
5327
5328   // This loop extracts the usage patterns of the source vectors
5329   // and prepares appropriate SDValues for a shuffle if possible.
5330   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5331     if (SourceVecs[i].getValueType() == VT) {
5332       // No VEXT necessary
5333       ShuffleSrcs[i] = SourceVecs[i];
5334       VEXTOffsets[i] = 0;
5335       continue;
5336     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5337       // It probably isn't worth padding out a smaller vector just to
5338       // break it down again in a shuffle.
5339       return SDValue();
5340     }
5341
5342     // Since only 64-bit and 128-bit vectors are legal on ARM and
5343     // we've eliminated the other cases...
5344     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5345            "unexpected vector sizes in ReconstructShuffle");
5346
5347     if (MaxElts[i] - MinElts[i] >= NumElts) {
5348       // Span too large for a VEXT to cope
5349       return SDValue();
5350     }
5351
5352     if (MinElts[i] >= NumElts) {
5353       // The extraction can just take the second half
5354       VEXTOffsets[i] = NumElts;
5355       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5356                                    SourceVecs[i],
5357                                    DAG.getIntPtrConstant(NumElts, dl));
5358     } else if (MaxElts[i] < NumElts) {
5359       // The extraction can just take the first half
5360       VEXTOffsets[i] = 0;
5361       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5362                                    SourceVecs[i],
5363                                    DAG.getIntPtrConstant(0, dl));
5364     } else {
5365       // An actual VEXT is needed
5366       VEXTOffsets[i] = MinElts[i];
5367       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5368                                      SourceVecs[i],
5369                                      DAG.getIntPtrConstant(0, dl));
5370       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5371                                      SourceVecs[i],
5372                                      DAG.getIntPtrConstant(NumElts, dl));
5373       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5374                                    DAG.getConstant(VEXTOffsets[i], dl,
5375                                                    MVT::i32));
5376     }
5377   }
5378
5379   SmallVector<int, 8> Mask;
5380
5381   for (unsigned i = 0; i < NumElts; ++i) {
5382     SDValue Entry = Op.getOperand(i);
5383     if (Entry.getOpcode() == ISD::UNDEF) {
5384       Mask.push_back(-1);
5385       continue;
5386     }
5387
5388     SDValue ExtractVec = Entry.getOperand(0);
5389     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5390                                           .getOperand(1))->getSExtValue();
5391     if (ExtractVec == SourceVecs[0]) {
5392       Mask.push_back(ExtractElt - VEXTOffsets[0]);
5393     } else {
5394       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5395     }
5396   }
5397
5398   // Final check before we try to produce nonsense...
5399   if (isShuffleMaskLegal(Mask, VT))
5400     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5401                                 &Mask[0]);
5402
5403   return SDValue();
5404 }
5405
5406 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5407 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5408 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5409 /// are assumed to be legal.
5410 bool
5411 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5412                                       EVT VT) const {
5413   if (VT.getVectorNumElements() == 4 &&
5414       (VT.is128BitVector() || VT.is64BitVector())) {
5415     unsigned PFIndexes[4];
5416     for (unsigned i = 0; i != 4; ++i) {
5417       if (M[i] < 0)
5418         PFIndexes[i] = 8;
5419       else
5420         PFIndexes[i] = M[i];
5421     }
5422
5423     // Compute the index in the perfect shuffle table.
5424     unsigned PFTableIndex =
5425       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5426     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5427     unsigned Cost = (PFEntry >> 30);
5428
5429     if (Cost <= 4)
5430       return true;
5431   }
5432
5433   bool ReverseVEXT;
5434   unsigned Imm, WhichResult;
5435
5436   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5437   return (EltSize >= 32 ||
5438           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5439           isVREVMask(M, VT, 64) ||
5440           isVREVMask(M, VT, 32) ||
5441           isVREVMask(M, VT, 16) ||
5442           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5443           isVTBLMask(M, VT) ||
5444           isVTRNMask(M, VT, WhichResult) ||
5445           isVUZPMask(M, VT, WhichResult) ||
5446           isVZIPMask(M, VT, WhichResult) ||
5447           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5448           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5449           isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5450           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5451 }
5452
5453 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5454 /// the specified operations to build the shuffle.
5455 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5456                                       SDValue RHS, SelectionDAG &DAG,
5457                                       SDLoc dl) {
5458   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5459   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5460   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5461
5462   enum {
5463     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5464     OP_VREV,
5465     OP_VDUP0,
5466     OP_VDUP1,
5467     OP_VDUP2,
5468     OP_VDUP3,
5469     OP_VEXT1,
5470     OP_VEXT2,
5471     OP_VEXT3,
5472     OP_VUZPL, // VUZP, left result
5473     OP_VUZPR, // VUZP, right result
5474     OP_VZIPL, // VZIP, left result
5475     OP_VZIPR, // VZIP, right result
5476     OP_VTRNL, // VTRN, left result
5477     OP_VTRNR  // VTRN, right result
5478   };
5479
5480   if (OpNum == OP_COPY) {
5481     if (LHSID == (1*9+2)*9+3) return LHS;
5482     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5483     return RHS;
5484   }
5485
5486   SDValue OpLHS, OpRHS;
5487   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5488   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5489   EVT VT = OpLHS.getValueType();
5490
5491   switch (OpNum) {
5492   default: llvm_unreachable("Unknown shuffle opcode!");
5493   case OP_VREV:
5494     // VREV divides the vector in half and swaps within the half.
5495     if (VT.getVectorElementType() == MVT::i32 ||
5496         VT.getVectorElementType() == MVT::f32)
5497       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5498     // vrev <4 x i16> -> VREV32
5499     if (VT.getVectorElementType() == MVT::i16)
5500       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5501     // vrev <4 x i8> -> VREV16
5502     assert(VT.getVectorElementType() == MVT::i8);
5503     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5504   case OP_VDUP0:
5505   case OP_VDUP1:
5506   case OP_VDUP2:
5507   case OP_VDUP3:
5508     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5509                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
5510   case OP_VEXT1:
5511   case OP_VEXT2:
5512   case OP_VEXT3:
5513     return DAG.getNode(ARMISD::VEXT, dl, VT,
5514                        OpLHS, OpRHS,
5515                        DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
5516   case OP_VUZPL:
5517   case OP_VUZPR:
5518     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5519                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5520   case OP_VZIPL:
5521   case OP_VZIPR:
5522     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5523                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5524   case OP_VTRNL:
5525   case OP_VTRNR:
5526     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5527                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5528   }
5529 }
5530
5531 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5532                                        ArrayRef<int> ShuffleMask,
5533                                        SelectionDAG &DAG) {
5534   // Check to see if we can use the VTBL instruction.
5535   SDValue V1 = Op.getOperand(0);
5536   SDValue V2 = Op.getOperand(1);
5537   SDLoc DL(Op);
5538
5539   SmallVector<SDValue, 8> VTBLMask;
5540   for (ArrayRef<int>::iterator
5541          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5542     VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
5543
5544   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5545     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5546                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5547
5548   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5549                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5550 }
5551
5552 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5553                                                       SelectionDAG &DAG) {
5554   SDLoc DL(Op);
5555   SDValue OpLHS = Op.getOperand(0);
5556   EVT VT = OpLHS.getValueType();
5557
5558   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5559          "Expect an v8i16/v16i8 type");
5560   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5561   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5562   // extract the first 8 bytes into the top double word and the last 8 bytes
5563   // into the bottom double word. The v8i16 case is similar.
5564   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5565   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5566                      DAG.getConstant(ExtractNum, DL, MVT::i32));
5567 }
5568
5569 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5570   SDValue V1 = Op.getOperand(0);
5571   SDValue V2 = Op.getOperand(1);
5572   SDLoc dl(Op);
5573   EVT VT = Op.getValueType();
5574   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5575
5576   // Convert shuffles that are directly supported on NEON to target-specific
5577   // DAG nodes, instead of keeping them as shuffles and matching them again
5578   // during code selection.  This is more efficient and avoids the possibility
5579   // of inconsistencies between legalization and selection.
5580   // FIXME: floating-point vectors should be canonicalized to integer vectors
5581   // of the same time so that they get CSEd properly.
5582   ArrayRef<int> ShuffleMask = SVN->getMask();
5583
5584   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5585   if (EltSize <= 32) {
5586     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5587       int Lane = SVN->getSplatIndex();
5588       // If this is undef splat, generate it via "just" vdup, if possible.
5589       if (Lane == -1) Lane = 0;
5590
5591       // Test if V1 is a SCALAR_TO_VECTOR.
5592       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5593         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5594       }
5595       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5596       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5597       // reaches it).
5598       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5599           !isa<ConstantSDNode>(V1.getOperand(0))) {
5600         bool IsScalarToVector = true;
5601         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5602           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5603             IsScalarToVector = false;
5604             break;
5605           }
5606         if (IsScalarToVector)
5607           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5608       }
5609       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5610                          DAG.getConstant(Lane, dl, MVT::i32));
5611     }
5612
5613     bool ReverseVEXT;
5614     unsigned Imm;
5615     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5616       if (ReverseVEXT)
5617         std::swap(V1, V2);
5618       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5619                          DAG.getConstant(Imm, dl, MVT::i32));
5620     }
5621
5622     if (isVREVMask(ShuffleMask, VT, 64))
5623       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5624     if (isVREVMask(ShuffleMask, VT, 32))
5625       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5626     if (isVREVMask(ShuffleMask, VT, 16))
5627       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5628
5629     if (V2->getOpcode() == ISD::UNDEF &&
5630         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5631       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5632                          DAG.getConstant(Imm, dl, MVT::i32));
5633     }
5634
5635     // Check for Neon shuffles that modify both input vectors in place.
5636     // If both results are used, i.e., if there are two shuffles with the same
5637     // source operands and with masks corresponding to both results of one of
5638     // these operations, DAG memoization will ensure that a single node is
5639     // used for both shuffles.
5640     unsigned WhichResult;
5641     if (isVTRNMask(ShuffleMask, VT, WhichResult))
5642       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5643                          V1, V2).getValue(WhichResult);
5644     if (isVUZPMask(ShuffleMask, VT, WhichResult))
5645       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5646                          V1, V2).getValue(WhichResult);
5647     if (isVZIPMask(ShuffleMask, VT, WhichResult))
5648       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5649                          V1, V2).getValue(WhichResult);
5650
5651     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5652       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5653                          V1, V1).getValue(WhichResult);
5654     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5655       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5656                          V1, V1).getValue(WhichResult);
5657     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5658       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5659                          V1, V1).getValue(WhichResult);
5660   }
5661
5662   // If the shuffle is not directly supported and it has 4 elements, use
5663   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5664   unsigned NumElts = VT.getVectorNumElements();
5665   if (NumElts == 4) {
5666     unsigned PFIndexes[4];
5667     for (unsigned i = 0; i != 4; ++i) {
5668       if (ShuffleMask[i] < 0)
5669         PFIndexes[i] = 8;
5670       else
5671         PFIndexes[i] = ShuffleMask[i];
5672     }
5673
5674     // Compute the index in the perfect shuffle table.
5675     unsigned PFTableIndex =
5676       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5677     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5678     unsigned Cost = (PFEntry >> 30);
5679
5680     if (Cost <= 4)
5681       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5682   }
5683
5684   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5685   if (EltSize >= 32) {
5686     // Do the expansion with floating-point types, since that is what the VFP
5687     // registers are defined to use, and since i64 is not legal.
5688     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5689     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5690     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5691     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5692     SmallVector<SDValue, 8> Ops;
5693     for (unsigned i = 0; i < NumElts; ++i) {
5694       if (ShuffleMask[i] < 0)
5695         Ops.push_back(DAG.getUNDEF(EltVT));
5696       else
5697         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5698                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
5699                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5700                                                   dl, MVT::i32)));
5701     }
5702     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5703     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5704   }
5705
5706   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5707     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5708
5709   if (VT == MVT::v8i8) {
5710     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5711     if (NewOp.getNode())
5712       return NewOp;
5713   }
5714
5715   return SDValue();
5716 }
5717
5718 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5719   // INSERT_VECTOR_ELT is legal only for immediate indexes.
5720   SDValue Lane = Op.getOperand(2);
5721   if (!isa<ConstantSDNode>(Lane))
5722     return SDValue();
5723
5724   return Op;
5725 }
5726
5727 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5728   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5729   SDValue Lane = Op.getOperand(1);
5730   if (!isa<ConstantSDNode>(Lane))
5731     return SDValue();
5732
5733   SDValue Vec = Op.getOperand(0);
5734   if (Op.getValueType() == MVT::i32 &&
5735       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5736     SDLoc dl(Op);
5737     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5738   }
5739
5740   return Op;
5741 }
5742
5743 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5744   // The only time a CONCAT_VECTORS operation can have legal types is when
5745   // two 64-bit vectors are concatenated to a 128-bit vector.
5746   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5747          "unexpected CONCAT_VECTORS");
5748   SDLoc dl(Op);
5749   SDValue Val = DAG.getUNDEF(MVT::v2f64);
5750   SDValue Op0 = Op.getOperand(0);
5751   SDValue Op1 = Op.getOperand(1);
5752   if (Op0.getOpcode() != ISD::UNDEF)
5753     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5754                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5755                       DAG.getIntPtrConstant(0, dl));
5756   if (Op1.getOpcode() != ISD::UNDEF)
5757     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5758                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5759                       DAG.getIntPtrConstant(1, dl));
5760   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5761 }
5762
5763 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5764 /// element has been zero/sign-extended, depending on the isSigned parameter,
5765 /// from an integer type half its size.
5766 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5767                                    bool isSigned) {
5768   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5769   EVT VT = N->getValueType(0);
5770   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5771     SDNode *BVN = N->getOperand(0).getNode();
5772     if (BVN->getValueType(0) != MVT::v4i32 ||
5773         BVN->getOpcode() != ISD::BUILD_VECTOR)
5774       return false;
5775     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5776     unsigned HiElt = 1 - LoElt;
5777     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5778     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5779     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5780     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5781     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5782       return false;
5783     if (isSigned) {
5784       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5785           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5786         return true;
5787     } else {
5788       if (Hi0->isNullValue() && Hi1->isNullValue())
5789         return true;
5790     }
5791     return false;
5792   }
5793
5794   if (N->getOpcode() != ISD::BUILD_VECTOR)
5795     return false;
5796
5797   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5798     SDNode *Elt = N->getOperand(i).getNode();
5799     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5800       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5801       unsigned HalfSize = EltSize / 2;
5802       if (isSigned) {
5803         if (!isIntN(HalfSize, C->getSExtValue()))
5804           return false;
5805       } else {
5806         if (!isUIntN(HalfSize, C->getZExtValue()))
5807           return false;
5808       }
5809       continue;
5810     }
5811     return false;
5812   }
5813
5814   return true;
5815 }
5816
5817 /// isSignExtended - Check if a node is a vector value that is sign-extended
5818 /// or a constant BUILD_VECTOR with sign-extended elements.
5819 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5820   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5821     return true;
5822   if (isExtendedBUILD_VECTOR(N, DAG, true))
5823     return true;
5824   return false;
5825 }
5826
5827 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5828 /// or a constant BUILD_VECTOR with zero-extended elements.
5829 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5830   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5831     return true;
5832   if (isExtendedBUILD_VECTOR(N, DAG, false))
5833     return true;
5834   return false;
5835 }
5836
5837 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5838   if (OrigVT.getSizeInBits() >= 64)
5839     return OrigVT;
5840
5841   assert(OrigVT.isSimple() && "Expecting a simple value type");
5842
5843   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5844   switch (OrigSimpleTy) {
5845   default: llvm_unreachable("Unexpected Vector Type");
5846   case MVT::v2i8:
5847   case MVT::v2i16:
5848      return MVT::v2i32;
5849   case MVT::v4i8:
5850     return  MVT::v4i16;
5851   }
5852 }
5853
5854 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5855 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5856 /// We insert the required extension here to get the vector to fill a D register.
5857 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5858                                             const EVT &OrigTy,
5859                                             const EVT &ExtTy,
5860                                             unsigned ExtOpcode) {
5861   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5862   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5863   // 64-bits we need to insert a new extension so that it will be 64-bits.
5864   assert(ExtTy.is128BitVector() && "Unexpected extension size");
5865   if (OrigTy.getSizeInBits() >= 64)
5866     return N;
5867
5868   // Must extend size to at least 64 bits to be used as an operand for VMULL.
5869   EVT NewVT = getExtensionTo64Bits(OrigTy);
5870
5871   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5872 }
5873
5874 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5875 /// does not do any sign/zero extension. If the original vector is less
5876 /// than 64 bits, an appropriate extension will be added after the load to
5877 /// reach a total size of 64 bits. We have to add the extension separately
5878 /// because ARM does not have a sign/zero extending load for vectors.
5879 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5880   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5881
5882   // The load already has the right type.
5883   if (ExtendedTy == LD->getMemoryVT())
5884     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5885                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5886                 LD->isNonTemporal(), LD->isInvariant(),
5887                 LD->getAlignment());
5888
5889   // We need to create a zextload/sextload. We cannot just create a load
5890   // followed by a zext/zext node because LowerMUL is also run during normal
5891   // operation legalization where we can't create illegal types.
5892   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5893                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5894                         LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
5895                         LD->isNonTemporal(), LD->getAlignment());
5896 }
5897
5898 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5899 /// extending load, or BUILD_VECTOR with extended elements, return the
5900 /// unextended value. The unextended vector should be 64 bits so that it can
5901 /// be used as an operand to a VMULL instruction. If the original vector size
5902 /// before extension is less than 64 bits we add a an extension to resize
5903 /// the vector to 64 bits.
5904 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5905   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5906     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5907                                         N->getOperand(0)->getValueType(0),
5908                                         N->getValueType(0),
5909                                         N->getOpcode());
5910
5911   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5912     return SkipLoadExtensionForVMULL(LD, DAG);
5913
5914   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
5915   // have been legalized as a BITCAST from v4i32.
5916   if (N->getOpcode() == ISD::BITCAST) {
5917     SDNode *BVN = N->getOperand(0).getNode();
5918     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5919            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5920     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5921     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5922                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5923   }
5924   // Construct a new BUILD_VECTOR with elements truncated to half the size.
5925   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5926   EVT VT = N->getValueType(0);
5927   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5928   unsigned NumElts = VT.getVectorNumElements();
5929   MVT TruncVT = MVT::getIntegerVT(EltSize);
5930   SmallVector<SDValue, 8> Ops;
5931   SDLoc dl(N);
5932   for (unsigned i = 0; i != NumElts; ++i) {
5933     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5934     const APInt &CInt = C->getAPIntValue();
5935     // Element types smaller than 32 bits are not legal, so use i32 elements.
5936     // The values are implicitly truncated so sext vs. zext doesn't matter.
5937     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
5938   }
5939   return DAG.getNode(ISD::BUILD_VECTOR, dl,
5940                      MVT::getVectorVT(TruncVT, NumElts), Ops);
5941 }
5942
5943 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5944   unsigned Opcode = N->getOpcode();
5945   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5946     SDNode *N0 = N->getOperand(0).getNode();
5947     SDNode *N1 = N->getOperand(1).getNode();
5948     return N0->hasOneUse() && N1->hasOneUse() &&
5949       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5950   }
5951   return false;
5952 }
5953
5954 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5955   unsigned Opcode = N->getOpcode();
5956   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5957     SDNode *N0 = N->getOperand(0).getNode();
5958     SDNode *N1 = N->getOperand(1).getNode();
5959     return N0->hasOneUse() && N1->hasOneUse() &&
5960       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5961   }
5962   return false;
5963 }
5964
5965 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5966   // Multiplications are only custom-lowered for 128-bit vectors so that
5967   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
5968   EVT VT = Op.getValueType();
5969   assert(VT.is128BitVector() && VT.isInteger() &&
5970          "unexpected type for custom-lowering ISD::MUL");
5971   SDNode *N0 = Op.getOperand(0).getNode();
5972   SDNode *N1 = Op.getOperand(1).getNode();
5973   unsigned NewOpc = 0;
5974   bool isMLA = false;
5975   bool isN0SExt = isSignExtended(N0, DAG);
5976   bool isN1SExt = isSignExtended(N1, DAG);
5977   if (isN0SExt && isN1SExt)
5978     NewOpc = ARMISD::VMULLs;
5979   else {
5980     bool isN0ZExt = isZeroExtended(N0, DAG);
5981     bool isN1ZExt = isZeroExtended(N1, DAG);
5982     if (isN0ZExt && isN1ZExt)
5983       NewOpc = ARMISD::VMULLu;
5984     else if (isN1SExt || isN1ZExt) {
5985       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5986       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5987       if (isN1SExt && isAddSubSExt(N0, DAG)) {
5988         NewOpc = ARMISD::VMULLs;
5989         isMLA = true;
5990       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5991         NewOpc = ARMISD::VMULLu;
5992         isMLA = true;
5993       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5994         std::swap(N0, N1);
5995         NewOpc = ARMISD::VMULLu;
5996         isMLA = true;
5997       }
5998     }
5999
6000     if (!NewOpc) {
6001       if (VT == MVT::v2i64)
6002         // Fall through to expand this.  It is not legal.
6003         return SDValue();
6004       else
6005         // Other vector multiplications are legal.
6006         return Op;
6007     }
6008   }
6009
6010   // Legalize to a VMULL instruction.
6011   SDLoc DL(Op);
6012   SDValue Op0;
6013   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
6014   if (!isMLA) {
6015     Op0 = SkipExtensionForVMULL(N0, DAG);
6016     assert(Op0.getValueType().is64BitVector() &&
6017            Op1.getValueType().is64BitVector() &&
6018            "unexpected types for extended operands to VMULL");
6019     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
6020   }
6021
6022   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
6023   // isel lowering to take advantage of no-stall back to back vmul + vmla.
6024   //   vmull q0, d4, d6
6025   //   vmlal q0, d5, d6
6026   // is faster than
6027   //   vaddl q0, d4, d5
6028   //   vmovl q1, d6
6029   //   vmul  q0, q0, q1
6030   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
6031   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
6032   EVT Op1VT = Op1.getValueType();
6033   return DAG.getNode(N0->getOpcode(), DL, VT,
6034                      DAG.getNode(NewOpc, DL, VT,
6035                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
6036                      DAG.getNode(NewOpc, DL, VT,
6037                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
6038 }
6039
6040 static SDValue
6041 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
6042   // Convert to float
6043   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
6044   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
6045   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
6046   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
6047   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
6048   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
6049   // Get reciprocal estimate.
6050   // float4 recip = vrecpeq_f32(yf);
6051   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6052                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6053                    Y);
6054   // Because char has a smaller range than uchar, we can actually get away
6055   // without any newton steps.  This requires that we use a weird bias
6056   // of 0xb000, however (again, this has been exhaustively tested).
6057   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
6058   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
6059   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
6060   Y = DAG.getConstant(0xb000, dl, MVT::i32);
6061   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
6062   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6063   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6064   // Convert back to short.
6065   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6066   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6067   return X;
6068 }
6069
6070 static SDValue
6071 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
6072   SDValue N2;
6073   // Convert to float.
6074   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6075   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6076   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6077   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6078   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6079   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6080
6081   // Use reciprocal estimate and one refinement step.
6082   // float4 recip = vrecpeq_f32(yf);
6083   // recip *= vrecpsq_f32(yf, recip);
6084   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6085                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6086                    N1);
6087   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6088                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6089                    N1, N2);
6090   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6091   // Because short has a smaller range than ushort, we can actually get away
6092   // with only a single newton step.  This requires that we use a weird bias
6093   // of 89, however (again, this has been exhaustively tested).
6094   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6095   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6096   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6097   N1 = DAG.getConstant(0x89, dl, MVT::i32);
6098   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6099   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6100   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6101   // Convert back to integer and return.
6102   // return vmovn_s32(vcvt_s32_f32(result));
6103   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6104   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6105   return N0;
6106 }
6107
6108 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6109   EVT VT = Op.getValueType();
6110   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6111          "unexpected type for custom-lowering ISD::SDIV");
6112
6113   SDLoc dl(Op);
6114   SDValue N0 = Op.getOperand(0);
6115   SDValue N1 = Op.getOperand(1);
6116   SDValue N2, N3;
6117
6118   if (VT == MVT::v8i8) {
6119     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6120     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6121
6122     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6123                      DAG.getIntPtrConstant(4, dl));
6124     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6125                      DAG.getIntPtrConstant(4, dl));
6126     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6127                      DAG.getIntPtrConstant(0, dl));
6128     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6129                      DAG.getIntPtrConstant(0, dl));
6130
6131     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6132     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6133
6134     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6135     N0 = LowerCONCAT_VECTORS(N0, DAG);
6136
6137     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6138     return N0;
6139   }
6140   return LowerSDIV_v4i16(N0, N1, dl, DAG);
6141 }
6142
6143 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6144   EVT VT = Op.getValueType();
6145   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6146          "unexpected type for custom-lowering ISD::UDIV");
6147
6148   SDLoc dl(Op);
6149   SDValue N0 = Op.getOperand(0);
6150   SDValue N1 = Op.getOperand(1);
6151   SDValue N2, N3;
6152
6153   if (VT == MVT::v8i8) {
6154     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6155     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6156
6157     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6158                      DAG.getIntPtrConstant(4, dl));
6159     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6160                      DAG.getIntPtrConstant(4, dl));
6161     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6162                      DAG.getIntPtrConstant(0, dl));
6163     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6164                      DAG.getIntPtrConstant(0, dl));
6165
6166     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6167     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6168
6169     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6170     N0 = LowerCONCAT_VECTORS(N0, DAG);
6171
6172     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6173                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
6174                                      MVT::i32),
6175                      N0);
6176     return N0;
6177   }
6178
6179   // v4i16 sdiv ... Convert to float.
6180   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6181   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6182   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6183   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6184   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6185   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6186
6187   // Use reciprocal estimate and two refinement steps.
6188   // float4 recip = vrecpeq_f32(yf);
6189   // recip *= vrecpsq_f32(yf, recip);
6190   // recip *= vrecpsq_f32(yf, recip);
6191   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6192                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6193                    BN1);
6194   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6195                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6196                    BN1, N2);
6197   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6198   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6199                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6200                    BN1, N2);
6201   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6202   // Simply multiplying by the reciprocal estimate can leave us a few ulps
6203   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6204   // and that it will never cause us to return an answer too large).
6205   // float4 result = as_float4(as_int4(xf*recip) + 2);
6206   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6207   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6208   N1 = DAG.getConstant(2, dl, MVT::i32);
6209   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6210   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6211   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6212   // Convert back to integer and return.
6213   // return vmovn_u32(vcvt_s32_f32(result));
6214   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6215   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6216   return N0;
6217 }
6218
6219 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6220   EVT VT = Op.getNode()->getValueType(0);
6221   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6222
6223   unsigned Opc;
6224   bool ExtraOp = false;
6225   switch (Op.getOpcode()) {
6226   default: llvm_unreachable("Invalid code");
6227   case ISD::ADDC: Opc = ARMISD::ADDC; break;
6228   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6229   case ISD::SUBC: Opc = ARMISD::SUBC; break;
6230   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6231   }
6232
6233   if (!ExtraOp)
6234     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6235                        Op.getOperand(1));
6236   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6237                      Op.getOperand(1), Op.getOperand(2));
6238 }
6239
6240 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6241   assert(Subtarget->isTargetDarwin());
6242
6243   // For iOS, we want to call an alternative entry point: __sincos_stret,
6244   // return values are passed via sret.
6245   SDLoc dl(Op);
6246   SDValue Arg = Op.getOperand(0);
6247   EVT ArgVT = Arg.getValueType();
6248   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6249
6250   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6251   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6252
6253   // Pair of floats / doubles used to pass the result.
6254   StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
6255
6256   // Create stack object for sret.
6257   const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
6258   const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
6259   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6260   SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
6261
6262   ArgListTy Args;
6263   ArgListEntry Entry;
6264
6265   Entry.Node = SRet;
6266   Entry.Ty = RetTy->getPointerTo();
6267   Entry.isSExt = false;
6268   Entry.isZExt = false;
6269   Entry.isSRet = true;
6270   Args.push_back(Entry);
6271
6272   Entry.Node = Arg;
6273   Entry.Ty = ArgTy;
6274   Entry.isSExt = false;
6275   Entry.isZExt = false;
6276   Args.push_back(Entry);
6277
6278   const char *LibcallName  = (ArgVT == MVT::f64)
6279   ? "__sincos_stret" : "__sincosf_stret";
6280   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
6281
6282   TargetLowering::CallLoweringInfo CLI(DAG);
6283   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6284     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6285                std::move(Args), 0)
6286     .setDiscardResult();
6287
6288   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6289
6290   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6291                                 MachinePointerInfo(), false, false, false, 0);
6292
6293   // Address of cos field.
6294   SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
6295                             DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
6296   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6297                                 MachinePointerInfo(), false, false, false, 0);
6298
6299   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6300   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6301                      LoadSin.getValue(0), LoadCos.getValue(0));
6302 }
6303
6304 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6305   // Monotonic load/store is legal for all targets
6306   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6307     return Op;
6308
6309   // Acquire/Release load/store is not legal for targets without a
6310   // dmb or equivalent available.
6311   return SDValue();
6312 }
6313
6314 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6315                                     SmallVectorImpl<SDValue> &Results,
6316                                     SelectionDAG &DAG,
6317                                     const ARMSubtarget *Subtarget) {
6318   SDLoc DL(N);
6319   SDValue Cycles32, OutChain;
6320
6321   if (Subtarget->hasPerfMon()) {
6322     // Under Power Management extensions, the cycle-count is:
6323     //    mrc p15, #0, <Rt>, c9, c13, #0
6324     SDValue Ops[] = { N->getOperand(0), // Chain
6325                       DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
6326                       DAG.getConstant(15, DL, MVT::i32),
6327                       DAG.getConstant(0, DL, MVT::i32),
6328                       DAG.getConstant(9, DL, MVT::i32),
6329                       DAG.getConstant(13, DL, MVT::i32),
6330                       DAG.getConstant(0, DL, MVT::i32)
6331     };
6332
6333     Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6334                            DAG.getVTList(MVT::i32, MVT::Other), Ops);
6335     OutChain = Cycles32.getValue(1);
6336   } else {
6337     // Intrinsic is defined to return 0 on unsupported platforms. Technically
6338     // there are older ARM CPUs that have implementation-specific ways of
6339     // obtaining this information (FIXME!).
6340     Cycles32 = DAG.getConstant(0, DL, MVT::i32);
6341     OutChain = DAG.getEntryNode();
6342   }
6343
6344
6345   SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6346                                  Cycles32, DAG.getConstant(0, DL, MVT::i32));
6347   Results.push_back(Cycles64);
6348   Results.push_back(OutChain);
6349 }
6350
6351 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6352   switch (Op.getOpcode()) {
6353   default: llvm_unreachable("Don't know how to custom lower this!");
6354   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6355   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6356   case ISD::GlobalAddress:
6357     switch (Subtarget->getTargetTriple().getObjectFormat()) {
6358     default: llvm_unreachable("unknown object format");
6359     case Triple::COFF:
6360       return LowerGlobalAddressWindows(Op, DAG);
6361     case Triple::ELF:
6362       return LowerGlobalAddressELF(Op, DAG);
6363     case Triple::MachO:
6364       return LowerGlobalAddressDarwin(Op, DAG);
6365     }
6366   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6367   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6368   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6369   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6370   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6371   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6372   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6373   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6374   case ISD::SINT_TO_FP:
6375   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6376   case ISD::FP_TO_SINT:
6377   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6378   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6379   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6380   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6381   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6382   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6383   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6384   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6385                                                                Subtarget);
6386   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6387   case ISD::SHL:
6388   case ISD::SRL:
6389   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6390   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6391   case ISD::SRL_PARTS:
6392   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6393   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6394   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6395   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6396   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6397   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6398   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6399   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6400   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6401   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6402   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6403   case ISD::MUL:           return LowerMUL(Op, DAG);
6404   case ISD::SDIV:          return LowerSDIV(Op, DAG);
6405   case ISD::UDIV:          return LowerUDIV(Op, DAG);
6406   case ISD::ADDC:
6407   case ISD::ADDE:
6408   case ISD::SUBC:
6409   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6410   case ISD::SADDO:
6411   case ISD::UADDO:
6412   case ISD::SSUBO:
6413   case ISD::USUBO:
6414     return LowerXALUO(Op, DAG);
6415   case ISD::ATOMIC_LOAD:
6416   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6417   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6418   case ISD::SDIVREM:
6419   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6420   case ISD::DYNAMIC_STACKALLOC:
6421     if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6422       return LowerDYNAMIC_STACKALLOC(Op, DAG);
6423     llvm_unreachable("Don't know how to custom lower this!");
6424   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6425   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6426   }
6427 }
6428
6429 /// ReplaceNodeResults - Replace the results of node with an illegal result
6430 /// type with new values built out of custom code.
6431 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6432                                            SmallVectorImpl<SDValue>&Results,
6433                                            SelectionDAG &DAG) const {
6434   SDValue Res;
6435   switch (N->getOpcode()) {
6436   default:
6437     llvm_unreachable("Don't know how to custom expand this!");
6438   case ISD::BITCAST:
6439     Res = ExpandBITCAST(N, DAG);
6440     break;
6441   case ISD::SRL:
6442   case ISD::SRA:
6443     Res = Expand64BitShift(N, DAG, Subtarget);
6444     break;
6445   case ISD::READCYCLECOUNTER:
6446     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6447     return;
6448   }
6449   if (Res.getNode())
6450     Results.push_back(Res);
6451 }
6452
6453 //===----------------------------------------------------------------------===//
6454 //                           ARM Scheduler Hooks
6455 //===----------------------------------------------------------------------===//
6456
6457 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6458 /// registers the function context.
6459 void ARMTargetLowering::
6460 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6461                        MachineBasicBlock *DispatchBB, int FI) const {
6462   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6463   DebugLoc dl = MI->getDebugLoc();
6464   MachineFunction *MF = MBB->getParent();
6465   MachineRegisterInfo *MRI = &MF->getRegInfo();
6466   MachineConstantPool *MCP = MF->getConstantPool();
6467   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6468   const Function *F = MF->getFunction();
6469
6470   bool isThumb = Subtarget->isThumb();
6471   bool isThumb2 = Subtarget->isThumb2();
6472
6473   unsigned PCLabelId = AFI->createPICLabelUId();
6474   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6475   ARMConstantPoolValue *CPV =
6476     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6477   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6478
6479   const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
6480                                            : &ARM::GPRRegClass;
6481
6482   // Grab constant pool and fixed stack memory operands.
6483   MachineMemOperand *CPMMO =
6484     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6485                              MachineMemOperand::MOLoad, 4, 4);
6486
6487   MachineMemOperand *FIMMOSt =
6488     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6489                              MachineMemOperand::MOStore, 4, 4);
6490
6491   // Load the address of the dispatch MBB into the jump buffer.
6492   if (isThumb2) {
6493     // Incoming value: jbuf
6494     //   ldr.n  r5, LCPI1_1
6495     //   orr    r5, r5, #1
6496     //   add    r5, pc
6497     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6498     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6499     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6500                    .addConstantPoolIndex(CPI)
6501                    .addMemOperand(CPMMO));
6502     // Set the low bit because of thumb mode.
6503     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6504     AddDefaultCC(
6505       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6506                      .addReg(NewVReg1, RegState::Kill)
6507                      .addImm(0x01)));
6508     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6509     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6510       .addReg(NewVReg2, RegState::Kill)
6511       .addImm(PCLabelId);
6512     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6513                    .addReg(NewVReg3, RegState::Kill)
6514                    .addFrameIndex(FI)
6515                    .addImm(36)  // &jbuf[1] :: pc
6516                    .addMemOperand(FIMMOSt));
6517   } else if (isThumb) {
6518     // Incoming value: jbuf
6519     //   ldr.n  r1, LCPI1_4
6520     //   add    r1, pc
6521     //   mov    r2, #1
6522     //   orrs   r1, r2
6523     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6524     //   str    r1, [r2]
6525     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6526     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6527                    .addConstantPoolIndex(CPI)
6528                    .addMemOperand(CPMMO));
6529     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6530     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6531       .addReg(NewVReg1, RegState::Kill)
6532       .addImm(PCLabelId);
6533     // Set the low bit because of thumb mode.
6534     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6535     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6536                    .addReg(ARM::CPSR, RegState::Define)
6537                    .addImm(1));
6538     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6539     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6540                    .addReg(ARM::CPSR, RegState::Define)
6541                    .addReg(NewVReg2, RegState::Kill)
6542                    .addReg(NewVReg3, RegState::Kill));
6543     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6544     BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
6545             .addFrameIndex(FI)
6546             .addImm(36); // &jbuf[1] :: pc
6547     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6548                    .addReg(NewVReg4, RegState::Kill)
6549                    .addReg(NewVReg5, RegState::Kill)
6550                    .addImm(0)
6551                    .addMemOperand(FIMMOSt));
6552   } else {
6553     // Incoming value: jbuf
6554     //   ldr  r1, LCPI1_1
6555     //   add  r1, pc, r1
6556     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6557     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6558     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6559                    .addConstantPoolIndex(CPI)
6560                    .addImm(0)
6561                    .addMemOperand(CPMMO));
6562     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6563     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6564                    .addReg(NewVReg1, RegState::Kill)
6565                    .addImm(PCLabelId));
6566     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6567                    .addReg(NewVReg2, RegState::Kill)
6568                    .addFrameIndex(FI)
6569                    .addImm(36)  // &jbuf[1] :: pc
6570                    .addMemOperand(FIMMOSt));
6571   }
6572 }
6573
6574 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr *MI,
6575                                               MachineBasicBlock *MBB) const {
6576   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6577   DebugLoc dl = MI->getDebugLoc();
6578   MachineFunction *MF = MBB->getParent();
6579   MachineRegisterInfo *MRI = &MF->getRegInfo();
6580   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6581   MachineFrameInfo *MFI = MF->getFrameInfo();
6582   int FI = MFI->getFunctionContextIndex();
6583
6584   const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
6585                                                         : &ARM::GPRnopcRegClass;
6586
6587   // Get a mapping of the call site numbers to all of the landing pads they're
6588   // associated with.
6589   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6590   unsigned MaxCSNum = 0;
6591   MachineModuleInfo &MMI = MF->getMMI();
6592   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6593        ++BB) {
6594     if (!BB->isLandingPad()) continue;
6595
6596     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6597     // pad.
6598     for (MachineBasicBlock::iterator
6599            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6600       if (!II->isEHLabel()) continue;
6601
6602       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6603       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6604
6605       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6606       for (SmallVectorImpl<unsigned>::iterator
6607              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6608            CSI != CSE; ++CSI) {
6609         CallSiteNumToLPad[*CSI].push_back(BB);
6610         MaxCSNum = std::max(MaxCSNum, *CSI);
6611       }
6612       break;
6613     }
6614   }
6615
6616   // Get an ordered list of the machine basic blocks for the jump table.
6617   std::vector<MachineBasicBlock*> LPadList;
6618   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6619   LPadList.reserve(CallSiteNumToLPad.size());
6620   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6621     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6622     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6623            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6624       LPadList.push_back(*II);
6625       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6626     }
6627   }
6628
6629   assert(!LPadList.empty() &&
6630          "No landing pad destinations for the dispatch jump table!");
6631
6632   // Create the jump table and associated information.
6633   MachineJumpTableInfo *JTI =
6634     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6635   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6636   unsigned UId = AFI->createJumpTableUId();
6637   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6638
6639   // Create the MBBs for the dispatch code.
6640
6641   // Shove the dispatch's address into the return slot in the function context.
6642   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6643   DispatchBB->setIsLandingPad();
6644
6645   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6646   unsigned trap_opcode;
6647   if (Subtarget->isThumb())
6648     trap_opcode = ARM::tTRAP;
6649   else
6650     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6651
6652   BuildMI(TrapBB, dl, TII->get(trap_opcode));
6653   DispatchBB->addSuccessor(TrapBB);
6654
6655   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6656   DispatchBB->addSuccessor(DispContBB);
6657
6658   // Insert and MBBs.
6659   MF->insert(MF->end(), DispatchBB);
6660   MF->insert(MF->end(), DispContBB);
6661   MF->insert(MF->end(), TrapBB);
6662
6663   // Insert code into the entry block that creates and registers the function
6664   // context.
6665   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6666
6667   MachineMemOperand *FIMMOLd =
6668     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6669                              MachineMemOperand::MOLoad |
6670                              MachineMemOperand::MOVolatile, 4, 4);
6671
6672   MachineInstrBuilder MIB;
6673   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6674
6675   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6676   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6677
6678   // Add a register mask with no preserved registers.  This results in all
6679   // registers being marked as clobbered.
6680   MIB.addRegMask(RI.getNoPreservedMask());
6681
6682   unsigned NumLPads = LPadList.size();
6683   if (Subtarget->isThumb2()) {
6684     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6685     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6686                    .addFrameIndex(FI)
6687                    .addImm(4)
6688                    .addMemOperand(FIMMOLd));
6689
6690     if (NumLPads < 256) {
6691       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6692                      .addReg(NewVReg1)
6693                      .addImm(LPadList.size()));
6694     } else {
6695       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6696       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6697                      .addImm(NumLPads & 0xFFFF));
6698
6699       unsigned VReg2 = VReg1;
6700       if ((NumLPads & 0xFFFF0000) != 0) {
6701         VReg2 = MRI->createVirtualRegister(TRC);
6702         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6703                        .addReg(VReg1)
6704                        .addImm(NumLPads >> 16));
6705       }
6706
6707       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6708                      .addReg(NewVReg1)
6709                      .addReg(VReg2));
6710     }
6711
6712     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6713       .addMBB(TrapBB)
6714       .addImm(ARMCC::HI)
6715       .addReg(ARM::CPSR);
6716
6717     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6718     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6719                    .addJumpTableIndex(MJTI)
6720                    .addImm(UId));
6721
6722     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6723     AddDefaultCC(
6724       AddDefaultPred(
6725         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6726         .addReg(NewVReg3, RegState::Kill)
6727         .addReg(NewVReg1)
6728         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6729
6730     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6731       .addReg(NewVReg4, RegState::Kill)
6732       .addReg(NewVReg1)
6733       .addJumpTableIndex(MJTI)
6734       .addImm(UId);
6735   } else if (Subtarget->isThumb()) {
6736     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6737     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6738                    .addFrameIndex(FI)
6739                    .addImm(1)
6740                    .addMemOperand(FIMMOLd));
6741
6742     if (NumLPads < 256) {
6743       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6744                      .addReg(NewVReg1)
6745                      .addImm(NumLPads));
6746     } else {
6747       MachineConstantPool *ConstantPool = MF->getConstantPool();
6748       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6749       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6750
6751       // MachineConstantPool wants an explicit alignment.
6752       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6753       if (Align == 0)
6754         Align = getDataLayout()->getTypeAllocSize(C->getType());
6755       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6756
6757       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6758       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6759                      .addReg(VReg1, RegState::Define)
6760                      .addConstantPoolIndex(Idx));
6761       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6762                      .addReg(NewVReg1)
6763                      .addReg(VReg1));
6764     }
6765
6766     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6767       .addMBB(TrapBB)
6768       .addImm(ARMCC::HI)
6769       .addReg(ARM::CPSR);
6770
6771     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6772     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6773                    .addReg(ARM::CPSR, RegState::Define)
6774                    .addReg(NewVReg1)
6775                    .addImm(2));
6776
6777     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6778     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6779                    .addJumpTableIndex(MJTI)
6780                    .addImm(UId));
6781
6782     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6783     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6784                    .addReg(ARM::CPSR, RegState::Define)
6785                    .addReg(NewVReg2, RegState::Kill)
6786                    .addReg(NewVReg3));
6787
6788     MachineMemOperand *JTMMOLd =
6789       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6790                                MachineMemOperand::MOLoad, 4, 4);
6791
6792     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6793     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6794                    .addReg(NewVReg4, RegState::Kill)
6795                    .addImm(0)
6796                    .addMemOperand(JTMMOLd));
6797
6798     unsigned NewVReg6 = NewVReg5;
6799     if (RelocM == Reloc::PIC_) {
6800       NewVReg6 = MRI->createVirtualRegister(TRC);
6801       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6802                      .addReg(ARM::CPSR, RegState::Define)
6803                      .addReg(NewVReg5, RegState::Kill)
6804                      .addReg(NewVReg3));
6805     }
6806
6807     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6808       .addReg(NewVReg6, RegState::Kill)
6809       .addJumpTableIndex(MJTI)
6810       .addImm(UId);
6811   } else {
6812     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6813     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6814                    .addFrameIndex(FI)
6815                    .addImm(4)
6816                    .addMemOperand(FIMMOLd));
6817
6818     if (NumLPads < 256) {
6819       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6820                      .addReg(NewVReg1)
6821                      .addImm(NumLPads));
6822     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6823       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6824       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6825                      .addImm(NumLPads & 0xFFFF));
6826
6827       unsigned VReg2 = VReg1;
6828       if ((NumLPads & 0xFFFF0000) != 0) {
6829         VReg2 = MRI->createVirtualRegister(TRC);
6830         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6831                        .addReg(VReg1)
6832                        .addImm(NumLPads >> 16));
6833       }
6834
6835       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6836                      .addReg(NewVReg1)
6837                      .addReg(VReg2));
6838     } else {
6839       MachineConstantPool *ConstantPool = MF->getConstantPool();
6840       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6841       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6842
6843       // MachineConstantPool wants an explicit alignment.
6844       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6845       if (Align == 0)
6846         Align = getDataLayout()->getTypeAllocSize(C->getType());
6847       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6848
6849       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6850       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6851                      .addReg(VReg1, RegState::Define)
6852                      .addConstantPoolIndex(Idx)
6853                      .addImm(0));
6854       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6855                      .addReg(NewVReg1)
6856                      .addReg(VReg1, RegState::Kill));
6857     }
6858
6859     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6860       .addMBB(TrapBB)
6861       .addImm(ARMCC::HI)
6862       .addReg(ARM::CPSR);
6863
6864     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6865     AddDefaultCC(
6866       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6867                      .addReg(NewVReg1)
6868                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6869     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6870     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6871                    .addJumpTableIndex(MJTI)
6872                    .addImm(UId));
6873
6874     MachineMemOperand *JTMMOLd =
6875       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6876                                MachineMemOperand::MOLoad, 4, 4);
6877     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6878     AddDefaultPred(
6879       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6880       .addReg(NewVReg3, RegState::Kill)
6881       .addReg(NewVReg4)
6882       .addImm(0)
6883       .addMemOperand(JTMMOLd));
6884
6885     if (RelocM == Reloc::PIC_) {
6886       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6887         .addReg(NewVReg5, RegState::Kill)
6888         .addReg(NewVReg4)
6889         .addJumpTableIndex(MJTI)
6890         .addImm(UId);
6891     } else {
6892       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6893         .addReg(NewVReg5, RegState::Kill)
6894         .addJumpTableIndex(MJTI)
6895         .addImm(UId);
6896     }
6897   }
6898
6899   // Add the jump table entries as successors to the MBB.
6900   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6901   for (std::vector<MachineBasicBlock*>::iterator
6902          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6903     MachineBasicBlock *CurMBB = *I;
6904     if (SeenMBBs.insert(CurMBB).second)
6905       DispContBB->addSuccessor(CurMBB);
6906   }
6907
6908   // N.B. the order the invoke BBs are processed in doesn't matter here.
6909   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
6910   SmallVector<MachineBasicBlock*, 64> MBBLPads;
6911   for (MachineBasicBlock *BB : InvokeBBs) {
6912
6913     // Remove the landing pad successor from the invoke block and replace it
6914     // with the new dispatch block.
6915     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6916                                                   BB->succ_end());
6917     while (!Successors.empty()) {
6918       MachineBasicBlock *SMBB = Successors.pop_back_val();
6919       if (SMBB->isLandingPad()) {
6920         BB->removeSuccessor(SMBB);
6921         MBBLPads.push_back(SMBB);
6922       }
6923     }
6924
6925     BB->addSuccessor(DispatchBB);
6926
6927     // Find the invoke call and mark all of the callee-saved registers as
6928     // 'implicit defined' so that they're spilled. This prevents code from
6929     // moving instructions to before the EH block, where they will never be
6930     // executed.
6931     for (MachineBasicBlock::reverse_iterator
6932            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6933       if (!II->isCall()) continue;
6934
6935       DenseMap<unsigned, bool> DefRegs;
6936       for (MachineInstr::mop_iterator
6937              OI = II->operands_begin(), OE = II->operands_end();
6938            OI != OE; ++OI) {
6939         if (!OI->isReg()) continue;
6940         DefRegs[OI->getReg()] = true;
6941       }
6942
6943       MachineInstrBuilder MIB(*MF, &*II);
6944
6945       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6946         unsigned Reg = SavedRegs[i];
6947         if (Subtarget->isThumb2() &&
6948             !ARM::tGPRRegClass.contains(Reg) &&
6949             !ARM::hGPRRegClass.contains(Reg))
6950           continue;
6951         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6952           continue;
6953         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6954           continue;
6955         if (!DefRegs[Reg])
6956           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6957       }
6958
6959       break;
6960     }
6961   }
6962
6963   // Mark all former landing pads as non-landing pads. The dispatch is the only
6964   // landing pad now.
6965   for (SmallVectorImpl<MachineBasicBlock*>::iterator
6966          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6967     (*I)->setIsLandingPad(false);
6968
6969   // The instruction is gone now.
6970   MI->eraseFromParent();
6971 }
6972
6973 static
6974 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6975   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6976        E = MBB->succ_end(); I != E; ++I)
6977     if (*I != Succ)
6978       return *I;
6979   llvm_unreachable("Expecting a BB with two successors!");
6980 }
6981
6982 /// Return the load opcode for a given load size. If load size >= 8,
6983 /// neon opcode will be returned.
6984 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
6985   if (LdSize >= 8)
6986     return LdSize == 16 ? ARM::VLD1q32wb_fixed
6987                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
6988   if (IsThumb1)
6989     return LdSize == 4 ? ARM::tLDRi
6990                        : LdSize == 2 ? ARM::tLDRHi
6991                                      : LdSize == 1 ? ARM::tLDRBi : 0;
6992   if (IsThumb2)
6993     return LdSize == 4 ? ARM::t2LDR_POST
6994                        : LdSize == 2 ? ARM::t2LDRH_POST
6995                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
6996   return LdSize == 4 ? ARM::LDR_POST_IMM
6997                      : LdSize == 2 ? ARM::LDRH_POST
6998                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
6999 }
7000
7001 /// Return the store opcode for a given store size. If store size >= 8,
7002 /// neon opcode will be returned.
7003 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7004   if (StSize >= 8)
7005     return StSize == 16 ? ARM::VST1q32wb_fixed
7006                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7007   if (IsThumb1)
7008     return StSize == 4 ? ARM::tSTRi
7009                        : StSize == 2 ? ARM::tSTRHi
7010                                      : StSize == 1 ? ARM::tSTRBi : 0;
7011   if (IsThumb2)
7012     return StSize == 4 ? ARM::t2STR_POST
7013                        : StSize == 2 ? ARM::t2STRH_POST
7014                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
7015   return StSize == 4 ? ARM::STR_POST_IMM
7016                      : StSize == 2 ? ARM::STRH_POST
7017                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7018 }
7019
7020 /// Emit a post-increment load operation with given size. The instructions
7021 /// will be added to BB at Pos.
7022 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7023                        const TargetInstrInfo *TII, DebugLoc dl,
7024                        unsigned LdSize, unsigned Data, unsigned AddrIn,
7025                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7026   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7027   assert(LdOpc != 0 && "Should have a load opcode");
7028   if (LdSize >= 8) {
7029     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7030                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7031                        .addImm(0));
7032   } else if (IsThumb1) {
7033     // load + update AddrIn
7034     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7035                        .addReg(AddrIn).addImm(0));
7036     MachineInstrBuilder MIB =
7037         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7038     MIB = AddDefaultT1CC(MIB);
7039     MIB.addReg(AddrIn).addImm(LdSize);
7040     AddDefaultPred(MIB);
7041   } else if (IsThumb2) {
7042     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7043                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7044                        .addImm(LdSize));
7045   } else { // arm
7046     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7047                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7048                        .addReg(0).addImm(LdSize));
7049   }
7050 }
7051
7052 /// Emit a post-increment store operation with given size. The instructions
7053 /// will be added to BB at Pos.
7054 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7055                        const TargetInstrInfo *TII, DebugLoc dl,
7056                        unsigned StSize, unsigned Data, unsigned AddrIn,
7057                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7058   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7059   assert(StOpc != 0 && "Should have a store opcode");
7060   if (StSize >= 8) {
7061     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7062                        .addReg(AddrIn).addImm(0).addReg(Data));
7063   } else if (IsThumb1) {
7064     // store + update AddrIn
7065     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7066                        .addReg(AddrIn).addImm(0));
7067     MachineInstrBuilder MIB =
7068         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7069     MIB = AddDefaultT1CC(MIB);
7070     MIB.addReg(AddrIn).addImm(StSize);
7071     AddDefaultPred(MIB);
7072   } else if (IsThumb2) {
7073     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7074                        .addReg(Data).addReg(AddrIn).addImm(StSize));
7075   } else { // arm
7076     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7077                        .addReg(Data).addReg(AddrIn).addReg(0)
7078                        .addImm(StSize));
7079   }
7080 }
7081
7082 MachineBasicBlock *
7083 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7084                                    MachineBasicBlock *BB) const {
7085   // This pseudo instruction has 3 operands: dst, src, size
7086   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7087   // Otherwise, we will generate unrolled scalar copies.
7088   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7089   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7090   MachineFunction::iterator It = BB;
7091   ++It;
7092
7093   unsigned dest = MI->getOperand(0).getReg();
7094   unsigned src = MI->getOperand(1).getReg();
7095   unsigned SizeVal = MI->getOperand(2).getImm();
7096   unsigned Align = MI->getOperand(3).getImm();
7097   DebugLoc dl = MI->getDebugLoc();
7098
7099   MachineFunction *MF = BB->getParent();
7100   MachineRegisterInfo &MRI = MF->getRegInfo();
7101   unsigned UnitSize = 0;
7102   const TargetRegisterClass *TRC = nullptr;
7103   const TargetRegisterClass *VecTRC = nullptr;
7104
7105   bool IsThumb1 = Subtarget->isThumb1Only();
7106   bool IsThumb2 = Subtarget->isThumb2();
7107
7108   if (Align & 1) {
7109     UnitSize = 1;
7110   } else if (Align & 2) {
7111     UnitSize = 2;
7112   } else {
7113     // Check whether we can use NEON instructions.
7114     if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
7115         Subtarget->hasNEON()) {
7116       if ((Align % 16 == 0) && SizeVal >= 16)
7117         UnitSize = 16;
7118       else if ((Align % 8 == 0) && SizeVal >= 8)
7119         UnitSize = 8;
7120     }
7121     // Can't use NEON instructions.
7122     if (UnitSize == 0)
7123       UnitSize = 4;
7124   }
7125
7126   // Select the correct opcode and register class for unit size load/store
7127   bool IsNeon = UnitSize >= 8;
7128   TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
7129   if (IsNeon)
7130     VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
7131                             : UnitSize == 8 ? &ARM::DPRRegClass
7132                                             : nullptr;
7133
7134   unsigned BytesLeft = SizeVal % UnitSize;
7135   unsigned LoopSize = SizeVal - BytesLeft;
7136
7137   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7138     // Use LDR and STR to copy.
7139     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7140     // [destOut] = STR_POST(scratch, destIn, UnitSize)
7141     unsigned srcIn = src;
7142     unsigned destIn = dest;
7143     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7144       unsigned srcOut = MRI.createVirtualRegister(TRC);
7145       unsigned destOut = MRI.createVirtualRegister(TRC);
7146       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7147       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7148                  IsThumb1, IsThumb2);
7149       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7150                  IsThumb1, IsThumb2);
7151       srcIn = srcOut;
7152       destIn = destOut;
7153     }
7154
7155     // Handle the leftover bytes with LDRB and STRB.
7156     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7157     // [destOut] = STRB_POST(scratch, destIn, 1)
7158     for (unsigned i = 0; i < BytesLeft; i++) {
7159       unsigned srcOut = MRI.createVirtualRegister(TRC);
7160       unsigned destOut = MRI.createVirtualRegister(TRC);
7161       unsigned scratch = MRI.createVirtualRegister(TRC);
7162       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7163                  IsThumb1, IsThumb2);
7164       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7165                  IsThumb1, IsThumb2);
7166       srcIn = srcOut;
7167       destIn = destOut;
7168     }
7169     MI->eraseFromParent();   // The instruction is gone now.
7170     return BB;
7171   }
7172
7173   // Expand the pseudo op to a loop.
7174   // thisMBB:
7175   //   ...
7176   //   movw varEnd, # --> with thumb2
7177   //   movt varEnd, #
7178   //   ldrcp varEnd, idx --> without thumb2
7179   //   fallthrough --> loopMBB
7180   // loopMBB:
7181   //   PHI varPhi, varEnd, varLoop
7182   //   PHI srcPhi, src, srcLoop
7183   //   PHI destPhi, dst, destLoop
7184   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7185   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7186   //   subs varLoop, varPhi, #UnitSize
7187   //   bne loopMBB
7188   //   fallthrough --> exitMBB
7189   // exitMBB:
7190   //   epilogue to handle left-over bytes
7191   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7192   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7193   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7194   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7195   MF->insert(It, loopMBB);
7196   MF->insert(It, exitMBB);
7197
7198   // Transfer the remainder of BB and its successor edges to exitMBB.
7199   exitMBB->splice(exitMBB->begin(), BB,
7200                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7201   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7202
7203   // Load an immediate to varEnd.
7204   unsigned varEnd = MRI.createVirtualRegister(TRC);
7205   if (Subtarget->useMovt(*MF)) {
7206     unsigned Vtmp = varEnd;
7207     if ((LoopSize & 0xFFFF0000) != 0)
7208       Vtmp = MRI.createVirtualRegister(TRC);
7209     AddDefaultPred(BuildMI(BB, dl,
7210                            TII->get(IsThumb2 ? ARM::t2MOVi16 : ARM::MOVi16),
7211                            Vtmp).addImm(LoopSize & 0xFFFF));
7212
7213     if ((LoopSize & 0xFFFF0000) != 0)
7214       AddDefaultPred(BuildMI(BB, dl,
7215                              TII->get(IsThumb2 ? ARM::t2MOVTi16 : ARM::MOVTi16),
7216                              varEnd)
7217                          .addReg(Vtmp)
7218                          .addImm(LoopSize >> 16));
7219   } else {
7220     MachineConstantPool *ConstantPool = MF->getConstantPool();
7221     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7222     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7223
7224     // MachineConstantPool wants an explicit alignment.
7225     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7226     if (Align == 0)
7227       Align = getDataLayout()->getTypeAllocSize(C->getType());
7228     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7229
7230     if (IsThumb1)
7231       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7232           varEnd, RegState::Define).addConstantPoolIndex(Idx));
7233     else
7234       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7235           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7236   }
7237   BB->addSuccessor(loopMBB);
7238
7239   // Generate the loop body:
7240   //   varPhi = PHI(varLoop, varEnd)
7241   //   srcPhi = PHI(srcLoop, src)
7242   //   destPhi = PHI(destLoop, dst)
7243   MachineBasicBlock *entryBB = BB;
7244   BB = loopMBB;
7245   unsigned varLoop = MRI.createVirtualRegister(TRC);
7246   unsigned varPhi = MRI.createVirtualRegister(TRC);
7247   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7248   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7249   unsigned destLoop = MRI.createVirtualRegister(TRC);
7250   unsigned destPhi = MRI.createVirtualRegister(TRC);
7251
7252   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7253     .addReg(varLoop).addMBB(loopMBB)
7254     .addReg(varEnd).addMBB(entryBB);
7255   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7256     .addReg(srcLoop).addMBB(loopMBB)
7257     .addReg(src).addMBB(entryBB);
7258   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7259     .addReg(destLoop).addMBB(loopMBB)
7260     .addReg(dest).addMBB(entryBB);
7261
7262   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7263   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7264   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7265   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7266              IsThumb1, IsThumb2);
7267   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7268              IsThumb1, IsThumb2);
7269
7270   // Decrement loop variable by UnitSize.
7271   if (IsThumb1) {
7272     MachineInstrBuilder MIB =
7273         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7274     MIB = AddDefaultT1CC(MIB);
7275     MIB.addReg(varPhi).addImm(UnitSize);
7276     AddDefaultPred(MIB);
7277   } else {
7278     MachineInstrBuilder MIB =
7279         BuildMI(*BB, BB->end(), dl,
7280                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7281     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7282     MIB->getOperand(5).setReg(ARM::CPSR);
7283     MIB->getOperand(5).setIsDef(true);
7284   }
7285   BuildMI(*BB, BB->end(), dl,
7286           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7287       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7288
7289   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7290   BB->addSuccessor(loopMBB);
7291   BB->addSuccessor(exitMBB);
7292
7293   // Add epilogue to handle BytesLeft.
7294   BB = exitMBB;
7295   MachineInstr *StartOfExit = exitMBB->begin();
7296
7297   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7298   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7299   unsigned srcIn = srcLoop;
7300   unsigned destIn = destLoop;
7301   for (unsigned i = 0; i < BytesLeft; i++) {
7302     unsigned srcOut = MRI.createVirtualRegister(TRC);
7303     unsigned destOut = MRI.createVirtualRegister(TRC);
7304     unsigned scratch = MRI.createVirtualRegister(TRC);
7305     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7306                IsThumb1, IsThumb2);
7307     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7308                IsThumb1, IsThumb2);
7309     srcIn = srcOut;
7310     destIn = destOut;
7311   }
7312
7313   MI->eraseFromParent();   // The instruction is gone now.
7314   return BB;
7315 }
7316
7317 MachineBasicBlock *
7318 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7319                                        MachineBasicBlock *MBB) const {
7320   const TargetMachine &TM = getTargetMachine();
7321   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
7322   DebugLoc DL = MI->getDebugLoc();
7323
7324   assert(Subtarget->isTargetWindows() &&
7325          "__chkstk is only supported on Windows");
7326   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7327
7328   // __chkstk takes the number of words to allocate on the stack in R4, and
7329   // returns the stack adjustment in number of bytes in R4.  This will not
7330   // clober any other registers (other than the obvious lr).
7331   //
7332   // Although, technically, IP should be considered a register which may be
7333   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
7334   // thumb-2 environment, so there is no interworking required.  As a result, we
7335   // do not expect a veneer to be emitted by the linker, clobbering IP.
7336   //
7337   // Each module receives its own copy of __chkstk, so no import thunk is
7338   // required, again, ensuring that IP is not clobbered.
7339   //
7340   // Finally, although some linkers may theoretically provide a trampoline for
7341   // out of range calls (which is quite common due to a 32M range limitation of
7342   // branches for Thumb), we can generate the long-call version via
7343   // -mcmodel=large, alleviating the need for the trampoline which may clobber
7344   // IP.
7345
7346   switch (TM.getCodeModel()) {
7347   case CodeModel::Small:
7348   case CodeModel::Medium:
7349   case CodeModel::Default:
7350   case CodeModel::Kernel:
7351     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7352       .addImm((unsigned)ARMCC::AL).addReg(0)
7353       .addExternalSymbol("__chkstk")
7354       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7355       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7356       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7357     break;
7358   case CodeModel::Large:
7359   case CodeModel::JITDefault: {
7360     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7361     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7362
7363     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7364       .addExternalSymbol("__chkstk");
7365     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7366       .addImm((unsigned)ARMCC::AL).addReg(0)
7367       .addReg(Reg, RegState::Kill)
7368       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7369       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7370       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7371     break;
7372   }
7373   }
7374
7375   AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7376                                       ARM::SP)
7377                               .addReg(ARM::SP).addReg(ARM::R4)));
7378
7379   MI->eraseFromParent();
7380   return MBB;
7381 }
7382
7383 MachineBasicBlock *
7384 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7385                                                MachineBasicBlock *BB) const {
7386   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7387   DebugLoc dl = MI->getDebugLoc();
7388   bool isThumb2 = Subtarget->isThumb2();
7389   switch (MI->getOpcode()) {
7390   default: {
7391     MI->dump();
7392     llvm_unreachable("Unexpected instr type to insert");
7393   }
7394   // The Thumb2 pre-indexed stores have the same MI operands, they just
7395   // define them differently in the .td files from the isel patterns, so
7396   // they need pseudos.
7397   case ARM::t2STR_preidx:
7398     MI->setDesc(TII->get(ARM::t2STR_PRE));
7399     return BB;
7400   case ARM::t2STRB_preidx:
7401     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7402     return BB;
7403   case ARM::t2STRH_preidx:
7404     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7405     return BB;
7406
7407   case ARM::STRi_preidx:
7408   case ARM::STRBi_preidx: {
7409     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7410       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7411     // Decode the offset.
7412     unsigned Offset = MI->getOperand(4).getImm();
7413     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7414     Offset = ARM_AM::getAM2Offset(Offset);
7415     if (isSub)
7416       Offset = -Offset;
7417
7418     MachineMemOperand *MMO = *MI->memoperands_begin();
7419     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7420       .addOperand(MI->getOperand(0))  // Rn_wb
7421       .addOperand(MI->getOperand(1))  // Rt
7422       .addOperand(MI->getOperand(2))  // Rn
7423       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7424       .addOperand(MI->getOperand(5))  // pred
7425       .addOperand(MI->getOperand(6))
7426       .addMemOperand(MMO);
7427     MI->eraseFromParent();
7428     return BB;
7429   }
7430   case ARM::STRr_preidx:
7431   case ARM::STRBr_preidx:
7432   case ARM::STRH_preidx: {
7433     unsigned NewOpc;
7434     switch (MI->getOpcode()) {
7435     default: llvm_unreachable("unexpected opcode!");
7436     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7437     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7438     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7439     }
7440     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7441     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7442       MIB.addOperand(MI->getOperand(i));
7443     MI->eraseFromParent();
7444     return BB;
7445   }
7446
7447   case ARM::tMOVCCr_pseudo: {
7448     // To "insert" a SELECT_CC instruction, we actually have to insert the
7449     // diamond control-flow pattern.  The incoming instruction knows the
7450     // destination vreg to set, the condition code register to branch on, the
7451     // true/false values to select between, and a branch opcode to use.
7452     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7453     MachineFunction::iterator It = BB;
7454     ++It;
7455
7456     //  thisMBB:
7457     //  ...
7458     //   TrueVal = ...
7459     //   cmpTY ccX, r1, r2
7460     //   bCC copy1MBB
7461     //   fallthrough --> copy0MBB
7462     MachineBasicBlock *thisMBB  = BB;
7463     MachineFunction *F = BB->getParent();
7464     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7465     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7466     F->insert(It, copy0MBB);
7467     F->insert(It, sinkMBB);
7468
7469     // Transfer the remainder of BB and its successor edges to sinkMBB.
7470     sinkMBB->splice(sinkMBB->begin(), BB,
7471                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7472     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7473
7474     BB->addSuccessor(copy0MBB);
7475     BB->addSuccessor(sinkMBB);
7476
7477     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7478       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7479
7480     //  copy0MBB:
7481     //   %FalseValue = ...
7482     //   # fallthrough to sinkMBB
7483     BB = copy0MBB;
7484
7485     // Update machine-CFG edges
7486     BB->addSuccessor(sinkMBB);
7487
7488     //  sinkMBB:
7489     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7490     //  ...
7491     BB = sinkMBB;
7492     BuildMI(*BB, BB->begin(), dl,
7493             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7494       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7495       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7496
7497     MI->eraseFromParent();   // The pseudo instruction is gone now.
7498     return BB;
7499   }
7500
7501   case ARM::BCCi64:
7502   case ARM::BCCZi64: {
7503     // If there is an unconditional branch to the other successor, remove it.
7504     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7505
7506     // Compare both parts that make up the double comparison separately for
7507     // equality.
7508     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7509
7510     unsigned LHS1 = MI->getOperand(1).getReg();
7511     unsigned LHS2 = MI->getOperand(2).getReg();
7512     if (RHSisZero) {
7513       AddDefaultPred(BuildMI(BB, dl,
7514                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7515                      .addReg(LHS1).addImm(0));
7516       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7517         .addReg(LHS2).addImm(0)
7518         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7519     } else {
7520       unsigned RHS1 = MI->getOperand(3).getReg();
7521       unsigned RHS2 = MI->getOperand(4).getReg();
7522       AddDefaultPred(BuildMI(BB, dl,
7523                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7524                      .addReg(LHS1).addReg(RHS1));
7525       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7526         .addReg(LHS2).addReg(RHS2)
7527         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7528     }
7529
7530     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7531     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7532     if (MI->getOperand(0).getImm() == ARMCC::NE)
7533       std::swap(destMBB, exitMBB);
7534
7535     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7536       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7537     if (isThumb2)
7538       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7539     else
7540       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7541
7542     MI->eraseFromParent();   // The pseudo instruction is gone now.
7543     return BB;
7544   }
7545
7546   case ARM::Int_eh_sjlj_setjmp:
7547   case ARM::Int_eh_sjlj_setjmp_nofp:
7548   case ARM::tInt_eh_sjlj_setjmp:
7549   case ARM::t2Int_eh_sjlj_setjmp:
7550   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7551     EmitSjLjDispatchBlock(MI, BB);
7552     return BB;
7553
7554   case ARM::ABS:
7555   case ARM::t2ABS: {
7556     // To insert an ABS instruction, we have to insert the
7557     // diamond control-flow pattern.  The incoming instruction knows the
7558     // source vreg to test against 0, the destination vreg to set,
7559     // the condition code register to branch on, the
7560     // true/false values to select between, and a branch opcode to use.
7561     // It transforms
7562     //     V1 = ABS V0
7563     // into
7564     //     V2 = MOVS V0
7565     //     BCC                      (branch to SinkBB if V0 >= 0)
7566     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7567     //     SinkBB: V1 = PHI(V2, V3)
7568     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7569     MachineFunction::iterator BBI = BB;
7570     ++BBI;
7571     MachineFunction *Fn = BB->getParent();
7572     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7573     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7574     Fn->insert(BBI, RSBBB);
7575     Fn->insert(BBI, SinkBB);
7576
7577     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7578     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7579     bool ABSSrcKIll = MI->getOperand(1).isKill();
7580     bool isThumb2 = Subtarget->isThumb2();
7581     MachineRegisterInfo &MRI = Fn->getRegInfo();
7582     // In Thumb mode S must not be specified if source register is the SP or
7583     // PC and if destination register is the SP, so restrict register class
7584     unsigned NewRsbDstReg =
7585       MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
7586
7587     // Transfer the remainder of BB and its successor edges to sinkMBB.
7588     SinkBB->splice(SinkBB->begin(), BB,
7589                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
7590     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7591
7592     BB->addSuccessor(RSBBB);
7593     BB->addSuccessor(SinkBB);
7594
7595     // fall through to SinkMBB
7596     RSBBB->addSuccessor(SinkBB);
7597
7598     // insert a cmp at the end of BB
7599     AddDefaultPred(BuildMI(BB, dl,
7600                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7601                    .addReg(ABSSrcReg).addImm(0));
7602
7603     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7604     BuildMI(BB, dl,
7605       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7606       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7607
7608     // insert rsbri in RSBBB
7609     // Note: BCC and rsbri will be converted into predicated rsbmi
7610     // by if-conversion pass
7611     BuildMI(*RSBBB, RSBBB->begin(), dl,
7612       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7613       .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
7614       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7615
7616     // insert PHI in SinkBB,
7617     // reuse ABSDstReg to not change uses of ABS instruction
7618     BuildMI(*SinkBB, SinkBB->begin(), dl,
7619       TII->get(ARM::PHI), ABSDstReg)
7620       .addReg(NewRsbDstReg).addMBB(RSBBB)
7621       .addReg(ABSSrcReg).addMBB(BB);
7622
7623     // remove ABS instruction
7624     MI->eraseFromParent();
7625
7626     // return last added BB
7627     return SinkBB;
7628   }
7629   case ARM::COPY_STRUCT_BYVAL_I32:
7630     ++NumLoopByVals;
7631     return EmitStructByval(MI, BB);
7632   case ARM::WIN__CHKSTK:
7633     return EmitLowered__chkstk(MI, BB);
7634   }
7635 }
7636
7637 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7638                                                       SDNode *Node) const {
7639   const MCInstrDesc *MCID = &MI->getDesc();
7640   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7641   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7642   // operand is still set to noreg. If needed, set the optional operand's
7643   // register to CPSR, and remove the redundant implicit def.
7644   //
7645   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7646
7647   // Rename pseudo opcodes.
7648   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7649   if (NewOpc) {
7650     const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
7651     MCID = &TII->get(NewOpc);
7652
7653     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7654            "converted opcode should be the same except for cc_out");
7655
7656     MI->setDesc(*MCID);
7657
7658     // Add the optional cc_out operand
7659     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7660   }
7661   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7662
7663   // Any ARM instruction that sets the 's' bit should specify an optional
7664   // "cc_out" operand in the last operand position.
7665   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7666     assert(!NewOpc && "Optional cc_out operand required");
7667     return;
7668   }
7669   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7670   // since we already have an optional CPSR def.
7671   bool definesCPSR = false;
7672   bool deadCPSR = false;
7673   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7674        i != e; ++i) {
7675     const MachineOperand &MO = MI->getOperand(i);
7676     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7677       definesCPSR = true;
7678       if (MO.isDead())
7679         deadCPSR = true;
7680       MI->RemoveOperand(i);
7681       break;
7682     }
7683   }
7684   if (!definesCPSR) {
7685     assert(!NewOpc && "Optional cc_out operand required");
7686     return;
7687   }
7688   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7689   if (deadCPSR) {
7690     assert(!MI->getOperand(ccOutIdx).getReg() &&
7691            "expect uninitialized optional cc_out operand");
7692     return;
7693   }
7694
7695   // If this instruction was defined with an optional CPSR def and its dag node
7696   // had a live implicit CPSR def, then activate the optional CPSR def.
7697   MachineOperand &MO = MI->getOperand(ccOutIdx);
7698   MO.setReg(ARM::CPSR);
7699   MO.setIsDef(true);
7700 }
7701
7702 //===----------------------------------------------------------------------===//
7703 //                           ARM Optimization Hooks
7704 //===----------------------------------------------------------------------===//
7705
7706 // Helper function that checks if N is a null or all ones constant.
7707 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7708   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7709   if (!C)
7710     return false;
7711   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7712 }
7713
7714 // Return true if N is conditionally 0 or all ones.
7715 // Detects these expressions where cc is an i1 value:
7716 //
7717 //   (select cc 0, y)   [AllOnes=0]
7718 //   (select cc y, 0)   [AllOnes=0]
7719 //   (zext cc)          [AllOnes=0]
7720 //   (sext cc)          [AllOnes=0/1]
7721 //   (select cc -1, y)  [AllOnes=1]
7722 //   (select cc y, -1)  [AllOnes=1]
7723 //
7724 // Invert is set when N is the null/all ones constant when CC is false.
7725 // OtherOp is set to the alternative value of N.
7726 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7727                                        SDValue &CC, bool &Invert,
7728                                        SDValue &OtherOp,
7729                                        SelectionDAG &DAG) {
7730   switch (N->getOpcode()) {
7731   default: return false;
7732   case ISD::SELECT: {
7733     CC = N->getOperand(0);
7734     SDValue N1 = N->getOperand(1);
7735     SDValue N2 = N->getOperand(2);
7736     if (isZeroOrAllOnes(N1, AllOnes)) {
7737       Invert = false;
7738       OtherOp = N2;
7739       return true;
7740     }
7741     if (isZeroOrAllOnes(N2, AllOnes)) {
7742       Invert = true;
7743       OtherOp = N1;
7744       return true;
7745     }
7746     return false;
7747   }
7748   case ISD::ZERO_EXTEND:
7749     // (zext cc) can never be the all ones value.
7750     if (AllOnes)
7751       return false;
7752     // Fall through.
7753   case ISD::SIGN_EXTEND: {
7754     SDLoc dl(N);
7755     EVT VT = N->getValueType(0);
7756     CC = N->getOperand(0);
7757     if (CC.getValueType() != MVT::i1)
7758       return false;
7759     Invert = !AllOnes;
7760     if (AllOnes)
7761       // When looking for an AllOnes constant, N is an sext, and the 'other'
7762       // value is 0.
7763       OtherOp = DAG.getConstant(0, dl, VT);
7764     else if (N->getOpcode() == ISD::ZERO_EXTEND)
7765       // When looking for a 0 constant, N can be zext or sext.
7766       OtherOp = DAG.getConstant(1, dl, VT);
7767     else
7768       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
7769                                 VT);
7770     return true;
7771   }
7772   }
7773 }
7774
7775 // Combine a constant select operand into its use:
7776 //
7777 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
7778 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
7779 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
7780 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
7781 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
7782 //
7783 // The transform is rejected if the select doesn't have a constant operand that
7784 // is null, or all ones when AllOnes is set.
7785 //
7786 // Also recognize sext/zext from i1:
7787 //
7788 //   (add (zext cc), x) -> (select cc (add x, 1), x)
7789 //   (add (sext cc), x) -> (select cc (add x, -1), x)
7790 //
7791 // These transformations eventually create predicated instructions.
7792 //
7793 // @param N       The node to transform.
7794 // @param Slct    The N operand that is a select.
7795 // @param OtherOp The other N operand (x above).
7796 // @param DCI     Context.
7797 // @param AllOnes Require the select constant to be all ones instead of null.
7798 // @returns The new node, or SDValue() on failure.
7799 static
7800 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7801                             TargetLowering::DAGCombinerInfo &DCI,
7802                             bool AllOnes = false) {
7803   SelectionDAG &DAG = DCI.DAG;
7804   EVT VT = N->getValueType(0);
7805   SDValue NonConstantVal;
7806   SDValue CCOp;
7807   bool SwapSelectOps;
7808   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7809                                   NonConstantVal, DAG))
7810     return SDValue();
7811
7812   // Slct is now know to be the desired identity constant when CC is true.
7813   SDValue TrueVal = OtherOp;
7814   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7815                                  OtherOp, NonConstantVal);
7816   // Unless SwapSelectOps says CC should be false.
7817   if (SwapSelectOps)
7818     std::swap(TrueVal, FalseVal);
7819
7820   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7821                      CCOp, TrueVal, FalseVal);
7822 }
7823
7824 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7825 static
7826 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7827                                        TargetLowering::DAGCombinerInfo &DCI) {
7828   SDValue N0 = N->getOperand(0);
7829   SDValue N1 = N->getOperand(1);
7830   if (N0.getNode()->hasOneUse()) {
7831     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7832     if (Result.getNode())
7833       return Result;
7834   }
7835   if (N1.getNode()->hasOneUse()) {
7836     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7837     if (Result.getNode())
7838       return Result;
7839   }
7840   return SDValue();
7841 }
7842
7843 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7844 // (only after legalization).
7845 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7846                                  TargetLowering::DAGCombinerInfo &DCI,
7847                                  const ARMSubtarget *Subtarget) {
7848
7849   // Only perform optimization if after legalize, and if NEON is available. We
7850   // also expected both operands to be BUILD_VECTORs.
7851   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7852       || N0.getOpcode() != ISD::BUILD_VECTOR
7853       || N1.getOpcode() != ISD::BUILD_VECTOR)
7854     return SDValue();
7855
7856   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7857   EVT VT = N->getValueType(0);
7858   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7859     return SDValue();
7860
7861   // Check that the vector operands are of the right form.
7862   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7863   // operands, where N is the size of the formed vector.
7864   // Each EXTRACT_VECTOR should have the same input vector and odd or even
7865   // index such that we have a pair wise add pattern.
7866
7867   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7868   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7869     return SDValue();
7870   SDValue Vec = N0->getOperand(0)->getOperand(0);
7871   SDNode *V = Vec.getNode();
7872   unsigned nextIndex = 0;
7873
7874   // For each operands to the ADD which are BUILD_VECTORs,
7875   // check to see if each of their operands are an EXTRACT_VECTOR with
7876   // the same vector and appropriate index.
7877   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7878     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7879         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7880
7881       SDValue ExtVec0 = N0->getOperand(i);
7882       SDValue ExtVec1 = N1->getOperand(i);
7883
7884       // First operand is the vector, verify its the same.
7885       if (V != ExtVec0->getOperand(0).getNode() ||
7886           V != ExtVec1->getOperand(0).getNode())
7887         return SDValue();
7888
7889       // Second is the constant, verify its correct.
7890       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7891       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7892
7893       // For the constant, we want to see all the even or all the odd.
7894       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7895           || C1->getZExtValue() != nextIndex+1)
7896         return SDValue();
7897
7898       // Increment index.
7899       nextIndex+=2;
7900     } else
7901       return SDValue();
7902   }
7903
7904   // Create VPADDL node.
7905   SelectionDAG &DAG = DCI.DAG;
7906   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7907
7908   SDLoc dl(N);
7909
7910   // Build operand list.
7911   SmallVector<SDValue, 8> Ops;
7912   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
7913                                 TLI.getPointerTy()));
7914
7915   // Input is the vector.
7916   Ops.push_back(Vec);
7917
7918   // Get widened type and narrowed type.
7919   MVT widenType;
7920   unsigned numElem = VT.getVectorNumElements();
7921   
7922   EVT inputLaneType = Vec.getValueType().getVectorElementType();
7923   switch (inputLaneType.getSimpleVT().SimpleTy) {
7924     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7925     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7926     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7927     default:
7928       llvm_unreachable("Invalid vector element type for padd optimization.");
7929   }
7930
7931   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
7932   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
7933   return DAG.getNode(ExtOp, dl, VT, tmp);
7934 }
7935
7936 static SDValue findMUL_LOHI(SDValue V) {
7937   if (V->getOpcode() == ISD::UMUL_LOHI ||
7938       V->getOpcode() == ISD::SMUL_LOHI)
7939     return V;
7940   return SDValue();
7941 }
7942
7943 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7944                                      TargetLowering::DAGCombinerInfo &DCI,
7945                                      const ARMSubtarget *Subtarget) {
7946
7947   if (Subtarget->isThumb1Only()) return SDValue();
7948
7949   // Only perform the checks after legalize when the pattern is available.
7950   if (DCI.isBeforeLegalize()) return SDValue();
7951
7952   // Look for multiply add opportunities.
7953   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7954   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7955   // a glue link from the first add to the second add.
7956   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7957   // a S/UMLAL instruction.
7958   //          loAdd   UMUL_LOHI
7959   //            \    / :lo    \ :hi
7960   //             \  /          \          [no multiline comment]
7961   //              ADDC         |  hiAdd
7962   //                 \ :glue  /  /
7963   //                  \      /  /
7964   //                    ADDE
7965   //
7966   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7967   SDValue AddcOp0 = AddcNode->getOperand(0);
7968   SDValue AddcOp1 = AddcNode->getOperand(1);
7969
7970   // Check if the two operands are from the same mul_lohi node.
7971   if (AddcOp0.getNode() == AddcOp1.getNode())
7972     return SDValue();
7973
7974   assert(AddcNode->getNumValues() == 2 &&
7975          AddcNode->getValueType(0) == MVT::i32 &&
7976          "Expect ADDC with two result values. First: i32");
7977
7978   // Check that we have a glued ADDC node.
7979   if (AddcNode->getValueType(1) != MVT::Glue)
7980     return SDValue();
7981
7982   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7983   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7984       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7985       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7986       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7987     return SDValue();
7988
7989   // Look for the glued ADDE.
7990   SDNode* AddeNode = AddcNode->getGluedUser();
7991   if (!AddeNode)
7992     return SDValue();
7993
7994   // Make sure it is really an ADDE.
7995   if (AddeNode->getOpcode() != ISD::ADDE)
7996     return SDValue();
7997
7998   assert(AddeNode->getNumOperands() == 3 &&
7999          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8000          "ADDE node has the wrong inputs");
8001
8002   // Check for the triangle shape.
8003   SDValue AddeOp0 = AddeNode->getOperand(0);
8004   SDValue AddeOp1 = AddeNode->getOperand(1);
8005
8006   // Make sure that the ADDE operands are not coming from the same node.
8007   if (AddeOp0.getNode() == AddeOp1.getNode())
8008     return SDValue();
8009
8010   // Find the MUL_LOHI node walking up ADDE's operands.
8011   bool IsLeftOperandMUL = false;
8012   SDValue MULOp = findMUL_LOHI(AddeOp0);
8013   if (MULOp == SDValue())
8014    MULOp = findMUL_LOHI(AddeOp1);
8015   else
8016     IsLeftOperandMUL = true;
8017   if (MULOp == SDValue())
8018     return SDValue();
8019
8020   // Figure out the right opcode.
8021   unsigned Opc = MULOp->getOpcode();
8022   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8023
8024   // Figure out the high and low input values to the MLAL node.
8025   SDValue* HiAdd = nullptr;
8026   SDValue* LoMul = nullptr;
8027   SDValue* LowAdd = nullptr;
8028
8029   // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
8030   if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
8031     return SDValue();
8032
8033   if (IsLeftOperandMUL)
8034     HiAdd = &AddeOp1;
8035   else
8036     HiAdd = &AddeOp0;
8037
8038
8039   // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
8040   // whose low result is fed to the ADDC we are checking.
8041
8042   if (AddcOp0 == MULOp.getValue(0)) {
8043     LoMul = &AddcOp0;
8044     LowAdd = &AddcOp1;
8045   }
8046   if (AddcOp1 == MULOp.getValue(0)) {
8047     LoMul = &AddcOp1;
8048     LowAdd = &AddcOp0;
8049   }
8050
8051   if (!LoMul)
8052     return SDValue();
8053
8054   // Create the merged node.
8055   SelectionDAG &DAG = DCI.DAG;
8056
8057   // Build operand list.
8058   SmallVector<SDValue, 8> Ops;
8059   Ops.push_back(LoMul->getOperand(0));
8060   Ops.push_back(LoMul->getOperand(1));
8061   Ops.push_back(*LowAdd);
8062   Ops.push_back(*HiAdd);
8063
8064   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
8065                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
8066
8067   // Replace the ADDs' nodes uses by the MLA node's values.
8068   SDValue HiMLALResult(MLALNode.getNode(), 1);
8069   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8070
8071   SDValue LoMLALResult(MLALNode.getNode(), 0);
8072   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8073
8074   // Return original node to notify the driver to stop replacing.
8075   SDValue resNode(AddcNode, 0);
8076   return resNode;
8077 }
8078
8079 /// PerformADDCCombine - Target-specific dag combine transform from
8080 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8081 static SDValue PerformADDCCombine(SDNode *N,
8082                                  TargetLowering::DAGCombinerInfo &DCI,
8083                                  const ARMSubtarget *Subtarget) {
8084
8085   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8086
8087 }
8088
8089 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8090 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
8091 /// called with the default operands, and if that fails, with commuted
8092 /// operands.
8093 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8094                                           TargetLowering::DAGCombinerInfo &DCI,
8095                                           const ARMSubtarget *Subtarget){
8096
8097   // Attempt to create vpaddl for this add.
8098   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8099   if (Result.getNode())
8100     return Result;
8101
8102   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8103   if (N0.getNode()->hasOneUse()) {
8104     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8105     if (Result.getNode()) return Result;
8106   }
8107   return SDValue();
8108 }
8109
8110 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8111 ///
8112 static SDValue PerformADDCombine(SDNode *N,
8113                                  TargetLowering::DAGCombinerInfo &DCI,
8114                                  const ARMSubtarget *Subtarget) {
8115   SDValue N0 = N->getOperand(0);
8116   SDValue N1 = N->getOperand(1);
8117
8118   // First try with the default operand order.
8119   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8120   if (Result.getNode())
8121     return Result;
8122
8123   // If that didn't work, try again with the operands commuted.
8124   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8125 }
8126
8127 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8128 ///
8129 static SDValue PerformSUBCombine(SDNode *N,
8130                                  TargetLowering::DAGCombinerInfo &DCI) {
8131   SDValue N0 = N->getOperand(0);
8132   SDValue N1 = N->getOperand(1);
8133
8134   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8135   if (N1.getNode()->hasOneUse()) {
8136     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8137     if (Result.getNode()) return Result;
8138   }
8139
8140   return SDValue();
8141 }
8142
8143 /// PerformVMULCombine
8144 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8145 /// special multiplier accumulator forwarding.
8146 ///   vmul d3, d0, d2
8147 ///   vmla d3, d1, d2
8148 /// is faster than
8149 ///   vadd d3, d0, d1
8150 ///   vmul d3, d3, d2
8151 //  However, for (A + B) * (A + B),
8152 //    vadd d2, d0, d1
8153 //    vmul d3, d0, d2
8154 //    vmla d3, d1, d2
8155 //  is slower than
8156 //    vadd d2, d0, d1
8157 //    vmul d3, d2, d2
8158 static SDValue PerformVMULCombine(SDNode *N,
8159                                   TargetLowering::DAGCombinerInfo &DCI,
8160                                   const ARMSubtarget *Subtarget) {
8161   if (!Subtarget->hasVMLxForwarding())
8162     return SDValue();
8163
8164   SelectionDAG &DAG = DCI.DAG;
8165   SDValue N0 = N->getOperand(0);
8166   SDValue N1 = N->getOperand(1);
8167   unsigned Opcode = N0.getOpcode();
8168   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8169       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8170     Opcode = N1.getOpcode();
8171     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8172         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8173       return SDValue();
8174     std::swap(N0, N1);
8175   }
8176
8177   if (N0 == N1)
8178     return SDValue();
8179
8180   EVT VT = N->getValueType(0);
8181   SDLoc DL(N);
8182   SDValue N00 = N0->getOperand(0);
8183   SDValue N01 = N0->getOperand(1);
8184   return DAG.getNode(Opcode, DL, VT,
8185                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8186                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8187 }
8188
8189 static SDValue PerformMULCombine(SDNode *N,
8190                                  TargetLowering::DAGCombinerInfo &DCI,
8191                                  const ARMSubtarget *Subtarget) {
8192   SelectionDAG &DAG = DCI.DAG;
8193
8194   if (Subtarget->isThumb1Only())
8195     return SDValue();
8196
8197   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8198     return SDValue();
8199
8200   EVT VT = N->getValueType(0);
8201   if (VT.is64BitVector() || VT.is128BitVector())
8202     return PerformVMULCombine(N, DCI, Subtarget);
8203   if (VT != MVT::i32)
8204     return SDValue();
8205
8206   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8207   if (!C)
8208     return SDValue();
8209
8210   int64_t MulAmt = C->getSExtValue();
8211   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8212
8213   ShiftAmt = ShiftAmt & (32 - 1);
8214   SDValue V = N->getOperand(0);
8215   SDLoc DL(N);
8216
8217   SDValue Res;
8218   MulAmt >>= ShiftAmt;
8219
8220   if (MulAmt >= 0) {
8221     if (isPowerOf2_32(MulAmt - 1)) {
8222       // (mul x, 2^N + 1) => (add (shl x, N), x)
8223       Res = DAG.getNode(ISD::ADD, DL, VT,
8224                         V,
8225                         DAG.getNode(ISD::SHL, DL, VT,
8226                                     V,
8227                                     DAG.getConstant(Log2_32(MulAmt - 1), DL,
8228                                                     MVT::i32)));
8229     } else if (isPowerOf2_32(MulAmt + 1)) {
8230       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8231       Res = DAG.getNode(ISD::SUB, DL, VT,
8232                         DAG.getNode(ISD::SHL, DL, VT,
8233                                     V,
8234                                     DAG.getConstant(Log2_32(MulAmt + 1), DL,
8235                                                     MVT::i32)),
8236                         V);
8237     } else
8238       return SDValue();
8239   } else {
8240     uint64_t MulAmtAbs = -MulAmt;
8241     if (isPowerOf2_32(MulAmtAbs + 1)) {
8242       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8243       Res = DAG.getNode(ISD::SUB, DL, VT,
8244                         V,
8245                         DAG.getNode(ISD::SHL, DL, VT,
8246                                     V,
8247                                     DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
8248                                                     MVT::i32)));
8249     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8250       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8251       Res = DAG.getNode(ISD::ADD, DL, VT,
8252                         V,
8253                         DAG.getNode(ISD::SHL, DL, VT,
8254                                     V,
8255                                     DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
8256                                                     MVT::i32)));
8257       Res = DAG.getNode(ISD::SUB, DL, VT,
8258                         DAG.getConstant(0, DL, MVT::i32), Res);
8259
8260     } else
8261       return SDValue();
8262   }
8263
8264   if (ShiftAmt != 0)
8265     Res = DAG.getNode(ISD::SHL, DL, VT,
8266                       Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
8267
8268   // Do not add new nodes to DAG combiner worklist.
8269   DCI.CombineTo(N, Res, false);
8270   return SDValue();
8271 }
8272
8273 static SDValue PerformANDCombine(SDNode *N,
8274                                  TargetLowering::DAGCombinerInfo &DCI,
8275                                  const ARMSubtarget *Subtarget) {
8276
8277   // Attempt to use immediate-form VBIC
8278   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8279   SDLoc dl(N);
8280   EVT VT = N->getValueType(0);
8281   SelectionDAG &DAG = DCI.DAG;
8282
8283   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8284     return SDValue();
8285
8286   APInt SplatBits, SplatUndef;
8287   unsigned SplatBitSize;
8288   bool HasAnyUndefs;
8289   if (BVN &&
8290       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8291     if (SplatBitSize <= 64) {
8292       EVT VbicVT;
8293       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8294                                       SplatUndef.getZExtValue(), SplatBitSize,
8295                                       DAG, dl, VbicVT, VT.is128BitVector(),
8296                                       OtherModImm);
8297       if (Val.getNode()) {
8298         SDValue Input =
8299           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8300         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8301         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8302       }
8303     }
8304   }
8305
8306   if (!Subtarget->isThumb1Only()) {
8307     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8308     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8309     if (Result.getNode())
8310       return Result;
8311   }
8312
8313   return SDValue();
8314 }
8315
8316 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8317 static SDValue PerformORCombine(SDNode *N,
8318                                 TargetLowering::DAGCombinerInfo &DCI,
8319                                 const ARMSubtarget *Subtarget) {
8320   // Attempt to use immediate-form VORR
8321   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8322   SDLoc dl(N);
8323   EVT VT = N->getValueType(0);
8324   SelectionDAG &DAG = DCI.DAG;
8325
8326   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8327     return SDValue();
8328
8329   APInt SplatBits, SplatUndef;
8330   unsigned SplatBitSize;
8331   bool HasAnyUndefs;
8332   if (BVN && Subtarget->hasNEON() &&
8333       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8334     if (SplatBitSize <= 64) {
8335       EVT VorrVT;
8336       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8337                                       SplatUndef.getZExtValue(), SplatBitSize,
8338                                       DAG, dl, VorrVT, VT.is128BitVector(),
8339                                       OtherModImm);
8340       if (Val.getNode()) {
8341         SDValue Input =
8342           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8343         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8344         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8345       }
8346     }
8347   }
8348
8349   if (!Subtarget->isThumb1Only()) {
8350     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8351     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8352     if (Result.getNode())
8353       return Result;
8354   }
8355
8356   // The code below optimizes (or (and X, Y), Z).
8357   // The AND operand needs to have a single user to make these optimizations
8358   // profitable.
8359   SDValue N0 = N->getOperand(0);
8360   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8361     return SDValue();
8362   SDValue N1 = N->getOperand(1);
8363
8364   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8365   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8366       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8367     APInt SplatUndef;
8368     unsigned SplatBitSize;
8369     bool HasAnyUndefs;
8370
8371     APInt SplatBits0, SplatBits1;
8372     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8373     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8374     // Ensure that the second operand of both ands are constants
8375     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8376                                       HasAnyUndefs) && !HasAnyUndefs) {
8377         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8378                                           HasAnyUndefs) && !HasAnyUndefs) {
8379             // Ensure that the bit width of the constants are the same and that
8380             // the splat arguments are logical inverses as per the pattern we
8381             // are trying to simplify.
8382             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8383                 SplatBits0 == ~SplatBits1) {
8384                 // Canonicalize the vector type to make instruction selection
8385                 // simpler.
8386                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8387                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8388                                              N0->getOperand(1),
8389                                              N0->getOperand(0),
8390                                              N1->getOperand(0));
8391                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8392             }
8393         }
8394     }
8395   }
8396
8397   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8398   // reasonable.
8399
8400   // BFI is only available on V6T2+
8401   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8402     return SDValue();
8403
8404   SDLoc DL(N);
8405   // 1) or (and A, mask), val => ARMbfi A, val, mask
8406   //      iff (val & mask) == val
8407   //
8408   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8409   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8410   //          && mask == ~mask2
8411   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8412   //          && ~mask == mask2
8413   //  (i.e., copy a bitfield value into another bitfield of the same width)
8414
8415   if (VT != MVT::i32)
8416     return SDValue();
8417
8418   SDValue N00 = N0.getOperand(0);
8419
8420   // The value and the mask need to be constants so we can verify this is
8421   // actually a bitfield set. If the mask is 0xffff, we can do better
8422   // via a movt instruction, so don't use BFI in that case.
8423   SDValue MaskOp = N0.getOperand(1);
8424   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8425   if (!MaskC)
8426     return SDValue();
8427   unsigned Mask = MaskC->getZExtValue();
8428   if (Mask == 0xffff)
8429     return SDValue();
8430   SDValue Res;
8431   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8432   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8433   if (N1C) {
8434     unsigned Val = N1C->getZExtValue();
8435     if ((Val & ~Mask) != Val)
8436       return SDValue();
8437
8438     if (ARM::isBitFieldInvertedMask(Mask)) {
8439       Val >>= countTrailingZeros(~Mask);
8440
8441       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8442                         DAG.getConstant(Val, DL, MVT::i32),
8443                         DAG.getConstant(Mask, DL, MVT::i32));
8444
8445       // Do not add new nodes to DAG combiner worklist.
8446       DCI.CombineTo(N, Res, false);
8447       return SDValue();
8448     }
8449   } else if (N1.getOpcode() == ISD::AND) {
8450     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8451     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8452     if (!N11C)
8453       return SDValue();
8454     unsigned Mask2 = N11C->getZExtValue();
8455
8456     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8457     // as is to match.
8458     if (ARM::isBitFieldInvertedMask(Mask) &&
8459         (Mask == ~Mask2)) {
8460       // The pack halfword instruction works better for masks that fit it,
8461       // so use that when it's available.
8462       if (Subtarget->hasT2ExtractPack() &&
8463           (Mask == 0xffff || Mask == 0xffff0000))
8464         return SDValue();
8465       // 2a
8466       unsigned amt = countTrailingZeros(Mask2);
8467       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8468                         DAG.getConstant(amt, DL, MVT::i32));
8469       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8470                         DAG.getConstant(Mask, DL, MVT::i32));
8471       // Do not add new nodes to DAG combiner worklist.
8472       DCI.CombineTo(N, Res, false);
8473       return SDValue();
8474     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8475                (~Mask == Mask2)) {
8476       // The pack halfword instruction works better for masks that fit it,
8477       // so use that when it's available.
8478       if (Subtarget->hasT2ExtractPack() &&
8479           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8480         return SDValue();
8481       // 2b
8482       unsigned lsb = countTrailingZeros(Mask);
8483       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8484                         DAG.getConstant(lsb, DL, MVT::i32));
8485       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8486                         DAG.getConstant(Mask2, DL, MVT::i32));
8487       // Do not add new nodes to DAG combiner worklist.
8488       DCI.CombineTo(N, Res, false);
8489       return SDValue();
8490     }
8491   }
8492
8493   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8494       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8495       ARM::isBitFieldInvertedMask(~Mask)) {
8496     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8497     // where lsb(mask) == #shamt and masked bits of B are known zero.
8498     SDValue ShAmt = N00.getOperand(1);
8499     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8500     unsigned LSB = countTrailingZeros(Mask);
8501     if (ShAmtC != LSB)
8502       return SDValue();
8503
8504     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8505                       DAG.getConstant(~Mask, DL, MVT::i32));
8506
8507     // Do not add new nodes to DAG combiner worklist.
8508     DCI.CombineTo(N, Res, false);
8509   }
8510
8511   return SDValue();
8512 }
8513
8514 static SDValue PerformXORCombine(SDNode *N,
8515                                  TargetLowering::DAGCombinerInfo &DCI,
8516                                  const ARMSubtarget *Subtarget) {
8517   EVT VT = N->getValueType(0);
8518   SelectionDAG &DAG = DCI.DAG;
8519
8520   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8521     return SDValue();
8522
8523   if (!Subtarget->isThumb1Only()) {
8524     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8525     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8526     if (Result.getNode())
8527       return Result;
8528   }
8529
8530   return SDValue();
8531 }
8532
8533 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8534 /// the bits being cleared by the AND are not demanded by the BFI.
8535 static SDValue PerformBFICombine(SDNode *N,
8536                                  TargetLowering::DAGCombinerInfo &DCI) {
8537   SDValue N1 = N->getOperand(1);
8538   if (N1.getOpcode() == ISD::AND) {
8539     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8540     if (!N11C)
8541       return SDValue();
8542     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8543     unsigned LSB = countTrailingZeros(~InvMask);
8544     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8545     assert(Width <
8546                static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
8547            "undefined behavior");
8548     unsigned Mask = (1u << Width) - 1;
8549     unsigned Mask2 = N11C->getZExtValue();
8550     if ((Mask & (~Mask2)) == 0)
8551       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8552                              N->getOperand(0), N1.getOperand(0),
8553                              N->getOperand(2));
8554   }
8555   return SDValue();
8556 }
8557
8558 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8559 /// ARMISD::VMOVRRD.
8560 static SDValue PerformVMOVRRDCombine(SDNode *N,
8561                                      TargetLowering::DAGCombinerInfo &DCI,
8562                                      const ARMSubtarget *Subtarget) {
8563   // vmovrrd(vmovdrr x, y) -> x,y
8564   SDValue InDouble = N->getOperand(0);
8565   if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
8566     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8567
8568   // vmovrrd(load f64) -> (load i32), (load i32)
8569   SDNode *InNode = InDouble.getNode();
8570   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8571       InNode->getValueType(0) == MVT::f64 &&
8572       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8573       !cast<LoadSDNode>(InNode)->isVolatile()) {
8574     // TODO: Should this be done for non-FrameIndex operands?
8575     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8576
8577     SelectionDAG &DAG = DCI.DAG;
8578     SDLoc DL(LD);
8579     SDValue BasePtr = LD->getBasePtr();
8580     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8581                                  LD->getPointerInfo(), LD->isVolatile(),
8582                                  LD->isNonTemporal(), LD->isInvariant(),
8583                                  LD->getAlignment());
8584
8585     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8586                                     DAG.getConstant(4, DL, MVT::i32));
8587     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8588                                  LD->getPointerInfo(), LD->isVolatile(),
8589                                  LD->isNonTemporal(), LD->isInvariant(),
8590                                  std::min(4U, LD->getAlignment() / 2));
8591
8592     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8593     if (DCI.DAG.getTargetLoweringInfo().isBigEndian())
8594       std::swap (NewLD1, NewLD2);
8595     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8596     return Result;
8597   }
8598
8599   return SDValue();
8600 }
8601
8602 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8603 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8604 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8605   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8606   SDValue Op0 = N->getOperand(0);
8607   SDValue Op1 = N->getOperand(1);
8608   if (Op0.getOpcode() == ISD::BITCAST)
8609     Op0 = Op0.getOperand(0);
8610   if (Op1.getOpcode() == ISD::BITCAST)
8611     Op1 = Op1.getOperand(0);
8612   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8613       Op0.getNode() == Op1.getNode() &&
8614       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8615     return DAG.getNode(ISD::BITCAST, SDLoc(N),
8616                        N->getValueType(0), Op0.getOperand(0));
8617   return SDValue();
8618 }
8619
8620 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8621 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8622 /// i64 vector to have f64 elements, since the value can then be loaded
8623 /// directly into a VFP register.
8624 static bool hasNormalLoadOperand(SDNode *N) {
8625   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8626   for (unsigned i = 0; i < NumElts; ++i) {
8627     SDNode *Elt = N->getOperand(i).getNode();
8628     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8629       return true;
8630   }
8631   return false;
8632 }
8633
8634 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8635 /// ISD::BUILD_VECTOR.
8636 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8637                                           TargetLowering::DAGCombinerInfo &DCI,
8638                                           const ARMSubtarget *Subtarget) {
8639   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8640   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
8641   // into a pair of GPRs, which is fine when the value is used as a scalar,
8642   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8643   SelectionDAG &DAG = DCI.DAG;
8644   if (N->getNumOperands() == 2) {
8645     SDValue RV = PerformVMOVDRRCombine(N, DAG);
8646     if (RV.getNode())
8647       return RV;
8648   }
8649
8650   // Load i64 elements as f64 values so that type legalization does not split
8651   // them up into i32 values.
8652   EVT VT = N->getValueType(0);
8653   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8654     return SDValue();
8655   SDLoc dl(N);
8656   SmallVector<SDValue, 8> Ops;
8657   unsigned NumElts = VT.getVectorNumElements();
8658   for (unsigned i = 0; i < NumElts; ++i) {
8659     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8660     Ops.push_back(V);
8661     // Make the DAGCombiner fold the bitcast.
8662     DCI.AddToWorklist(V.getNode());
8663   }
8664   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8665   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8666   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8667 }
8668
8669 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8670 static SDValue
8671 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8672   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8673   // At that time, we may have inserted bitcasts from integer to float.
8674   // If these bitcasts have survived DAGCombine, change the lowering of this
8675   // BUILD_VECTOR in something more vector friendly, i.e., that does not
8676   // force to use floating point types.
8677
8678   // Make sure we can change the type of the vector.
8679   // This is possible iff:
8680   // 1. The vector is only used in a bitcast to a integer type. I.e.,
8681   //    1.1. Vector is used only once.
8682   //    1.2. Use is a bit convert to an integer type.
8683   // 2. The size of its operands are 32-bits (64-bits are not legal).
8684   EVT VT = N->getValueType(0);
8685   EVT EltVT = VT.getVectorElementType();
8686
8687   // Check 1.1. and 2.
8688   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8689     return SDValue();
8690
8691   // By construction, the input type must be float.
8692   assert(EltVT == MVT::f32 && "Unexpected type!");
8693
8694   // Check 1.2.
8695   SDNode *Use = *N->use_begin();
8696   if (Use->getOpcode() != ISD::BITCAST ||
8697       Use->getValueType(0).isFloatingPoint())
8698     return SDValue();
8699
8700   // Check profitability.
8701   // Model is, if more than half of the relevant operands are bitcast from
8702   // i32, turn the build_vector into a sequence of insert_vector_elt.
8703   // Relevant operands are everything that is not statically
8704   // (i.e., at compile time) bitcasted.
8705   unsigned NumOfBitCastedElts = 0;
8706   unsigned NumElts = VT.getVectorNumElements();
8707   unsigned NumOfRelevantElts = NumElts;
8708   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8709     SDValue Elt = N->getOperand(Idx);
8710     if (Elt->getOpcode() == ISD::BITCAST) {
8711       // Assume only bit cast to i32 will go away.
8712       if (Elt->getOperand(0).getValueType() == MVT::i32)
8713         ++NumOfBitCastedElts;
8714     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8715       // Constants are statically casted, thus do not count them as
8716       // relevant operands.
8717       --NumOfRelevantElts;
8718   }
8719
8720   // Check if more than half of the elements require a non-free bitcast.
8721   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8722     return SDValue();
8723
8724   SelectionDAG &DAG = DCI.DAG;
8725   // Create the new vector type.
8726   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8727   // Check if the type is legal.
8728   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8729   if (!TLI.isTypeLegal(VecVT))
8730     return SDValue();
8731
8732   // Combine:
8733   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8734   // => BITCAST INSERT_VECTOR_ELT
8735   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8736   //                      (BITCAST EN), N.
8737   SDValue Vec = DAG.getUNDEF(VecVT);
8738   SDLoc dl(N);
8739   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8740     SDValue V = N->getOperand(Idx);
8741     if (V.getOpcode() == ISD::UNDEF)
8742       continue;
8743     if (V.getOpcode() == ISD::BITCAST &&
8744         V->getOperand(0).getValueType() == MVT::i32)
8745       // Fold obvious case.
8746       V = V.getOperand(0);
8747     else {
8748       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
8749       // Make the DAGCombiner fold the bitcasts.
8750       DCI.AddToWorklist(V.getNode());
8751     }
8752     SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
8753     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8754   }
8755   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8756   // Make the DAGCombiner fold the bitcasts.
8757   DCI.AddToWorklist(Vec.getNode());
8758   return Vec;
8759 }
8760
8761 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8762 /// ISD::INSERT_VECTOR_ELT.
8763 static SDValue PerformInsertEltCombine(SDNode *N,
8764                                        TargetLowering::DAGCombinerInfo &DCI) {
8765   // Bitcast an i64 load inserted into a vector to f64.
8766   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8767   EVT VT = N->getValueType(0);
8768   SDNode *Elt = N->getOperand(1).getNode();
8769   if (VT.getVectorElementType() != MVT::i64 ||
8770       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8771     return SDValue();
8772
8773   SelectionDAG &DAG = DCI.DAG;
8774   SDLoc dl(N);
8775   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8776                                  VT.getVectorNumElements());
8777   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8778   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8779   // Make the DAGCombiner fold the bitcasts.
8780   DCI.AddToWorklist(Vec.getNode());
8781   DCI.AddToWorklist(V.getNode());
8782   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8783                                Vec, V, N->getOperand(2));
8784   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8785 }
8786
8787 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8788 /// ISD::VECTOR_SHUFFLE.
8789 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8790   // The LLVM shufflevector instruction does not require the shuffle mask
8791   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8792   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
8793   // operands do not match the mask length, they are extended by concatenating
8794   // them with undef vectors.  That is probably the right thing for other
8795   // targets, but for NEON it is better to concatenate two double-register
8796   // size vector operands into a single quad-register size vector.  Do that
8797   // transformation here:
8798   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
8799   //   shuffle(concat(v1, v2), undef)
8800   SDValue Op0 = N->getOperand(0);
8801   SDValue Op1 = N->getOperand(1);
8802   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8803       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8804       Op0.getNumOperands() != 2 ||
8805       Op1.getNumOperands() != 2)
8806     return SDValue();
8807   SDValue Concat0Op1 = Op0.getOperand(1);
8808   SDValue Concat1Op1 = Op1.getOperand(1);
8809   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8810       Concat1Op1.getOpcode() != ISD::UNDEF)
8811     return SDValue();
8812   // Skip the transformation if any of the types are illegal.
8813   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8814   EVT VT = N->getValueType(0);
8815   if (!TLI.isTypeLegal(VT) ||
8816       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8817       !TLI.isTypeLegal(Concat1Op1.getValueType()))
8818     return SDValue();
8819
8820   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
8821                                   Op0.getOperand(0), Op1.getOperand(0));
8822   // Translate the shuffle mask.
8823   SmallVector<int, 16> NewMask;
8824   unsigned NumElts = VT.getVectorNumElements();
8825   unsigned HalfElts = NumElts/2;
8826   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8827   for (unsigned n = 0; n < NumElts; ++n) {
8828     int MaskElt = SVN->getMaskElt(n);
8829     int NewElt = -1;
8830     if (MaskElt < (int)HalfElts)
8831       NewElt = MaskElt;
8832     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8833       NewElt = HalfElts + MaskElt - NumElts;
8834     NewMask.push_back(NewElt);
8835   }
8836   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
8837                               DAG.getUNDEF(VT), NewMask.data());
8838 }
8839
8840 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
8841 /// NEON load/store intrinsics, and generic vector load/stores, to merge
8842 /// base address updates.
8843 /// For generic load/stores, the memory type is assumed to be a vector.
8844 /// The caller is assumed to have checked legality.
8845 static SDValue CombineBaseUpdate(SDNode *N,
8846                                  TargetLowering::DAGCombinerInfo &DCI) {
8847   SelectionDAG &DAG = DCI.DAG;
8848   const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8849                             N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8850   const bool isStore = N->getOpcode() == ISD::STORE;
8851   const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
8852   SDValue Addr = N->getOperand(AddrOpIdx);
8853   MemSDNode *MemN = cast<MemSDNode>(N);
8854   SDLoc dl(N);
8855
8856   // Search for a use of the address operand that is an increment.
8857   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8858          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8859     SDNode *User = *UI;
8860     if (User->getOpcode() != ISD::ADD ||
8861         UI.getUse().getResNo() != Addr.getResNo())
8862       continue;
8863
8864     // Check that the add is independent of the load/store.  Otherwise, folding
8865     // it would create a cycle.
8866     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8867       continue;
8868
8869     // Find the new opcode for the updating load/store.
8870     bool isLoadOp = true;
8871     bool isLaneOp = false;
8872     unsigned NewOpc = 0;
8873     unsigned NumVecs = 0;
8874     if (isIntrinsic) {
8875       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8876       switch (IntNo) {
8877       default: llvm_unreachable("unexpected intrinsic for Neon base update");
8878       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
8879         NumVecs = 1; break;
8880       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
8881         NumVecs = 2; break;
8882       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
8883         NumVecs = 3; break;
8884       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
8885         NumVecs = 4; break;
8886       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8887         NumVecs = 2; isLaneOp = true; break;
8888       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8889         NumVecs = 3; isLaneOp = true; break;
8890       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8891         NumVecs = 4; isLaneOp = true; break;
8892       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
8893         NumVecs = 1; isLoadOp = false; break;
8894       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
8895         NumVecs = 2; isLoadOp = false; break;
8896       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
8897         NumVecs = 3; isLoadOp = false; break;
8898       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
8899         NumVecs = 4; isLoadOp = false; break;
8900       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8901         NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
8902       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8903         NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
8904       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8905         NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
8906       }
8907     } else {
8908       isLaneOp = true;
8909       switch (N->getOpcode()) {
8910       default: llvm_unreachable("unexpected opcode for Neon base update");
8911       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8912       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8913       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8914       case ISD::LOAD:       NewOpc = ARMISD::VLD1_UPD;
8915         NumVecs = 1; isLaneOp = false; break;
8916       case ISD::STORE:      NewOpc = ARMISD::VST1_UPD;
8917         NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
8918       }
8919     }
8920
8921     // Find the size of memory referenced by the load/store.
8922     EVT VecTy;
8923     if (isLoadOp) {
8924       VecTy = N->getValueType(0);
8925     } else if (isIntrinsic) {
8926       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8927     } else {
8928       assert(isStore && "Node has to be a load, a store, or an intrinsic!");
8929       VecTy = N->getOperand(1).getValueType();
8930     }
8931
8932     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8933     if (isLaneOp)
8934       NumBytes /= VecTy.getVectorNumElements();
8935
8936     // If the increment is a constant, it must match the memory ref size.
8937     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8938     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8939       uint64_t IncVal = CInc->getZExtValue();
8940       if (IncVal != NumBytes)
8941         continue;
8942     } else if (NumBytes >= 3 * 16) {
8943       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8944       // separate instructions that make it harder to use a non-constant update.
8945       continue;
8946     }
8947
8948     // OK, we found an ADD we can fold into the base update.
8949     // Now, create a _UPD node, taking care of not breaking alignment.
8950
8951     EVT AlignedVecTy = VecTy;
8952     unsigned Alignment = MemN->getAlignment();
8953
8954     // If this is a less-than-standard-aligned load/store, change the type to
8955     // match the standard alignment.
8956     // The alignment is overlooked when selecting _UPD variants; and it's
8957     // easier to introduce bitcasts here than fix that.
8958     // There are 3 ways to get to this base-update combine:
8959     // - intrinsics: they are assumed to be properly aligned (to the standard
8960     //   alignment of the memory type), so we don't need to do anything.
8961     // - ARMISD::VLDx nodes: they are only generated from the aforementioned
8962     //   intrinsics, so, likewise, there's nothing to do.
8963     // - generic load/store instructions: the alignment is specified as an
8964     //   explicit operand, rather than implicitly as the standard alignment
8965     //   of the memory type (like the intrisics).  We need to change the
8966     //   memory type to match the explicit alignment.  That way, we don't
8967     //   generate non-standard-aligned ARMISD::VLDx nodes.
8968     if (isa<LSBaseSDNode>(N)) {
8969       if (Alignment == 0)
8970         Alignment = 1;
8971       if (Alignment < VecTy.getScalarSizeInBits() / 8) {
8972         MVT EltTy = MVT::getIntegerVT(Alignment * 8);
8973         assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
8974         assert(!isLaneOp && "Unexpected generic load/store lane.");
8975         unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
8976         AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
8977       }
8978       // Don't set an explicit alignment on regular load/stores that we want
8979       // to transform to VLD/VST 1_UPD nodes.
8980       // This matches the behavior of regular load/stores, which only get an
8981       // explicit alignment if the MMO alignment is larger than the standard
8982       // alignment of the memory type.
8983       // Intrinsics, however, always get an explicit alignment, set to the
8984       // alignment of the MMO.
8985       Alignment = 1;
8986     }
8987
8988     // Create the new updating load/store node.
8989     // First, create an SDVTList for the new updating node's results.
8990     EVT Tys[6];
8991     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
8992     unsigned n;
8993     for (n = 0; n < NumResultVecs; ++n)
8994       Tys[n] = AlignedVecTy;
8995     Tys[n++] = MVT::i32;
8996     Tys[n] = MVT::Other;
8997     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
8998
8999     // Then, gather the new node's operands.
9000     SmallVector<SDValue, 8> Ops;
9001     Ops.push_back(N->getOperand(0)); // incoming chain
9002     Ops.push_back(N->getOperand(AddrOpIdx));
9003     Ops.push_back(Inc);
9004
9005     if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
9006       // Try to match the intrinsic's signature
9007       Ops.push_back(StN->getValue());
9008     } else {
9009       // Loads (and of course intrinsics) match the intrinsics' signature,
9010       // so just add all but the alignment operand.
9011       for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
9012         Ops.push_back(N->getOperand(i));
9013     }
9014
9015     // For all node types, the alignment operand is always the last one.
9016     Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
9017
9018     // If this is a non-standard-aligned STORE, the penultimate operand is the
9019     // stored value.  Bitcast it to the aligned type.
9020     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
9021       SDValue &StVal = Ops[Ops.size()-2];
9022       StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
9023     }
9024
9025     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys,
9026                                            Ops, AlignedVecTy,
9027                                            MemN->getMemOperand());
9028
9029     // Update the uses.
9030     SmallVector<SDValue, 5> NewResults;
9031     for (unsigned i = 0; i < NumResultVecs; ++i)
9032       NewResults.push_back(SDValue(UpdN.getNode(), i));
9033
9034     // If this is an non-standard-aligned LOAD, the first result is the loaded
9035     // value.  Bitcast it to the expected result type.
9036     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
9037       SDValue &LdVal = NewResults[0];
9038       LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
9039     }
9040
9041     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9042     DCI.CombineTo(N, NewResults);
9043     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9044
9045     break;
9046   }
9047   return SDValue();
9048 }
9049
9050 static SDValue PerformVLDCombine(SDNode *N,
9051                                  TargetLowering::DAGCombinerInfo &DCI) {
9052   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9053     return SDValue();
9054
9055   return CombineBaseUpdate(N, DCI);
9056 }
9057
9058 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9059 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9060 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
9061 /// return true.
9062 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9063   SelectionDAG &DAG = DCI.DAG;
9064   EVT VT = N->getValueType(0);
9065   // vldN-dup instructions only support 64-bit vectors for N > 1.
9066   if (!VT.is64BitVector())
9067     return false;
9068
9069   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9070   SDNode *VLD = N->getOperand(0).getNode();
9071   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9072     return false;
9073   unsigned NumVecs = 0;
9074   unsigned NewOpc = 0;
9075   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9076   if (IntNo == Intrinsic::arm_neon_vld2lane) {
9077     NumVecs = 2;
9078     NewOpc = ARMISD::VLD2DUP;
9079   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9080     NumVecs = 3;
9081     NewOpc = ARMISD::VLD3DUP;
9082   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9083     NumVecs = 4;
9084     NewOpc = ARMISD::VLD4DUP;
9085   } else {
9086     return false;
9087   }
9088
9089   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9090   // numbers match the load.
9091   unsigned VLDLaneNo =
9092     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9093   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9094        UI != UE; ++UI) {
9095     // Ignore uses of the chain result.
9096     if (UI.getUse().getResNo() == NumVecs)
9097       continue;
9098     SDNode *User = *UI;
9099     if (User->getOpcode() != ARMISD::VDUPLANE ||
9100         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9101       return false;
9102   }
9103
9104   // Create the vldN-dup node.
9105   EVT Tys[5];
9106   unsigned n;
9107   for (n = 0; n < NumVecs; ++n)
9108     Tys[n] = VT;
9109   Tys[n] = MVT::Other;
9110   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9111   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9112   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9113   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9114                                            Ops, VLDMemInt->getMemoryVT(),
9115                                            VLDMemInt->getMemOperand());
9116
9117   // Update the uses.
9118   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9119        UI != UE; ++UI) {
9120     unsigned ResNo = UI.getUse().getResNo();
9121     // Ignore uses of the chain result.
9122     if (ResNo == NumVecs)
9123       continue;
9124     SDNode *User = *UI;
9125     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9126   }
9127
9128   // Now the vldN-lane intrinsic is dead except for its chain result.
9129   // Update uses of the chain.
9130   std::vector<SDValue> VLDDupResults;
9131   for (unsigned n = 0; n < NumVecs; ++n)
9132     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9133   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9134   DCI.CombineTo(VLD, VLDDupResults);
9135
9136   return true;
9137 }
9138
9139 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9140 /// ARMISD::VDUPLANE.
9141 static SDValue PerformVDUPLANECombine(SDNode *N,
9142                                       TargetLowering::DAGCombinerInfo &DCI) {
9143   SDValue Op = N->getOperand(0);
9144
9145   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9146   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9147   if (CombineVLDDUP(N, DCI))
9148     return SDValue(N, 0);
9149
9150   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9151   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9152   while (Op.getOpcode() == ISD::BITCAST)
9153     Op = Op.getOperand(0);
9154   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9155     return SDValue();
9156
9157   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9158   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9159   // The canonical VMOV for a zero vector uses a 32-bit element size.
9160   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9161   unsigned EltBits;
9162   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9163     EltSize = 8;
9164   EVT VT = N->getValueType(0);
9165   if (EltSize > VT.getVectorElementType().getSizeInBits())
9166     return SDValue();
9167
9168   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9169 }
9170
9171 static SDValue PerformLOADCombine(SDNode *N,
9172                                   TargetLowering::DAGCombinerInfo &DCI) {
9173   EVT VT = N->getValueType(0);
9174
9175   // If this is a legal vector load, try to combine it into a VLD1_UPD.
9176   if (ISD::isNormalLoad(N) && VT.isVector() &&
9177       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9178     return CombineBaseUpdate(N, DCI);
9179
9180   return SDValue();
9181 }
9182
9183 /// PerformSTORECombine - Target-specific dag combine xforms for
9184 /// ISD::STORE.
9185 static SDValue PerformSTORECombine(SDNode *N,
9186                                    TargetLowering::DAGCombinerInfo &DCI) {
9187   StoreSDNode *St = cast<StoreSDNode>(N);
9188   if (St->isVolatile())
9189     return SDValue();
9190
9191   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
9192   // pack all of the elements in one place.  Next, store to memory in fewer
9193   // chunks.
9194   SDValue StVal = St->getValue();
9195   EVT VT = StVal.getValueType();
9196   if (St->isTruncatingStore() && VT.isVector()) {
9197     SelectionDAG &DAG = DCI.DAG;
9198     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9199     EVT StVT = St->getMemoryVT();
9200     unsigned NumElems = VT.getVectorNumElements();
9201     assert(StVT != VT && "Cannot truncate to the same type");
9202     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
9203     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
9204
9205     // From, To sizes and ElemCount must be pow of two
9206     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
9207
9208     // We are going to use the original vector elt for storing.
9209     // Accumulated smaller vector elements must be a multiple of the store size.
9210     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
9211
9212     unsigned SizeRatio  = FromEltSz / ToEltSz;
9213     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
9214
9215     // Create a type on which we perform the shuffle.
9216     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9217                                      NumElems*SizeRatio);
9218     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9219
9220     SDLoc DL(St);
9221     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9222     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9223     for (unsigned i = 0; i < NumElems; ++i)
9224       ShuffleVec[i] = TLI.isBigEndian() ? (i+1) * SizeRatio - 1 : i * SizeRatio;
9225
9226     // Can't shuffle using an illegal type.
9227     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9228
9229     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9230                                 DAG.getUNDEF(WideVec.getValueType()),
9231                                 ShuffleVec.data());
9232     // At this point all of the data is stored at the bottom of the
9233     // register. We now need to save it to mem.
9234
9235     // Find the largest store unit
9236     MVT StoreType = MVT::i8;
9237     for (MVT Tp : MVT::integer_valuetypes()) {
9238       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9239         StoreType = Tp;
9240     }
9241     // Didn't find a legal store type.
9242     if (!TLI.isTypeLegal(StoreType))
9243       return SDValue();
9244
9245     // Bitcast the original vector into a vector of store-size units
9246     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9247             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9248     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9249     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9250     SmallVector<SDValue, 8> Chains;
9251     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8, DL,
9252                                         TLI.getPointerTy());
9253     SDValue BasePtr = St->getBasePtr();
9254
9255     // Perform one or more big stores into memory.
9256     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9257     for (unsigned I = 0; I < E; I++) {
9258       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9259                                    StoreType, ShuffWide,
9260                                    DAG.getIntPtrConstant(I, DL));
9261       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9262                                 St->getPointerInfo(), St->isVolatile(),
9263                                 St->isNonTemporal(), St->getAlignment());
9264       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9265                             Increment);
9266       Chains.push_back(Ch);
9267     }
9268     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
9269   }
9270
9271   if (!ISD::isNormalStore(St))
9272     return SDValue();
9273
9274   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9275   // ARM stores of arguments in the same cache line.
9276   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9277       StVal.getNode()->hasOneUse()) {
9278     SelectionDAG  &DAG = DCI.DAG;
9279     bool isBigEndian = DAG.getTargetLoweringInfo().isBigEndian();
9280     SDLoc DL(St);
9281     SDValue BasePtr = St->getBasePtr();
9282     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9283                                   StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
9284                                   BasePtr, St->getPointerInfo(), St->isVolatile(),
9285                                   St->isNonTemporal(), St->getAlignment());
9286
9287     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9288                                     DAG.getConstant(4, DL, MVT::i32));
9289     return DAG.getStore(NewST1.getValue(0), DL,
9290                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
9291                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9292                         St->isNonTemporal(),
9293                         std::min(4U, St->getAlignment() / 2));
9294   }
9295
9296   if (StVal.getValueType() == MVT::i64 &&
9297       StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9298
9299     // Bitcast an i64 store extracted from a vector to f64.
9300     // Otherwise, the i64 value will be legalized to a pair of i32 values.
9301     SelectionDAG &DAG = DCI.DAG;
9302     SDLoc dl(StVal);
9303     SDValue IntVec = StVal.getOperand(0);
9304     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9305                                    IntVec.getValueType().getVectorNumElements());
9306     SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9307     SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9308                                  Vec, StVal.getOperand(1));
9309     dl = SDLoc(N);
9310     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9311     // Make the DAGCombiner fold the bitcasts.
9312     DCI.AddToWorklist(Vec.getNode());
9313     DCI.AddToWorklist(ExtElt.getNode());
9314     DCI.AddToWorklist(V.getNode());
9315     return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9316                         St->getPointerInfo(), St->isVolatile(),
9317                         St->isNonTemporal(), St->getAlignment(),
9318                         St->getAAInfo());
9319   }
9320
9321   // If this is a legal vector store, try to combine it into a VST1_UPD.
9322   if (ISD::isNormalStore(N) && VT.isVector() &&
9323       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9324     return CombineBaseUpdate(N, DCI);
9325
9326   return SDValue();
9327 }
9328
9329 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9330 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9331 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9332 {
9333   integerPart cN;
9334   integerPart c0 = 0;
9335   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9336        I != E; I++) {
9337     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9338     if (!C)
9339       return false;
9340
9341     bool isExact;
9342     APFloat APF = C->getValueAPF();
9343     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9344         != APFloat::opOK || !isExact)
9345       return false;
9346
9347     c0 = (I == 0) ? cN : c0;
9348     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9349       return false;
9350   }
9351   C = c0;
9352   return true;
9353 }
9354
9355 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9356 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9357 /// when the VMUL has a constant operand that is a power of 2.
9358 ///
9359 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9360 ///  vmul.f32        d16, d17, d16
9361 ///  vcvt.s32.f32    d16, d16
9362 /// becomes:
9363 ///  vcvt.s32.f32    d16, d16, #3
9364 static SDValue PerformVCVTCombine(SDNode *N,
9365                                   TargetLowering::DAGCombinerInfo &DCI,
9366                                   const ARMSubtarget *Subtarget) {
9367   SelectionDAG &DAG = DCI.DAG;
9368   SDValue Op = N->getOperand(0);
9369
9370   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9371       Op.getOpcode() != ISD::FMUL)
9372     return SDValue();
9373
9374   uint64_t C;
9375   SDValue N0 = Op->getOperand(0);
9376   SDValue ConstVec = Op->getOperand(1);
9377   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9378
9379   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9380       !isConstVecPow2(ConstVec, isSigned, C))
9381     return SDValue();
9382
9383   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9384   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9385   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9386   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32 ||
9387       NumLanes > 4) {
9388     // These instructions only exist converting from f32 to i32. We can handle
9389     // smaller integers by generating an extra truncate, but larger ones would
9390     // be lossy. We also can't handle more then 4 lanes, since these intructions
9391     // only support v2i32/v4i32 types.
9392     return SDValue();
9393   }
9394
9395   SDLoc dl(N);
9396   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9397     Intrinsic::arm_neon_vcvtfp2fxu;
9398   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9399                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9400                                  DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9401                                  N0,
9402                                  DAG.getConstant(Log2_64(C), dl, MVT::i32));
9403
9404   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9405     FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
9406
9407   return FixConv;
9408 }
9409
9410 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9411 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9412 /// when the VDIV has a constant operand that is a power of 2.
9413 ///
9414 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9415 ///  vcvt.f32.s32    d16, d16
9416 ///  vdiv.f32        d16, d17, d16
9417 /// becomes:
9418 ///  vcvt.f32.s32    d16, d16, #3
9419 static SDValue PerformVDIVCombine(SDNode *N,
9420                                   TargetLowering::DAGCombinerInfo &DCI,
9421                                   const ARMSubtarget *Subtarget) {
9422   SelectionDAG &DAG = DCI.DAG;
9423   SDValue Op = N->getOperand(0);
9424   unsigned OpOpcode = Op.getNode()->getOpcode();
9425
9426   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9427       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9428     return SDValue();
9429
9430   uint64_t C;
9431   SDValue ConstVec = N->getOperand(1);
9432   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9433
9434   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9435       !isConstVecPow2(ConstVec, isSigned, C))
9436     return SDValue();
9437
9438   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9439   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9440   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9441     // These instructions only exist converting from i32 to f32. We can handle
9442     // smaller integers by generating an extra extend, but larger ones would
9443     // be lossy.
9444     return SDValue();
9445   }
9446
9447   SDLoc dl(N);
9448   SDValue ConvInput = Op.getOperand(0);
9449   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9450   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9451     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9452                             dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9453                             ConvInput);
9454
9455   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9456     Intrinsic::arm_neon_vcvtfxu2fp;
9457   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9458                      Op.getValueType(),
9459                      DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9460                      ConvInput, DAG.getConstant(Log2_64(C), dl, MVT::i32));
9461 }
9462
9463 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9464 /// operand of a vector shift operation, where all the elements of the
9465 /// build_vector must have the same constant integer value.
9466 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9467   // Ignore bit_converts.
9468   while (Op.getOpcode() == ISD::BITCAST)
9469     Op = Op.getOperand(0);
9470   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9471   APInt SplatBits, SplatUndef;
9472   unsigned SplatBitSize;
9473   bool HasAnyUndefs;
9474   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9475                                       HasAnyUndefs, ElementBits) ||
9476       SplatBitSize > ElementBits)
9477     return false;
9478   Cnt = SplatBits.getSExtValue();
9479   return true;
9480 }
9481
9482 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9483 /// operand of a vector shift left operation.  That value must be in the range:
9484 ///   0 <= Value < ElementBits for a left shift; or
9485 ///   0 <= Value <= ElementBits for a long left shift.
9486 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9487   assert(VT.isVector() && "vector shift count is not a vector type");
9488   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9489   if (! getVShiftImm(Op, ElementBits, Cnt))
9490     return false;
9491   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9492 }
9493
9494 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9495 /// operand of a vector shift right operation.  For a shift opcode, the value
9496 /// is positive, but for an intrinsic the value count must be negative. The
9497 /// absolute value must be in the range:
9498 ///   1 <= |Value| <= ElementBits for a right shift; or
9499 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9500 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9501                          int64_t &Cnt) {
9502   assert(VT.isVector() && "vector shift count is not a vector type");
9503   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9504   if (! getVShiftImm(Op, ElementBits, Cnt))
9505     return false;
9506   if (isIntrinsic)
9507     Cnt = -Cnt;
9508   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9509 }
9510
9511 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9512 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9513   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9514   switch (IntNo) {
9515   default:
9516     // Don't do anything for most intrinsics.
9517     break;
9518
9519   // Vector shifts: check for immediate versions and lower them.
9520   // Note: This is done during DAG combining instead of DAG legalizing because
9521   // the build_vectors for 64-bit vector element shift counts are generally
9522   // not legal, and it is hard to see their values after they get legalized to
9523   // loads from a constant pool.
9524   case Intrinsic::arm_neon_vshifts:
9525   case Intrinsic::arm_neon_vshiftu:
9526   case Intrinsic::arm_neon_vrshifts:
9527   case Intrinsic::arm_neon_vrshiftu:
9528   case Intrinsic::arm_neon_vrshiftn:
9529   case Intrinsic::arm_neon_vqshifts:
9530   case Intrinsic::arm_neon_vqshiftu:
9531   case Intrinsic::arm_neon_vqshiftsu:
9532   case Intrinsic::arm_neon_vqshiftns:
9533   case Intrinsic::arm_neon_vqshiftnu:
9534   case Intrinsic::arm_neon_vqshiftnsu:
9535   case Intrinsic::arm_neon_vqrshiftns:
9536   case Intrinsic::arm_neon_vqrshiftnu:
9537   case Intrinsic::arm_neon_vqrshiftnsu: {
9538     EVT VT = N->getOperand(1).getValueType();
9539     int64_t Cnt;
9540     unsigned VShiftOpc = 0;
9541
9542     switch (IntNo) {
9543     case Intrinsic::arm_neon_vshifts:
9544     case Intrinsic::arm_neon_vshiftu:
9545       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9546         VShiftOpc = ARMISD::VSHL;
9547         break;
9548       }
9549       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9550         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9551                      ARMISD::VSHRs : ARMISD::VSHRu);
9552         break;
9553       }
9554       return SDValue();
9555
9556     case Intrinsic::arm_neon_vrshifts:
9557     case Intrinsic::arm_neon_vrshiftu:
9558       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9559         break;
9560       return SDValue();
9561
9562     case Intrinsic::arm_neon_vqshifts:
9563     case Intrinsic::arm_neon_vqshiftu:
9564       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9565         break;
9566       return SDValue();
9567
9568     case Intrinsic::arm_neon_vqshiftsu:
9569       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9570         break;
9571       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9572
9573     case Intrinsic::arm_neon_vrshiftn:
9574     case Intrinsic::arm_neon_vqshiftns:
9575     case Intrinsic::arm_neon_vqshiftnu:
9576     case Intrinsic::arm_neon_vqshiftnsu:
9577     case Intrinsic::arm_neon_vqrshiftns:
9578     case Intrinsic::arm_neon_vqrshiftnu:
9579     case Intrinsic::arm_neon_vqrshiftnsu:
9580       // Narrowing shifts require an immediate right shift.
9581       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9582         break;
9583       llvm_unreachable("invalid shift count for narrowing vector shift "
9584                        "intrinsic");
9585
9586     default:
9587       llvm_unreachable("unhandled vector shift");
9588     }
9589
9590     switch (IntNo) {
9591     case Intrinsic::arm_neon_vshifts:
9592     case Intrinsic::arm_neon_vshiftu:
9593       // Opcode already set above.
9594       break;
9595     case Intrinsic::arm_neon_vrshifts:
9596       VShiftOpc = ARMISD::VRSHRs; break;
9597     case Intrinsic::arm_neon_vrshiftu:
9598       VShiftOpc = ARMISD::VRSHRu; break;
9599     case Intrinsic::arm_neon_vrshiftn:
9600       VShiftOpc = ARMISD::VRSHRN; break;
9601     case Intrinsic::arm_neon_vqshifts:
9602       VShiftOpc = ARMISD::VQSHLs; break;
9603     case Intrinsic::arm_neon_vqshiftu:
9604       VShiftOpc = ARMISD::VQSHLu; break;
9605     case Intrinsic::arm_neon_vqshiftsu:
9606       VShiftOpc = ARMISD::VQSHLsu; break;
9607     case Intrinsic::arm_neon_vqshiftns:
9608       VShiftOpc = ARMISD::VQSHRNs; break;
9609     case Intrinsic::arm_neon_vqshiftnu:
9610       VShiftOpc = ARMISD::VQSHRNu; break;
9611     case Intrinsic::arm_neon_vqshiftnsu:
9612       VShiftOpc = ARMISD::VQSHRNsu; break;
9613     case Intrinsic::arm_neon_vqrshiftns:
9614       VShiftOpc = ARMISD::VQRSHRNs; break;
9615     case Intrinsic::arm_neon_vqrshiftnu:
9616       VShiftOpc = ARMISD::VQRSHRNu; break;
9617     case Intrinsic::arm_neon_vqrshiftnsu:
9618       VShiftOpc = ARMISD::VQRSHRNsu; break;
9619     }
9620
9621     SDLoc dl(N);
9622     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
9623                        N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
9624   }
9625
9626   case Intrinsic::arm_neon_vshiftins: {
9627     EVT VT = N->getOperand(1).getValueType();
9628     int64_t Cnt;
9629     unsigned VShiftOpc = 0;
9630
9631     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9632       VShiftOpc = ARMISD::VSLI;
9633     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9634       VShiftOpc = ARMISD::VSRI;
9635     else {
9636       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9637     }
9638
9639     SDLoc dl(N);
9640     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
9641                        N->getOperand(1), N->getOperand(2),
9642                        DAG.getConstant(Cnt, dl, MVT::i32));
9643   }
9644
9645   case Intrinsic::arm_neon_vqrshifts:
9646   case Intrinsic::arm_neon_vqrshiftu:
9647     // No immediate versions of these to check for.
9648     break;
9649   }
9650
9651   return SDValue();
9652 }
9653
9654 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9655 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9656 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9657 /// vector element shift counts are generally not legal, and it is hard to see
9658 /// their values after they get legalized to loads from a constant pool.
9659 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9660                                    const ARMSubtarget *ST) {
9661   EVT VT = N->getValueType(0);
9662   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9663     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9664     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9665     SDValue N1 = N->getOperand(1);
9666     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9667       SDValue N0 = N->getOperand(0);
9668       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9669           DAG.MaskedValueIsZero(N0.getOperand(0),
9670                                 APInt::getHighBitsSet(32, 16)))
9671         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9672     }
9673   }
9674
9675   // Nothing to be done for scalar shifts.
9676   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9677   if (!VT.isVector() || !TLI.isTypeLegal(VT))
9678     return SDValue();
9679
9680   assert(ST->hasNEON() && "unexpected vector shift");
9681   int64_t Cnt;
9682
9683   switch (N->getOpcode()) {
9684   default: llvm_unreachable("unexpected shift opcode");
9685
9686   case ISD::SHL:
9687     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
9688       SDLoc dl(N);
9689       return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
9690                          DAG.getConstant(Cnt, dl, MVT::i32));
9691     }
9692     break;
9693
9694   case ISD::SRA:
9695   case ISD::SRL:
9696     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9697       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9698                             ARMISD::VSHRs : ARMISD::VSHRu);
9699       SDLoc dl(N);
9700       return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
9701                          DAG.getConstant(Cnt, dl, MVT::i32));
9702     }
9703   }
9704   return SDValue();
9705 }
9706
9707 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9708 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9709 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9710                                     const ARMSubtarget *ST) {
9711   SDValue N0 = N->getOperand(0);
9712
9713   // Check for sign- and zero-extensions of vector extract operations of 8-
9714   // and 16-bit vector elements.  NEON supports these directly.  They are
9715   // handled during DAG combining because type legalization will promote them
9716   // to 32-bit types and it is messy to recognize the operations after that.
9717   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9718     SDValue Vec = N0.getOperand(0);
9719     SDValue Lane = N0.getOperand(1);
9720     EVT VT = N->getValueType(0);
9721     EVT EltVT = N0.getValueType();
9722     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9723
9724     if (VT == MVT::i32 &&
9725         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9726         TLI.isTypeLegal(Vec.getValueType()) &&
9727         isa<ConstantSDNode>(Lane)) {
9728
9729       unsigned Opc = 0;
9730       switch (N->getOpcode()) {
9731       default: llvm_unreachable("unexpected opcode");
9732       case ISD::SIGN_EXTEND:
9733         Opc = ARMISD::VGETLANEs;
9734         break;
9735       case ISD::ZERO_EXTEND:
9736       case ISD::ANY_EXTEND:
9737         Opc = ARMISD::VGETLANEu;
9738         break;
9739       }
9740       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9741     }
9742   }
9743
9744   return SDValue();
9745 }
9746
9747 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9748 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9749 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9750                                        const ARMSubtarget *ST) {
9751   // If the target supports NEON, try to use vmax/vmin instructions for f32
9752   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
9753   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
9754   // a NaN; only do the transformation when it matches that behavior.
9755
9756   // For now only do this when using NEON for FP operations; if using VFP, it
9757   // is not obvious that the benefit outweighs the cost of switching to the
9758   // NEON pipeline.
9759   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9760       N->getValueType(0) != MVT::f32)
9761     return SDValue();
9762
9763   SDValue CondLHS = N->getOperand(0);
9764   SDValue CondRHS = N->getOperand(1);
9765   SDValue LHS = N->getOperand(2);
9766   SDValue RHS = N->getOperand(3);
9767   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9768
9769   unsigned Opcode = 0;
9770   bool IsReversed;
9771   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9772     IsReversed = false; // x CC y ? x : y
9773   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9774     IsReversed = true ; // x CC y ? y : x
9775   } else {
9776     return SDValue();
9777   }
9778
9779   bool IsUnordered;
9780   switch (CC) {
9781   default: break;
9782   case ISD::SETOLT:
9783   case ISD::SETOLE:
9784   case ISD::SETLT:
9785   case ISD::SETLE:
9786   case ISD::SETULT:
9787   case ISD::SETULE:
9788     // If LHS is NaN, an ordered comparison will be false and the result will
9789     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
9790     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9791     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9792     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9793       break;
9794     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9795     // will return -0, so vmin can only be used for unsafe math or if one of
9796     // the operands is known to be nonzero.
9797     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9798         !DAG.getTarget().Options.UnsafeFPMath &&
9799         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9800       break;
9801     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9802     break;
9803
9804   case ISD::SETOGT:
9805   case ISD::SETOGE:
9806   case ISD::SETGT:
9807   case ISD::SETGE:
9808   case ISD::SETUGT:
9809   case ISD::SETUGE:
9810     // If LHS is NaN, an ordered comparison will be false and the result will
9811     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
9812     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9813     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9814     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9815       break;
9816     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9817     // will return +0, so vmax can only be used for unsafe math or if one of
9818     // the operands is known to be nonzero.
9819     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9820         !DAG.getTarget().Options.UnsafeFPMath &&
9821         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9822       break;
9823     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9824     break;
9825   }
9826
9827   if (!Opcode)
9828     return SDValue();
9829   return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9830 }
9831
9832 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9833 SDValue
9834 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9835   SDValue Cmp = N->getOperand(4);
9836   if (Cmp.getOpcode() != ARMISD::CMPZ)
9837     // Only looking at EQ and NE cases.
9838     return SDValue();
9839
9840   EVT VT = N->getValueType(0);
9841   SDLoc dl(N);
9842   SDValue LHS = Cmp.getOperand(0);
9843   SDValue RHS = Cmp.getOperand(1);
9844   SDValue FalseVal = N->getOperand(0);
9845   SDValue TrueVal = N->getOperand(1);
9846   SDValue ARMcc = N->getOperand(2);
9847   ARMCC::CondCodes CC =
9848     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9849
9850   // Simplify
9851   //   mov     r1, r0
9852   //   cmp     r1, x
9853   //   mov     r0, y
9854   //   moveq   r0, x
9855   // to
9856   //   cmp     r0, x
9857   //   movne   r0, y
9858   //
9859   //   mov     r1, r0
9860   //   cmp     r1, x
9861   //   mov     r0, x
9862   //   movne   r0, y
9863   // to
9864   //   cmp     r0, x
9865   //   movne   r0, y
9866   /// FIXME: Turn this into a target neutral optimization?
9867   SDValue Res;
9868   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9869     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9870                       N->getOperand(3), Cmp);
9871   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9872     SDValue ARMcc;
9873     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9874     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9875                       N->getOperand(3), NewCmp);
9876   }
9877
9878   if (Res.getNode()) {
9879     APInt KnownZero, KnownOne;
9880     DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
9881     // Capture demanded bits information that would be otherwise lost.
9882     if (KnownZero == 0xfffffffe)
9883       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9884                         DAG.getValueType(MVT::i1));
9885     else if (KnownZero == 0xffffff00)
9886       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9887                         DAG.getValueType(MVT::i8));
9888     else if (KnownZero == 0xffff0000)
9889       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9890                         DAG.getValueType(MVT::i16));
9891   }
9892
9893   return Res;
9894 }
9895
9896 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9897                                              DAGCombinerInfo &DCI) const {
9898   switch (N->getOpcode()) {
9899   default: break;
9900   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
9901   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
9902   case ISD::SUB:        return PerformSUBCombine(N, DCI);
9903   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
9904   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
9905   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
9906   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
9907   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
9908   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
9909   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9910   case ISD::STORE:      return PerformSTORECombine(N, DCI);
9911   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
9912   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9913   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9914   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9915   case ISD::FP_TO_SINT:
9916   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9917   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
9918   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9919   case ISD::SHL:
9920   case ISD::SRA:
9921   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
9922   case ISD::SIGN_EXTEND:
9923   case ISD::ZERO_EXTEND:
9924   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9925   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9926   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9927   case ISD::LOAD:       return PerformLOADCombine(N, DCI);
9928   case ARMISD::VLD2DUP:
9929   case ARMISD::VLD3DUP:
9930   case ARMISD::VLD4DUP:
9931     return PerformVLDCombine(N, DCI);
9932   case ARMISD::BUILD_VECTOR:
9933     return PerformARMBUILD_VECTORCombine(N, DCI);
9934   case ISD::INTRINSIC_VOID:
9935   case ISD::INTRINSIC_W_CHAIN:
9936     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9937     case Intrinsic::arm_neon_vld1:
9938     case Intrinsic::arm_neon_vld2:
9939     case Intrinsic::arm_neon_vld3:
9940     case Intrinsic::arm_neon_vld4:
9941     case Intrinsic::arm_neon_vld2lane:
9942     case Intrinsic::arm_neon_vld3lane:
9943     case Intrinsic::arm_neon_vld4lane:
9944     case Intrinsic::arm_neon_vst1:
9945     case Intrinsic::arm_neon_vst2:
9946     case Intrinsic::arm_neon_vst3:
9947     case Intrinsic::arm_neon_vst4:
9948     case Intrinsic::arm_neon_vst2lane:
9949     case Intrinsic::arm_neon_vst3lane:
9950     case Intrinsic::arm_neon_vst4lane:
9951       return PerformVLDCombine(N, DCI);
9952     default: break;
9953     }
9954     break;
9955   }
9956   return SDValue();
9957 }
9958
9959 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9960                                                           EVT VT) const {
9961   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9962 }
9963
9964 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
9965                                                        unsigned,
9966                                                        unsigned,
9967                                                        bool *Fast) const {
9968   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9969   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9970
9971   switch (VT.getSimpleVT().SimpleTy) {
9972   default:
9973     return false;
9974   case MVT::i8:
9975   case MVT::i16:
9976   case MVT::i32: {
9977     // Unaligned access can use (for example) LRDB, LRDH, LDR
9978     if (AllowsUnaligned) {
9979       if (Fast)
9980         *Fast = Subtarget->hasV7Ops();
9981       return true;
9982     }
9983     return false;
9984   }
9985   case MVT::f64:
9986   case MVT::v2f64: {
9987     // For any little-endian targets with neon, we can support unaligned ld/st
9988     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9989     // A big-endian target may also explicitly support unaligned accesses
9990     if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9991       if (Fast)
9992         *Fast = true;
9993       return true;
9994     }
9995     return false;
9996   }
9997   }
9998 }
9999
10000 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10001                        unsigned AlignCheck) {
10002   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10003           (DstAlign == 0 || DstAlign % AlignCheck == 0));
10004 }
10005
10006 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10007                                            unsigned DstAlign, unsigned SrcAlign,
10008                                            bool IsMemset, bool ZeroMemset,
10009                                            bool MemcpyStrSrc,
10010                                            MachineFunction &MF) const {
10011   const Function *F = MF.getFunction();
10012
10013   // See if we can use NEON instructions for this...
10014   if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
10015       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10016     bool Fast;
10017     if (Size >= 16 &&
10018         (memOpAlign(SrcAlign, DstAlign, 16) ||
10019          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
10020       return MVT::v2f64;
10021     } else if (Size >= 8 &&
10022                (memOpAlign(SrcAlign, DstAlign, 8) ||
10023                 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
10024                  Fast))) {
10025       return MVT::f64;
10026     }
10027   }
10028
10029   // Lowering to i32/i16 if the size permits.
10030   if (Size >= 4)
10031     return MVT::i32;
10032   else if (Size >= 2)
10033     return MVT::i16;
10034
10035   // Let the target-independent logic figure it out.
10036   return MVT::Other;
10037 }
10038
10039 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10040   if (Val.getOpcode() != ISD::LOAD)
10041     return false;
10042
10043   EVT VT1 = Val.getValueType();
10044   if (!VT1.isSimple() || !VT1.isInteger() ||
10045       !VT2.isSimple() || !VT2.isInteger())
10046     return false;
10047
10048   switch (VT1.getSimpleVT().SimpleTy) {
10049   default: break;
10050   case MVT::i1:
10051   case MVT::i8:
10052   case MVT::i16:
10053     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10054     return true;
10055   }
10056
10057   return false;
10058 }
10059
10060 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
10061   EVT VT = ExtVal.getValueType();
10062
10063   if (!isTypeLegal(VT))
10064     return false;
10065
10066   // Don't create a loadext if we can fold the extension into a wide/long
10067   // instruction.
10068   // If there's more than one user instruction, the loadext is desirable no
10069   // matter what.  There can be two uses by the same instruction.
10070   if (ExtVal->use_empty() ||
10071       !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
10072     return true;
10073
10074   SDNode *U = *ExtVal->use_begin();
10075   if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
10076        U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
10077     return false;
10078
10079   return true;
10080 }
10081
10082 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10083   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10084     return false;
10085
10086   if (!isTypeLegal(EVT::getEVT(Ty1)))
10087     return false;
10088
10089   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10090
10091   // Assuming the caller doesn't have a zeroext or signext return parameter,
10092   // truncation all the way down to i1 is valid.
10093   return true;
10094 }
10095
10096
10097 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10098   if (V < 0)
10099     return false;
10100
10101   unsigned Scale = 1;
10102   switch (VT.getSimpleVT().SimpleTy) {
10103   default: return false;
10104   case MVT::i1:
10105   case MVT::i8:
10106     // Scale == 1;
10107     break;
10108   case MVT::i16:
10109     // Scale == 2;
10110     Scale = 2;
10111     break;
10112   case MVT::i32:
10113     // Scale == 4;
10114     Scale = 4;
10115     break;
10116   }
10117
10118   if ((V & (Scale - 1)) != 0)
10119     return false;
10120   V /= Scale;
10121   return V == (V & ((1LL << 5) - 1));
10122 }
10123
10124 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10125                                       const ARMSubtarget *Subtarget) {
10126   bool isNeg = false;
10127   if (V < 0) {
10128     isNeg = true;
10129     V = - V;
10130   }
10131
10132   switch (VT.getSimpleVT().SimpleTy) {
10133   default: return false;
10134   case MVT::i1:
10135   case MVT::i8:
10136   case MVT::i16:
10137   case MVT::i32:
10138     // + imm12 or - imm8
10139     if (isNeg)
10140       return V == (V & ((1LL << 8) - 1));
10141     return V == (V & ((1LL << 12) - 1));
10142   case MVT::f32:
10143   case MVT::f64:
10144     // Same as ARM mode. FIXME: NEON?
10145     if (!Subtarget->hasVFP2())
10146       return false;
10147     if ((V & 3) != 0)
10148       return false;
10149     V >>= 2;
10150     return V == (V & ((1LL << 8) - 1));
10151   }
10152 }
10153
10154 /// isLegalAddressImmediate - Return true if the integer value can be used
10155 /// as the offset of the target addressing mode for load / store of the
10156 /// given type.
10157 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10158                                     const ARMSubtarget *Subtarget) {
10159   if (V == 0)
10160     return true;
10161
10162   if (!VT.isSimple())
10163     return false;
10164
10165   if (Subtarget->isThumb1Only())
10166     return isLegalT1AddressImmediate(V, VT);
10167   else if (Subtarget->isThumb2())
10168     return isLegalT2AddressImmediate(V, VT, Subtarget);
10169
10170   // ARM mode.
10171   if (V < 0)
10172     V = - V;
10173   switch (VT.getSimpleVT().SimpleTy) {
10174   default: return false;
10175   case MVT::i1:
10176   case MVT::i8:
10177   case MVT::i32:
10178     // +- imm12
10179     return V == (V & ((1LL << 12) - 1));
10180   case MVT::i16:
10181     // +- imm8
10182     return V == (V & ((1LL << 8) - 1));
10183   case MVT::f32:
10184   case MVT::f64:
10185     if (!Subtarget->hasVFP2()) // FIXME: NEON?
10186       return false;
10187     if ((V & 3) != 0)
10188       return false;
10189     V >>= 2;
10190     return V == (V & ((1LL << 8) - 1));
10191   }
10192 }
10193
10194 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10195                                                       EVT VT) const {
10196   int Scale = AM.Scale;
10197   if (Scale < 0)
10198     return false;
10199
10200   switch (VT.getSimpleVT().SimpleTy) {
10201   default: return false;
10202   case MVT::i1:
10203   case MVT::i8:
10204   case MVT::i16:
10205   case MVT::i32:
10206     if (Scale == 1)
10207       return true;
10208     // r + r << imm
10209     Scale = Scale & ~1;
10210     return Scale == 2 || Scale == 4 || Scale == 8;
10211   case MVT::i64:
10212     // r + r
10213     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10214       return true;
10215     return false;
10216   case MVT::isVoid:
10217     // Note, we allow "void" uses (basically, uses that aren't loads or
10218     // stores), because arm allows folding a scale into many arithmetic
10219     // operations.  This should be made more precise and revisited later.
10220
10221     // Allow r << imm, but the imm has to be a multiple of two.
10222     if (Scale & 1) return false;
10223     return isPowerOf2_32(Scale);
10224   }
10225 }
10226
10227 /// isLegalAddressingMode - Return true if the addressing mode represented
10228 /// by AM is legal for this target, for a load/store of the specified type.
10229 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10230                                               Type *Ty) const {
10231   EVT VT = getValueType(Ty, true);
10232   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10233     return false;
10234
10235   // Can never fold addr of global into load/store.
10236   if (AM.BaseGV)
10237     return false;
10238
10239   switch (AM.Scale) {
10240   case 0:  // no scale reg, must be "r+i" or "r", or "i".
10241     break;
10242   case 1:
10243     if (Subtarget->isThumb1Only())
10244       return false;
10245     // FALL THROUGH.
10246   default:
10247     // ARM doesn't support any R+R*scale+imm addr modes.
10248     if (AM.BaseOffs)
10249       return false;
10250
10251     if (!VT.isSimple())
10252       return false;
10253
10254     if (Subtarget->isThumb2())
10255       return isLegalT2ScaledAddressingMode(AM, VT);
10256
10257     int Scale = AM.Scale;
10258     switch (VT.getSimpleVT().SimpleTy) {
10259     default: return false;
10260     case MVT::i1:
10261     case MVT::i8:
10262     case MVT::i32:
10263       if (Scale < 0) Scale = -Scale;
10264       if (Scale == 1)
10265         return true;
10266       // r + r << imm
10267       return isPowerOf2_32(Scale & ~1);
10268     case MVT::i16:
10269     case MVT::i64:
10270       // r + r
10271       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10272         return true;
10273       return false;
10274
10275     case MVT::isVoid:
10276       // Note, we allow "void" uses (basically, uses that aren't loads or
10277       // stores), because arm allows folding a scale into many arithmetic
10278       // operations.  This should be made more precise and revisited later.
10279
10280       // Allow r << imm, but the imm has to be a multiple of two.
10281       if (Scale & 1) return false;
10282       return isPowerOf2_32(Scale);
10283     }
10284   }
10285   return true;
10286 }
10287
10288 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10289 /// icmp immediate, that is the target has icmp instructions which can compare
10290 /// a register against the immediate without having to materialize the
10291 /// immediate into a register.
10292 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10293   // Thumb2 and ARM modes can use cmn for negative immediates.
10294   if (!Subtarget->isThumb())
10295     return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
10296   if (Subtarget->isThumb2())
10297     return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
10298   // Thumb1 doesn't have cmn, and only 8-bit immediates.
10299   return Imm >= 0 && Imm <= 255;
10300 }
10301
10302 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10303 /// *or sub* immediate, that is the target has add or sub instructions which can
10304 /// add a register with the immediate without having to materialize the
10305 /// immediate into a register.
10306 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10307   // Same encoding for add/sub, just flip the sign.
10308   int64_t AbsImm = std::abs(Imm);
10309   if (!Subtarget->isThumb())
10310     return ARM_AM::getSOImmVal(AbsImm) != -1;
10311   if (Subtarget->isThumb2())
10312     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10313   // Thumb1 only has 8-bit unsigned immediate.
10314   return AbsImm >= 0 && AbsImm <= 255;
10315 }
10316
10317 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10318                                       bool isSEXTLoad, SDValue &Base,
10319                                       SDValue &Offset, bool &isInc,
10320                                       SelectionDAG &DAG) {
10321   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10322     return false;
10323
10324   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10325     // AddressingMode 3
10326     Base = Ptr->getOperand(0);
10327     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10328       int RHSC = (int)RHS->getZExtValue();
10329       if (RHSC < 0 && RHSC > -256) {
10330         assert(Ptr->getOpcode() == ISD::ADD);
10331         isInc = false;
10332         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10333         return true;
10334       }
10335     }
10336     isInc = (Ptr->getOpcode() == ISD::ADD);
10337     Offset = Ptr->getOperand(1);
10338     return true;
10339   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10340     // AddressingMode 2
10341     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10342       int RHSC = (int)RHS->getZExtValue();
10343       if (RHSC < 0 && RHSC > -0x1000) {
10344         assert(Ptr->getOpcode() == ISD::ADD);
10345         isInc = false;
10346         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10347         Base = Ptr->getOperand(0);
10348         return true;
10349       }
10350     }
10351
10352     if (Ptr->getOpcode() == ISD::ADD) {
10353       isInc = true;
10354       ARM_AM::ShiftOpc ShOpcVal=
10355         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10356       if (ShOpcVal != ARM_AM::no_shift) {
10357         Base = Ptr->getOperand(1);
10358         Offset = Ptr->getOperand(0);
10359       } else {
10360         Base = Ptr->getOperand(0);
10361         Offset = Ptr->getOperand(1);
10362       }
10363       return true;
10364     }
10365
10366     isInc = (Ptr->getOpcode() == ISD::ADD);
10367     Base = Ptr->getOperand(0);
10368     Offset = Ptr->getOperand(1);
10369     return true;
10370   }
10371
10372   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10373   return false;
10374 }
10375
10376 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10377                                      bool isSEXTLoad, SDValue &Base,
10378                                      SDValue &Offset, bool &isInc,
10379                                      SelectionDAG &DAG) {
10380   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10381     return false;
10382
10383   Base = Ptr->getOperand(0);
10384   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10385     int RHSC = (int)RHS->getZExtValue();
10386     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10387       assert(Ptr->getOpcode() == ISD::ADD);
10388       isInc = false;
10389       Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10390       return true;
10391     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10392       isInc = Ptr->getOpcode() == ISD::ADD;
10393       Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
10394       return true;
10395     }
10396   }
10397
10398   return false;
10399 }
10400
10401 /// getPreIndexedAddressParts - returns true by value, base pointer and
10402 /// offset pointer and addressing mode by reference if the node's address
10403 /// can be legally represented as pre-indexed load / store address.
10404 bool
10405 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10406                                              SDValue &Offset,
10407                                              ISD::MemIndexedMode &AM,
10408                                              SelectionDAG &DAG) const {
10409   if (Subtarget->isThumb1Only())
10410     return false;
10411
10412   EVT VT;
10413   SDValue Ptr;
10414   bool isSEXTLoad = false;
10415   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10416     Ptr = LD->getBasePtr();
10417     VT  = LD->getMemoryVT();
10418     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10419   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10420     Ptr = ST->getBasePtr();
10421     VT  = ST->getMemoryVT();
10422   } else
10423     return false;
10424
10425   bool isInc;
10426   bool isLegal = false;
10427   if (Subtarget->isThumb2())
10428     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10429                                        Offset, isInc, DAG);
10430   else
10431     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10432                                         Offset, isInc, DAG);
10433   if (!isLegal)
10434     return false;
10435
10436   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10437   return true;
10438 }
10439
10440 /// getPostIndexedAddressParts - returns true by value, base pointer and
10441 /// offset pointer and addressing mode by reference if this node can be
10442 /// combined with a load / store to form a post-indexed load / store.
10443 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10444                                                    SDValue &Base,
10445                                                    SDValue &Offset,
10446                                                    ISD::MemIndexedMode &AM,
10447                                                    SelectionDAG &DAG) const {
10448   if (Subtarget->isThumb1Only())
10449     return false;
10450
10451   EVT VT;
10452   SDValue Ptr;
10453   bool isSEXTLoad = false;
10454   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10455     VT  = LD->getMemoryVT();
10456     Ptr = LD->getBasePtr();
10457     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10458   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10459     VT  = ST->getMemoryVT();
10460     Ptr = ST->getBasePtr();
10461   } else
10462     return false;
10463
10464   bool isInc;
10465   bool isLegal = false;
10466   if (Subtarget->isThumb2())
10467     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10468                                        isInc, DAG);
10469   else
10470     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10471                                         isInc, DAG);
10472   if (!isLegal)
10473     return false;
10474
10475   if (Ptr != Base) {
10476     // Swap base ptr and offset to catch more post-index load / store when
10477     // it's legal. In Thumb2 mode, offset must be an immediate.
10478     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10479         !Subtarget->isThumb2())
10480       std::swap(Base, Offset);
10481
10482     // Post-indexed load / store update the base pointer.
10483     if (Ptr != Base)
10484       return false;
10485   }
10486
10487   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10488   return true;
10489 }
10490
10491 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10492                                                       APInt &KnownZero,
10493                                                       APInt &KnownOne,
10494                                                       const SelectionDAG &DAG,
10495                                                       unsigned Depth) const {
10496   unsigned BitWidth = KnownOne.getBitWidth();
10497   KnownZero = KnownOne = APInt(BitWidth, 0);
10498   switch (Op.getOpcode()) {
10499   default: break;
10500   case ARMISD::ADDC:
10501   case ARMISD::ADDE:
10502   case ARMISD::SUBC:
10503   case ARMISD::SUBE:
10504     // These nodes' second result is a boolean
10505     if (Op.getResNo() == 0)
10506       break;
10507     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10508     break;
10509   case ARMISD::CMOV: {
10510     // Bits are known zero/one if known on the LHS and RHS.
10511     DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10512     if (KnownZero == 0 && KnownOne == 0) return;
10513
10514     APInt KnownZeroRHS, KnownOneRHS;
10515     DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10516     KnownZero &= KnownZeroRHS;
10517     KnownOne  &= KnownOneRHS;
10518     return;
10519   }
10520   case ISD::INTRINSIC_W_CHAIN: {
10521     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10522     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10523     switch (IntID) {
10524     default: return;
10525     case Intrinsic::arm_ldaex:
10526     case Intrinsic::arm_ldrex: {
10527       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10528       unsigned MemBits = VT.getScalarType().getSizeInBits();
10529       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10530       return;
10531     }
10532     }
10533   }
10534   }
10535 }
10536
10537 //===----------------------------------------------------------------------===//
10538 //                           ARM Inline Assembly Support
10539 //===----------------------------------------------------------------------===//
10540
10541 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10542   // Looking for "rev" which is V6+.
10543   if (!Subtarget->hasV6Ops())
10544     return false;
10545
10546   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10547   std::string AsmStr = IA->getAsmString();
10548   SmallVector<StringRef, 4> AsmPieces;
10549   SplitString(AsmStr, AsmPieces, ";\n");
10550
10551   switch (AsmPieces.size()) {
10552   default: return false;
10553   case 1:
10554     AsmStr = AsmPieces[0];
10555     AsmPieces.clear();
10556     SplitString(AsmStr, AsmPieces, " \t,");
10557
10558     // rev $0, $1
10559     if (AsmPieces.size() == 3 &&
10560         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10561         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10562       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10563       if (Ty && Ty->getBitWidth() == 32)
10564         return IntrinsicLowering::LowerToByteSwap(CI);
10565     }
10566     break;
10567   }
10568
10569   return false;
10570 }
10571
10572 /// getConstraintType - Given a constraint letter, return the type of
10573 /// constraint it is for this target.
10574 ARMTargetLowering::ConstraintType
10575 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10576   if (Constraint.size() == 1) {
10577     switch (Constraint[0]) {
10578     default:  break;
10579     case 'l': return C_RegisterClass;
10580     case 'w': return C_RegisterClass;
10581     case 'h': return C_RegisterClass;
10582     case 'x': return C_RegisterClass;
10583     case 't': return C_RegisterClass;
10584     case 'j': return C_Other; // Constant for movw.
10585       // An address with a single base register. Due to the way we
10586       // currently handle addresses it is the same as an 'r' memory constraint.
10587     case 'Q': return C_Memory;
10588     }
10589   } else if (Constraint.size() == 2) {
10590     switch (Constraint[0]) {
10591     default: break;
10592     // All 'U+' constraints are addresses.
10593     case 'U': return C_Memory;
10594     }
10595   }
10596   return TargetLowering::getConstraintType(Constraint);
10597 }
10598
10599 /// Examine constraint type and operand type and determine a weight value.
10600 /// This object must already have been set up with the operand type
10601 /// and the current alternative constraint selected.
10602 TargetLowering::ConstraintWeight
10603 ARMTargetLowering::getSingleConstraintMatchWeight(
10604     AsmOperandInfo &info, const char *constraint) const {
10605   ConstraintWeight weight = CW_Invalid;
10606   Value *CallOperandVal = info.CallOperandVal;
10607     // If we don't have a value, we can't do a match,
10608     // but allow it at the lowest weight.
10609   if (!CallOperandVal)
10610     return CW_Default;
10611   Type *type = CallOperandVal->getType();
10612   // Look at the constraint type.
10613   switch (*constraint) {
10614   default:
10615     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10616     break;
10617   case 'l':
10618     if (type->isIntegerTy()) {
10619       if (Subtarget->isThumb())
10620         weight = CW_SpecificReg;
10621       else
10622         weight = CW_Register;
10623     }
10624     break;
10625   case 'w':
10626     if (type->isFloatingPointTy())
10627       weight = CW_Register;
10628     break;
10629   }
10630   return weight;
10631 }
10632
10633 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10634 RCPair
10635 ARMTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
10636                                                 const std::string &Constraint,
10637                                                 MVT VT) const {
10638   if (Constraint.size() == 1) {
10639     // GCC ARM Constraint Letters
10640     switch (Constraint[0]) {
10641     case 'l': // Low regs or general regs.
10642       if (Subtarget->isThumb())
10643         return RCPair(0U, &ARM::tGPRRegClass);
10644       return RCPair(0U, &ARM::GPRRegClass);
10645     case 'h': // High regs or no regs.
10646       if (Subtarget->isThumb())
10647         return RCPair(0U, &ARM::hGPRRegClass);
10648       break;
10649     case 'r':
10650       if (Subtarget->isThumb1Only())
10651         return RCPair(0U, &ARM::tGPRRegClass);
10652       return RCPair(0U, &ARM::GPRRegClass);
10653     case 'w':
10654       if (VT == MVT::Other)
10655         break;
10656       if (VT == MVT::f32)
10657         return RCPair(0U, &ARM::SPRRegClass);
10658       if (VT.getSizeInBits() == 64)
10659         return RCPair(0U, &ARM::DPRRegClass);
10660       if (VT.getSizeInBits() == 128)
10661         return RCPair(0U, &ARM::QPRRegClass);
10662       break;
10663     case 'x':
10664       if (VT == MVT::Other)
10665         break;
10666       if (VT == MVT::f32)
10667         return RCPair(0U, &ARM::SPR_8RegClass);
10668       if (VT.getSizeInBits() == 64)
10669         return RCPair(0U, &ARM::DPR_8RegClass);
10670       if (VT.getSizeInBits() == 128)
10671         return RCPair(0U, &ARM::QPR_8RegClass);
10672       break;
10673     case 't':
10674       if (VT == MVT::f32)
10675         return RCPair(0U, &ARM::SPRRegClass);
10676       break;
10677     }
10678   }
10679   if (StringRef("{cc}").equals_lower(Constraint))
10680     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10681
10682   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10683 }
10684
10685 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10686 /// vector.  If it is invalid, don't add anything to Ops.
10687 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10688                                                      std::string &Constraint,
10689                                                      std::vector<SDValue>&Ops,
10690                                                      SelectionDAG &DAG) const {
10691   SDValue Result;
10692
10693   // Currently only support length 1 constraints.
10694   if (Constraint.length() != 1) return;
10695
10696   char ConstraintLetter = Constraint[0];
10697   switch (ConstraintLetter) {
10698   default: break;
10699   case 'j':
10700   case 'I': case 'J': case 'K': case 'L':
10701   case 'M': case 'N': case 'O':
10702     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10703     if (!C)
10704       return;
10705
10706     int64_t CVal64 = C->getSExtValue();
10707     int CVal = (int) CVal64;
10708     // None of these constraints allow values larger than 32 bits.  Check
10709     // that the value fits in an int.
10710     if (CVal != CVal64)
10711       return;
10712
10713     switch (ConstraintLetter) {
10714       case 'j':
10715         // Constant suitable for movw, must be between 0 and
10716         // 65535.
10717         if (Subtarget->hasV6T2Ops())
10718           if (CVal >= 0 && CVal <= 65535)
10719             break;
10720         return;
10721       case 'I':
10722         if (Subtarget->isThumb1Only()) {
10723           // This must be a constant between 0 and 255, for ADD
10724           // immediates.
10725           if (CVal >= 0 && CVal <= 255)
10726             break;
10727         } else if (Subtarget->isThumb2()) {
10728           // A constant that can be used as an immediate value in a
10729           // data-processing instruction.
10730           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10731             break;
10732         } else {
10733           // A constant that can be used as an immediate value in a
10734           // data-processing instruction.
10735           if (ARM_AM::getSOImmVal(CVal) != -1)
10736             break;
10737         }
10738         return;
10739
10740       case 'J':
10741         if (Subtarget->isThumb()) {  // FIXME thumb2
10742           // This must be a constant between -255 and -1, for negated ADD
10743           // immediates. This can be used in GCC with an "n" modifier that
10744           // prints the negated value, for use with SUB instructions. It is
10745           // not useful otherwise but is implemented for compatibility.
10746           if (CVal >= -255 && CVal <= -1)
10747             break;
10748         } else {
10749           // This must be a constant between -4095 and 4095. It is not clear
10750           // what this constraint is intended for. Implemented for
10751           // compatibility with GCC.
10752           if (CVal >= -4095 && CVal <= 4095)
10753             break;
10754         }
10755         return;
10756
10757       case 'K':
10758         if (Subtarget->isThumb1Only()) {
10759           // A 32-bit value where only one byte has a nonzero value. Exclude
10760           // zero to match GCC. This constraint is used by GCC internally for
10761           // constants that can be loaded with a move/shift combination.
10762           // It is not useful otherwise but is implemented for compatibility.
10763           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10764             break;
10765         } else if (Subtarget->isThumb2()) {
10766           // A constant whose bitwise inverse can be used as an immediate
10767           // value in a data-processing instruction. This can be used in GCC
10768           // with a "B" modifier that prints the inverted value, for use with
10769           // BIC and MVN instructions. It is not useful otherwise but is
10770           // implemented for compatibility.
10771           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10772             break;
10773         } else {
10774           // A constant whose bitwise inverse can be used as an immediate
10775           // value in a data-processing instruction. This can be used in GCC
10776           // with a "B" modifier that prints the inverted value, for use with
10777           // BIC and MVN instructions. It is not useful otherwise but is
10778           // implemented for compatibility.
10779           if (ARM_AM::getSOImmVal(~CVal) != -1)
10780             break;
10781         }
10782         return;
10783
10784       case 'L':
10785         if (Subtarget->isThumb1Only()) {
10786           // This must be a constant between -7 and 7,
10787           // for 3-operand ADD/SUB immediate instructions.
10788           if (CVal >= -7 && CVal < 7)
10789             break;
10790         } else if (Subtarget->isThumb2()) {
10791           // A constant whose negation can be used as an immediate value in a
10792           // data-processing instruction. This can be used in GCC with an "n"
10793           // modifier that prints the negated value, for use with SUB
10794           // instructions. It is not useful otherwise but is implemented for
10795           // compatibility.
10796           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10797             break;
10798         } else {
10799           // A constant whose negation can be used as an immediate value in a
10800           // data-processing instruction. This can be used in GCC with an "n"
10801           // modifier that prints the negated value, for use with SUB
10802           // instructions. It is not useful otherwise but is implemented for
10803           // compatibility.
10804           if (ARM_AM::getSOImmVal(-CVal) != -1)
10805             break;
10806         }
10807         return;
10808
10809       case 'M':
10810         if (Subtarget->isThumb()) { // FIXME thumb2
10811           // This must be a multiple of 4 between 0 and 1020, for
10812           // ADD sp + immediate.
10813           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10814             break;
10815         } else {
10816           // A power of two or a constant between 0 and 32.  This is used in
10817           // GCC for the shift amount on shifted register operands, but it is
10818           // useful in general for any shift amounts.
10819           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10820             break;
10821         }
10822         return;
10823
10824       case 'N':
10825         if (Subtarget->isThumb()) {  // FIXME thumb2
10826           // This must be a constant between 0 and 31, for shift amounts.
10827           if (CVal >= 0 && CVal <= 31)
10828             break;
10829         }
10830         return;
10831
10832       case 'O':
10833         if (Subtarget->isThumb()) {  // FIXME thumb2
10834           // This must be a multiple of 4 between -508 and 508, for
10835           // ADD/SUB sp = sp + immediate.
10836           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10837             break;
10838         }
10839         return;
10840     }
10841     Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
10842     break;
10843   }
10844
10845   if (Result.getNode()) {
10846     Ops.push_back(Result);
10847     return;
10848   }
10849   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10850 }
10851
10852 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10853   assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10854   unsigned Opcode = Op->getOpcode();
10855   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10856          "Invalid opcode for Div/Rem lowering");
10857   bool isSigned = (Opcode == ISD::SDIVREM);
10858   EVT VT = Op->getValueType(0);
10859   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10860
10861   RTLIB::Libcall LC;
10862   switch (VT.getSimpleVT().SimpleTy) {
10863   default: llvm_unreachable("Unexpected request for libcall!");
10864   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
10865   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10866   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10867   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10868   }
10869
10870   SDValue InChain = DAG.getEntryNode();
10871
10872   TargetLowering::ArgListTy Args;
10873   TargetLowering::ArgListEntry Entry;
10874   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
10875     EVT ArgVT = Op->getOperand(i).getValueType();
10876     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10877     Entry.Node = Op->getOperand(i);
10878     Entry.Ty = ArgTy;
10879     Entry.isSExt = isSigned;
10880     Entry.isZExt = !isSigned;
10881     Args.push_back(Entry);
10882   }
10883
10884   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
10885                                          getPointerTy());
10886
10887   Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
10888
10889   SDLoc dl(Op);
10890   TargetLowering::CallLoweringInfo CLI(DAG);
10891   CLI.setDebugLoc(dl).setChain(InChain)
10892     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
10893     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
10894
10895   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
10896   return CallInfo.first;
10897 }
10898
10899 SDValue
10900 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
10901   assert(Subtarget->isTargetWindows() && "unsupported target platform");
10902   SDLoc DL(Op);
10903
10904   // Get the inputs.
10905   SDValue Chain = Op.getOperand(0);
10906   SDValue Size  = Op.getOperand(1);
10907
10908   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
10909                               DAG.getConstant(2, DL, MVT::i32));
10910
10911   SDValue Flag;
10912   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
10913   Flag = Chain.getValue(1);
10914
10915   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10916   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
10917
10918   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
10919   Chain = NewSP.getValue(1);
10920
10921   SDValue Ops[2] = { NewSP, Chain };
10922   return DAG.getMergeValues(Ops, DL);
10923 }
10924
10925 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
10926   assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
10927          "Unexpected type for custom-lowering FP_EXTEND");
10928
10929   RTLIB::Libcall LC;
10930   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
10931
10932   SDValue SrcVal = Op.getOperand(0);
10933   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
10934                      /*isSigned*/ false, SDLoc(Op)).first;
10935 }
10936
10937 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
10938   assert(Op.getOperand(0).getValueType() == MVT::f64 &&
10939          Subtarget->isFPOnlySP() &&
10940          "Unexpected type for custom-lowering FP_ROUND");
10941
10942   RTLIB::Libcall LC;
10943   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
10944
10945   SDValue SrcVal = Op.getOperand(0);
10946   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
10947                      /*isSigned*/ false, SDLoc(Op)).first;
10948 }
10949
10950 bool
10951 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10952   // The ARM target isn't yet aware of offsets.
10953   return false;
10954 }
10955
10956 bool ARM::isBitFieldInvertedMask(unsigned v) {
10957   if (v == 0xffffffff)
10958     return false;
10959
10960   // there can be 1's on either or both "outsides", all the "inside"
10961   // bits must be 0's
10962   return isShiftedMask_32(~v);
10963 }
10964
10965 /// isFPImmLegal - Returns true if the target can instruction select the
10966 /// specified FP immediate natively. If false, the legalizer will
10967 /// materialize the FP immediate as a load from a constant pool.
10968 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10969   if (!Subtarget->hasVFP3())
10970     return false;
10971   if (VT == MVT::f32)
10972     return ARM_AM::getFP32Imm(Imm) != -1;
10973   if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
10974     return ARM_AM::getFP64Imm(Imm) != -1;
10975   return false;
10976 }
10977
10978 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10979 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
10980 /// specified in the intrinsic calls.
10981 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10982                                            const CallInst &I,
10983                                            unsigned Intrinsic) const {
10984   switch (Intrinsic) {
10985   case Intrinsic::arm_neon_vld1:
10986   case Intrinsic::arm_neon_vld2:
10987   case Intrinsic::arm_neon_vld3:
10988   case Intrinsic::arm_neon_vld4:
10989   case Intrinsic::arm_neon_vld2lane:
10990   case Intrinsic::arm_neon_vld3lane:
10991   case Intrinsic::arm_neon_vld4lane: {
10992     Info.opc = ISD::INTRINSIC_W_CHAIN;
10993     // Conservatively set memVT to the entire set of vectors loaded.
10994     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10995     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10996     Info.ptrVal = I.getArgOperand(0);
10997     Info.offset = 0;
10998     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10999     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11000     Info.vol = false; // volatile loads with NEON intrinsics not supported
11001     Info.readMem = true;
11002     Info.writeMem = false;
11003     return true;
11004   }
11005   case Intrinsic::arm_neon_vst1:
11006   case Intrinsic::arm_neon_vst2:
11007   case Intrinsic::arm_neon_vst3:
11008   case Intrinsic::arm_neon_vst4:
11009   case Intrinsic::arm_neon_vst2lane:
11010   case Intrinsic::arm_neon_vst3lane:
11011   case Intrinsic::arm_neon_vst4lane: {
11012     Info.opc = ISD::INTRINSIC_VOID;
11013     // Conservatively set memVT to the entire set of vectors stored.
11014     unsigned NumElts = 0;
11015     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11016       Type *ArgTy = I.getArgOperand(ArgI)->getType();
11017       if (!ArgTy->isVectorTy())
11018         break;
11019       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
11020     }
11021     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11022     Info.ptrVal = I.getArgOperand(0);
11023     Info.offset = 0;
11024     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11025     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11026     Info.vol = false; // volatile stores with NEON intrinsics not supported
11027     Info.readMem = false;
11028     Info.writeMem = true;
11029     return true;
11030   }
11031   case Intrinsic::arm_ldaex:
11032   case Intrinsic::arm_ldrex: {
11033     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11034     Info.opc = ISD::INTRINSIC_W_CHAIN;
11035     Info.memVT = MVT::getVT(PtrTy->getElementType());
11036     Info.ptrVal = I.getArgOperand(0);
11037     Info.offset = 0;
11038     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11039     Info.vol = true;
11040     Info.readMem = true;
11041     Info.writeMem = false;
11042     return true;
11043   }
11044   case Intrinsic::arm_stlex:
11045   case Intrinsic::arm_strex: {
11046     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11047     Info.opc = ISD::INTRINSIC_W_CHAIN;
11048     Info.memVT = MVT::getVT(PtrTy->getElementType());
11049     Info.ptrVal = I.getArgOperand(1);
11050     Info.offset = 0;
11051     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11052     Info.vol = true;
11053     Info.readMem = false;
11054     Info.writeMem = true;
11055     return true;
11056   }
11057   case Intrinsic::arm_stlexd:
11058   case Intrinsic::arm_strexd: {
11059     Info.opc = ISD::INTRINSIC_W_CHAIN;
11060     Info.memVT = MVT::i64;
11061     Info.ptrVal = I.getArgOperand(2);
11062     Info.offset = 0;
11063     Info.align = 8;
11064     Info.vol = true;
11065     Info.readMem = false;
11066     Info.writeMem = true;
11067     return true;
11068   }
11069   case Intrinsic::arm_ldaexd:
11070   case Intrinsic::arm_ldrexd: {
11071     Info.opc = ISD::INTRINSIC_W_CHAIN;
11072     Info.memVT = MVT::i64;
11073     Info.ptrVal = I.getArgOperand(0);
11074     Info.offset = 0;
11075     Info.align = 8;
11076     Info.vol = true;
11077     Info.readMem = true;
11078     Info.writeMem = false;
11079     return true;
11080   }
11081   default:
11082     break;
11083   }
11084
11085   return false;
11086 }
11087
11088 /// \brief Returns true if it is beneficial to convert a load of a constant
11089 /// to just the constant itself.
11090 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11091                                                           Type *Ty) const {
11092   assert(Ty->isIntegerTy());
11093
11094   unsigned Bits = Ty->getPrimitiveSizeInBits();
11095   if (Bits == 0 || Bits > 32)
11096     return false;
11097   return true;
11098 }
11099
11100 bool ARMTargetLowering::hasLoadLinkedStoreConditional() const { return true; }
11101
11102 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
11103                                         ARM_MB::MemBOpt Domain) const {
11104   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11105
11106   // First, if the target has no DMB, see what fallback we can use.
11107   if (!Subtarget->hasDataBarrier()) {
11108     // Some ARMv6 cpus can support data barriers with an mcr instruction.
11109     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
11110     // here.
11111     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
11112       Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
11113       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
11114                         Builder.getInt32(0), Builder.getInt32(7),
11115                         Builder.getInt32(10), Builder.getInt32(5)};
11116       return Builder.CreateCall(MCR, args);
11117     } else {
11118       // Instead of using barriers, atomic accesses on these subtargets use
11119       // libcalls.
11120       llvm_unreachable("makeDMB on a target so old that it has no barriers");
11121     }
11122   } else {
11123     Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
11124     // Only a full system barrier exists in the M-class architectures.
11125     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
11126     Constant *CDomain = Builder.getInt32(Domain);
11127     return Builder.CreateCall(DMB, CDomain);
11128   }
11129 }
11130
11131 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11132 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11133                                          AtomicOrdering Ord, bool IsStore,
11134                                          bool IsLoad) const {
11135   if (!getInsertFencesForAtomic())
11136     return nullptr;
11137
11138   switch (Ord) {
11139   case NotAtomic:
11140   case Unordered:
11141     llvm_unreachable("Invalid fence: unordered/non-atomic");
11142   case Monotonic:
11143   case Acquire:
11144     return nullptr; // Nothing to do
11145   case SequentiallyConsistent:
11146     if (!IsStore)
11147       return nullptr; // Nothing to do
11148     /*FALLTHROUGH*/
11149   case Release:
11150   case AcquireRelease:
11151     if (Subtarget->isSwift())
11152       return makeDMB(Builder, ARM_MB::ISHST);
11153     // FIXME: add a comment with a link to documentation justifying this.
11154     else
11155       return makeDMB(Builder, ARM_MB::ISH);
11156   }
11157   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
11158 }
11159
11160 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11161                                           AtomicOrdering Ord, bool IsStore,
11162                                           bool IsLoad) const {
11163   if (!getInsertFencesForAtomic())
11164     return nullptr;
11165
11166   switch (Ord) {
11167   case NotAtomic:
11168   case Unordered:
11169     llvm_unreachable("Invalid fence: unordered/not-atomic");
11170   case Monotonic:
11171   case Release:
11172     return nullptr; // Nothing to do
11173   case Acquire:
11174   case AcquireRelease:
11175   case SequentiallyConsistent:
11176     return makeDMB(Builder, ARM_MB::ISH);
11177   }
11178   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
11179 }
11180
11181 // Loads and stores less than 64-bits are already atomic; ones above that
11182 // are doomed anyway, so defer to the default libcall and blame the OS when
11183 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11184 // anything for those.
11185 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11186   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11187   return (Size == 64) && !Subtarget->isMClass();
11188 }
11189
11190 // Loads and stores less than 64-bits are already atomic; ones above that
11191 // are doomed anyway, so defer to the default libcall and blame the OS when
11192 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11193 // anything for those.
11194 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
11195 // guarantee, see DDI0406C ARM architecture reference manual,
11196 // sections A8.8.72-74 LDRD)
11197 bool ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11198   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11199   return (Size == 64) && !Subtarget->isMClass();
11200 }
11201
11202 // For the real atomic operations, we have ldrex/strex up to 32 bits,
11203 // and up to 64 bits on the non-M profiles
11204 TargetLoweringBase::AtomicRMWExpansionKind
11205 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11206   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11207   return (Size <= (Subtarget->isMClass() ? 32U : 64U))
11208              ? AtomicRMWExpansionKind::LLSC
11209              : AtomicRMWExpansionKind::None;
11210 }
11211
11212 // This has so far only been implemented for MachO.
11213 bool ARMTargetLowering::useLoadStackGuardNode() const {
11214   return Subtarget->isTargetMachO();
11215 }
11216
11217 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
11218                                                   unsigned &Cost) const {
11219   // If we do not have NEON, vector types are not natively supported.
11220   if (!Subtarget->hasNEON())
11221     return false;
11222
11223   // Floating point values and vector values map to the same register file.
11224   // Therefore, althought we could do a store extract of a vector type, this is
11225   // better to leave at float as we have more freedom in the addressing mode for
11226   // those.
11227   if (VectorTy->isFPOrFPVectorTy())
11228     return false;
11229
11230   // If the index is unknown at compile time, this is very expensive to lower
11231   // and it is not possible to combine the store with the extract.
11232   if (!isa<ConstantInt>(Idx))
11233     return false;
11234
11235   assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
11236   unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
11237   // We can do a store + vector extract on any vector that fits perfectly in a D
11238   // or Q register.
11239   if (BitWidth == 64 || BitWidth == 128) {
11240     Cost = 0;
11241     return true;
11242   }
11243   return false;
11244 }
11245
11246 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11247                                          AtomicOrdering Ord) const {
11248   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11249   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11250   bool IsAcquire = isAtLeastAcquire(Ord);
11251
11252   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
11253   // intrinsic must return {i32, i32} and we have to recombine them into a
11254   // single i64 here.
11255   if (ValTy->getPrimitiveSizeInBits() == 64) {
11256     Intrinsic::ID Int =
11257         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
11258     Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
11259
11260     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11261     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
11262
11263     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11264     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11265     if (!Subtarget->isLittle())
11266       std::swap (Lo, Hi);
11267     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11268     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11269     return Builder.CreateOr(
11270         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
11271   }
11272
11273   Type *Tys[] = { Addr->getType() };
11274   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
11275   Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
11276
11277   return Builder.CreateTruncOrBitCast(
11278       Builder.CreateCall(Ldrex, Addr),
11279       cast<PointerType>(Addr->getType())->getElementType());
11280 }
11281
11282 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
11283                                                Value *Addr,
11284                                                AtomicOrdering Ord) const {
11285   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11286   bool IsRelease = isAtLeastRelease(Ord);
11287
11288   // Since the intrinsics must have legal type, the i64 intrinsics take two
11289   // parameters: "i32, i32". We must marshal Val into the appropriate form
11290   // before the call.
11291   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
11292     Intrinsic::ID Int =
11293         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
11294     Function *Strex = Intrinsic::getDeclaration(M, Int);
11295     Type *Int32Ty = Type::getInt32Ty(M->getContext());
11296
11297     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
11298     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
11299     if (!Subtarget->isLittle())
11300       std::swap (Lo, Hi);
11301     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11302     return Builder.CreateCall3(Strex, Lo, Hi, Addr);
11303   }
11304
11305   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
11306   Type *Tys[] = { Addr->getType() };
11307   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
11308
11309   return Builder.CreateCall2(
11310       Strex, Builder.CreateZExtOrBitCast(
11311                  Val, Strex->getFunctionType()->getParamType(0)),
11312       Addr);
11313 }
11314
11315 enum HABaseType {
11316   HA_UNKNOWN = 0,
11317   HA_FLOAT,
11318   HA_DOUBLE,
11319   HA_VECT64,
11320   HA_VECT128
11321 };
11322
11323 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
11324                                    uint64_t &Members) {
11325   if (const StructType *ST = dyn_cast<StructType>(Ty)) {
11326     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
11327       uint64_t SubMembers = 0;
11328       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
11329         return false;
11330       Members += SubMembers;
11331     }
11332   } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
11333     uint64_t SubMembers = 0;
11334     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
11335       return false;
11336     Members += SubMembers * AT->getNumElements();
11337   } else if (Ty->isFloatTy()) {
11338     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
11339       return false;
11340     Members = 1;
11341     Base = HA_FLOAT;
11342   } else if (Ty->isDoubleTy()) {
11343     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
11344       return false;
11345     Members = 1;
11346     Base = HA_DOUBLE;
11347   } else if (const VectorType *VT = dyn_cast<VectorType>(Ty)) {
11348     Members = 1;
11349     switch (Base) {
11350     case HA_FLOAT:
11351     case HA_DOUBLE:
11352       return false;
11353     case HA_VECT64:
11354       return VT->getBitWidth() == 64;
11355     case HA_VECT128:
11356       return VT->getBitWidth() == 128;
11357     case HA_UNKNOWN:
11358       switch (VT->getBitWidth()) {
11359       case 64:
11360         Base = HA_VECT64;
11361         return true;
11362       case 128:
11363         Base = HA_VECT128;
11364         return true;
11365       default:
11366         return false;
11367       }
11368     }
11369   }
11370
11371   return (Members > 0 && Members <= 4);
11372 }
11373
11374 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
11375 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
11376 /// passing according to AAPCS rules.
11377 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
11378     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11379   if (getEffectiveCallingConv(CallConv, isVarArg) !=
11380       CallingConv::ARM_AAPCS_VFP)
11381     return false;
11382
11383   HABaseType Base = HA_UNKNOWN;
11384   uint64_t Members = 0;
11385   bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
11386   DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
11387
11388   bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
11389   return IsHA || IsIntArray;
11390 }