Simplify IRBuilder::CreateCall* by using ArrayRef+initializer_list/braced init only
[oota-llvm.git] / lib / Target / ARM / ARMISelLowering.cpp
1 //===-- ARMISelLowering.cpp - ARM DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that ARM uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "ARMISelLowering.h"
16 #include "ARMCallingConv.h"
17 #include "ARMConstantPoolValue.h"
18 #include "ARMMachineFunctionInfo.h"
19 #include "ARMPerfectShuffle.h"
20 #include "ARMSubtarget.h"
21 #include "ARMTargetMachine.h"
22 #include "ARMTargetObjectFile.h"
23 #include "MCTargetDesc/ARMAddressingModes.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/ADT/StringSwitch.h"
27 #include "llvm/CodeGen/CallingConvLower.h"
28 #include "llvm/CodeGen/IntrinsicLowering.h"
29 #include "llvm/CodeGen/MachineBasicBlock.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineJumpTableInfo.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/SelectionDAG.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/GlobalValue.h"
41 #include "llvm/IR/IRBuilder.h"
42 #include "llvm/IR/Instruction.h"
43 #include "llvm/IR/Instructions.h"
44 #include "llvm/IR/IntrinsicInst.h"
45 #include "llvm/IR/Intrinsics.h"
46 #include "llvm/IR/Type.h"
47 #include "llvm/MC/MCSectionMachO.h"
48 #include "llvm/Support/CommandLine.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Support/raw_ostream.h"
53 #include "llvm/Target/TargetOptions.h"
54 #include <utility>
55 using namespace llvm;
56
57 #define DEBUG_TYPE "arm-isel"
58
59 STATISTIC(NumTailCalls, "Number of tail calls");
60 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
61 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
62
63 cl::opt<bool>
64 EnableARMLongCalls("arm-long-calls", cl::Hidden,
65   cl::desc("Generate calls via indirect call instructions"),
66   cl::init(false));
67
68 static cl::opt<bool>
69 ARMInterworking("arm-interworking", cl::Hidden,
70   cl::desc("Enable / disable ARM interworking (for debugging only)"),
71   cl::init(true));
72
73 namespace {
74   class ARMCCState : public CCState {
75   public:
76     ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
77                SmallVectorImpl<CCValAssign> &locs, LLVMContext &C,
78                ParmContext PC)
79         : CCState(CC, isVarArg, MF, locs, C) {
80       assert(((PC == Call) || (PC == Prologue)) &&
81              "ARMCCState users must specify whether their context is call"
82              "or prologue generation.");
83       CallOrPrologue = PC;
84     }
85   };
86 }
87
88 // The APCS parameter registers.
89 static const MCPhysReg GPRArgRegs[] = {
90   ARM::R0, ARM::R1, ARM::R2, ARM::R3
91 };
92
93 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
94                                        MVT PromotedBitwiseVT) {
95   if (VT != PromotedLdStVT) {
96     setOperationAction(ISD::LOAD, VT, Promote);
97     AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
98
99     setOperationAction(ISD::STORE, VT, Promote);
100     AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
101   }
102
103   MVT ElemTy = VT.getVectorElementType();
104   if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
105     setOperationAction(ISD::SETCC, VT, Custom);
106   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
107   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
108   if (ElemTy == MVT::i32) {
109     setOperationAction(ISD::SINT_TO_FP, VT, Custom);
110     setOperationAction(ISD::UINT_TO_FP, VT, Custom);
111     setOperationAction(ISD::FP_TO_SINT, VT, Custom);
112     setOperationAction(ISD::FP_TO_UINT, VT, Custom);
113   } else {
114     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
115     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
116     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
117     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
118   }
119   setOperationAction(ISD::BUILD_VECTOR,      VT, Custom);
120   setOperationAction(ISD::VECTOR_SHUFFLE,    VT, Custom);
121   setOperationAction(ISD::CONCAT_VECTORS,    VT, Legal);
122   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
123   setOperationAction(ISD::SELECT,            VT, Expand);
124   setOperationAction(ISD::SELECT_CC,         VT, Expand);
125   setOperationAction(ISD::VSELECT,           VT, Expand);
126   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
127   if (VT.isInteger()) {
128     setOperationAction(ISD::SHL, VT, Custom);
129     setOperationAction(ISD::SRA, VT, Custom);
130     setOperationAction(ISD::SRL, VT, Custom);
131   }
132
133   // Promote all bit-wise operations.
134   if (VT.isInteger() && VT != PromotedBitwiseVT) {
135     setOperationAction(ISD::AND, VT, Promote);
136     AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
137     setOperationAction(ISD::OR,  VT, Promote);
138     AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
139     setOperationAction(ISD::XOR, VT, Promote);
140     AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
141   }
142
143   // Neon does not support vector divide/remainder operations.
144   setOperationAction(ISD::SDIV, VT, Expand);
145   setOperationAction(ISD::UDIV, VT, Expand);
146   setOperationAction(ISD::FDIV, VT, Expand);
147   setOperationAction(ISD::SREM, VT, Expand);
148   setOperationAction(ISD::UREM, VT, Expand);
149   setOperationAction(ISD::FREM, VT, Expand);
150 }
151
152 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
153   addRegisterClass(VT, &ARM::DPRRegClass);
154   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
155 }
156
157 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
158   addRegisterClass(VT, &ARM::DPairRegClass);
159   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
160 }
161
162 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM,
163                                      const ARMSubtarget &STI)
164     : TargetLowering(TM), Subtarget(&STI) {
165   RegInfo = Subtarget->getRegisterInfo();
166   Itins = Subtarget->getInstrItineraryData();
167
168   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
169
170   if (Subtarget->isTargetMachO()) {
171     // Uses VFP for Thumb libfuncs if available.
172     if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
173         Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) {
174       // Single-precision floating-point arithmetic.
175       setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
176       setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
177       setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
178       setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
179
180       // Double-precision floating-point arithmetic.
181       setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
182       setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
183       setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
184       setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
185
186       // Single-precision comparisons.
187       setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
188       setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
189       setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
190       setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
191       setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
192       setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
193       setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
194       setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
195
196       setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
197       setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
198       setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
199       setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
200       setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
201       setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
202       setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
203       setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
204
205       // Double-precision comparisons.
206       setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
207       setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
208       setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
209       setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
210       setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
211       setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
212       setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
213       setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
214
215       setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
216       setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
217       setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
218       setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
219       setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
220       setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
221       setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
222       setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
223
224       // Floating-point to integer conversions.
225       // i64 conversions are done via library routines even when generating VFP
226       // instructions, so use the same ones.
227       setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
228       setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
229       setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
230       setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
231
232       // Conversions between floating types.
233       setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
234       setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
235
236       // Integer to floating-point conversions.
237       // i64 conversions are done via library routines even when generating VFP
238       // instructions, so use the same ones.
239       // FIXME: There appears to be some naming inconsistency in ARM libgcc:
240       // e.g., __floatunsidf vs. __floatunssidfvfp.
241       setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
242       setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
243       setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
244       setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
245     }
246   }
247
248   // These libcalls are not available in 32-bit.
249   setLibcallName(RTLIB::SHL_I128, nullptr);
250   setLibcallName(RTLIB::SRL_I128, nullptr);
251   setLibcallName(RTLIB::SRA_I128, nullptr);
252
253   if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO() &&
254       !Subtarget->isTargetWindows()) {
255     static const struct {
256       const RTLIB::Libcall Op;
257       const char * const Name;
258       const CallingConv::ID CC;
259       const ISD::CondCode Cond;
260     } LibraryCalls[] = {
261       // Double-precision floating-point arithmetic helper functions
262       // RTABI chapter 4.1.2, Table 2
263       { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
264       { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
265       { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
266       { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
267
268       // Double-precision floating-point comparison helper functions
269       // RTABI chapter 4.1.2, Table 3
270       { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
271       { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
272       { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
273       { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
274       { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
275       { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
276       { RTLIB::UO_F64,  "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
277       { RTLIB::O_F64,   "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
278
279       // Single-precision floating-point arithmetic helper functions
280       // RTABI chapter 4.1.2, Table 4
281       { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
282       { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
283       { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
284       { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
285
286       // Single-precision floating-point comparison helper functions
287       // RTABI chapter 4.1.2, Table 5
288       { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
289       { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
290       { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
291       { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
292       { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
293       { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
294       { RTLIB::UO_F32,  "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
295       { RTLIB::O_F32,   "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
296
297       // Floating-point to integer conversions.
298       // RTABI chapter 4.1.2, Table 6
299       { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
300       { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
301       { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
302       { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
303       { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
304       { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
305       { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
306       { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
307
308       // Conversions between floating types.
309       // RTABI chapter 4.1.2, Table 7
310       { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
311       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
312       { RTLIB::FPEXT_F32_F64,   "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
313
314       // Integer to floating-point conversions.
315       // RTABI chapter 4.1.2, Table 8
316       { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
317       { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
318       { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
319       { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
320       { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
321       { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
322       { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
323       { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
324
325       // Long long helper functions
326       // RTABI chapter 4.2, Table 9
327       { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
328       { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
329       { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
330       { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
331
332       // Integer division functions
333       // RTABI chapter 4.3.1
334       { RTLIB::SDIV_I8,  "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
335       { RTLIB::SDIV_I16, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
336       { RTLIB::SDIV_I32, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
337       { RTLIB::SDIV_I64, "__aeabi_ldivmod",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
338       { RTLIB::UDIV_I8,  "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
339       { RTLIB::UDIV_I16, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
340       { RTLIB::UDIV_I32, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
341       { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
342
343       // Memory operations
344       // RTABI chapter 4.3.4
345       { RTLIB::MEMCPY,  "__aeabi_memcpy",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
346       { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
347       { RTLIB::MEMSET,  "__aeabi_memset",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
348     };
349
350     for (const auto &LC : LibraryCalls) {
351       setLibcallName(LC.Op, LC.Name);
352       setLibcallCallingConv(LC.Op, LC.CC);
353       if (LC.Cond != ISD::SETCC_INVALID)
354         setCmpLibcallCC(LC.Op, LC.Cond);
355     }
356   }
357
358   if (Subtarget->isTargetWindows()) {
359     static const struct {
360       const RTLIB::Libcall Op;
361       const char * const Name;
362       const CallingConv::ID CC;
363     } LibraryCalls[] = {
364       { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
365       { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
366       { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
367       { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
368       { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
369       { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
370       { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
371       { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
372     };
373
374     for (const auto &LC : LibraryCalls) {
375       setLibcallName(LC.Op, LC.Name);
376       setLibcallCallingConv(LC.Op, LC.CC);
377     }
378   }
379
380   // Use divmod compiler-rt calls for iOS 5.0 and later.
381   if (Subtarget->getTargetTriple().isiOS() &&
382       !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
383     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
384     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
385   }
386
387   // The half <-> float conversion functions are always soft-float, but are
388   // needed for some targets which use a hard-float calling convention by
389   // default.
390   if (Subtarget->isAAPCS_ABI()) {
391     setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
392     setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
393     setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
394   } else {
395     setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
396     setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
397     setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
398   }
399
400   if (Subtarget->isThumb1Only())
401     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
402   else
403     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
404   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
405       !Subtarget->isThumb1Only()) {
406     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
407     addRegisterClass(MVT::f64, &ARM::DPRRegClass);
408   }
409
410   for (MVT VT : MVT::vector_valuetypes()) {
411     for (MVT InnerVT : MVT::vector_valuetypes()) {
412       setTruncStoreAction(VT, InnerVT, Expand);
413       setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
414       setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
415       setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
416     }
417
418     setOperationAction(ISD::MULHS, VT, Expand);
419     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
420     setOperationAction(ISD::MULHU, VT, Expand);
421     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
422
423     setOperationAction(ISD::BSWAP, VT, Expand);
424   }
425
426   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
427   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
428
429   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 (!Subtarget->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 (!Subtarget->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 (!Subtarget->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 (Subtarget->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 bool ARMTargetLowering::useSoftFloat() const {
960   return Subtarget->useSoftFloat();
961 }
962
963 // FIXME: It might make sense to define the representative register class as the
964 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
965 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
966 // SPR's representative would be DPR_VFP2. This should work well if register
967 // pressure tracking were modified such that a register use would increment the
968 // pressure of the register class's representative and all of it's super
969 // classes' representatives transitively. We have not implemented this because
970 // of the difficulty prior to coalescing of modeling operand register classes
971 // due to the common occurrence of cross class copies and subregister insertions
972 // and extractions.
973 std::pair<const TargetRegisterClass *, uint8_t>
974 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
975                                            MVT VT) const {
976   const TargetRegisterClass *RRC = nullptr;
977   uint8_t Cost = 1;
978   switch (VT.SimpleTy) {
979   default:
980     return TargetLowering::findRepresentativeClass(TRI, VT);
981   // Use DPR as representative register class for all floating point
982   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
983   // the cost is 1 for both f32 and f64.
984   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
985   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
986     RRC = &ARM::DPRRegClass;
987     // When NEON is used for SP, only half of the register file is available
988     // because operations that define both SP and DP results will be constrained
989     // to the VFP2 class (D0-D15). We currently model this constraint prior to
990     // coalescing by double-counting the SP regs. See the FIXME above.
991     if (Subtarget->useNEONForSinglePrecisionFP())
992       Cost = 2;
993     break;
994   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
995   case MVT::v4f32: case MVT::v2f64:
996     RRC = &ARM::DPRRegClass;
997     Cost = 2;
998     break;
999   case MVT::v4i64:
1000     RRC = &ARM::DPRRegClass;
1001     Cost = 4;
1002     break;
1003   case MVT::v8i64:
1004     RRC = &ARM::DPRRegClass;
1005     Cost = 8;
1006     break;
1007   }
1008   return std::make_pair(RRC, Cost);
1009 }
1010
1011 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1012   switch ((ARMISD::NodeType)Opcode) {
1013   case ARMISD::FIRST_NUMBER:  break;
1014   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1015   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1016   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1017   case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1018   case ARMISD::CALL:          return "ARMISD::CALL";
1019   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1020   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1021   case ARMISD::tCALL:         return "ARMISD::tCALL";
1022   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1023   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1024   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1025   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1026   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1027   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1028   case ARMISD::CMP:           return "ARMISD::CMP";
1029   case ARMISD::CMN:           return "ARMISD::CMN";
1030   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1031   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1032   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1033   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1034   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1035
1036   case ARMISD::CMOV:          return "ARMISD::CMOV";
1037
1038   case ARMISD::RBIT:          return "ARMISD::RBIT";
1039
1040   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1041   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1042   case ARMISD::RRX:           return "ARMISD::RRX";
1043
1044   case ARMISD::ADDC:          return "ARMISD::ADDC";
1045   case ARMISD::ADDE:          return "ARMISD::ADDE";
1046   case ARMISD::SUBC:          return "ARMISD::SUBC";
1047   case ARMISD::SUBE:          return "ARMISD::SUBE";
1048
1049   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1050   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1051
1052   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1053   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
1054
1055   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1056
1057   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1058
1059   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1060
1061   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1062
1063   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1064
1065   case ARMISD::WIN__CHKSTK:   return "ARMISD:::WIN__CHKSTK";
1066
1067   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1068   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1069   case ARMISD::VCGE:          return "ARMISD::VCGE";
1070   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1071   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1072   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1073   case ARMISD::VCGT:          return "ARMISD::VCGT";
1074   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1075   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1076   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1077   case ARMISD::VTST:          return "ARMISD::VTST";
1078
1079   case ARMISD::VSHL:          return "ARMISD::VSHL";
1080   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1081   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1082   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1083   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1084   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1085   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1086   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1087   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1088   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1089   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1090   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1091   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1092   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1093   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1094   case ARMISD::VSLI:          return "ARMISD::VSLI";
1095   case ARMISD::VSRI:          return "ARMISD::VSRI";
1096   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1097   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1098   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1099   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1100   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1101   case ARMISD::VDUP:          return "ARMISD::VDUP";
1102   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1103   case ARMISD::VEXT:          return "ARMISD::VEXT";
1104   case ARMISD::VREV64:        return "ARMISD::VREV64";
1105   case ARMISD::VREV32:        return "ARMISD::VREV32";
1106   case ARMISD::VREV16:        return "ARMISD::VREV16";
1107   case ARMISD::VZIP:          return "ARMISD::VZIP";
1108   case ARMISD::VUZP:          return "ARMISD::VUZP";
1109   case ARMISD::VTRN:          return "ARMISD::VTRN";
1110   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1111   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1112   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1113   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1114   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1115   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1116   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1117   case ARMISD::FMAX:          return "ARMISD::FMAX";
1118   case ARMISD::FMIN:          return "ARMISD::FMIN";
1119   case ARMISD::VMAXNM:        return "ARMISD::VMAX";
1120   case ARMISD::VMINNM:        return "ARMISD::VMIN";
1121   case ARMISD::BFI:           return "ARMISD::BFI";
1122   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1123   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1124   case ARMISD::VBSL:          return "ARMISD::VBSL";
1125   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1126   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1127   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1128   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1129   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1130   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1131   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1132   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1133   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1134   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1135   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1136   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1137   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1138   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1139   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1140   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1141   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1142   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1143   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1144   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1145   }
1146   return nullptr;
1147 }
1148
1149 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1150   if (!VT.isVector()) return getPointerTy();
1151   return VT.changeVectorElementTypeToInteger();
1152 }
1153
1154 /// getRegClassFor - Return the register class that should be used for the
1155 /// specified value type.
1156 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1157   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1158   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1159   // load / store 4 to 8 consecutive D registers.
1160   if (Subtarget->hasNEON()) {
1161     if (VT == MVT::v4i64)
1162       return &ARM::QQPRRegClass;
1163     if (VT == MVT::v8i64)
1164       return &ARM::QQQQPRRegClass;
1165   }
1166   return TargetLowering::getRegClassFor(VT);
1167 }
1168
1169 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1170 // source/dest is aligned and the copy size is large enough. We therefore want
1171 // to align such objects passed to memory intrinsics.
1172 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1173                                                unsigned &PrefAlign) const {
1174   if (!isa<MemIntrinsic>(CI))
1175     return false;
1176   MinSize = 8;
1177   // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1178   // cycle faster than 4-byte aligned LDM.
1179   PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1180   return true;
1181 }
1182
1183 // Create a fast isel object.
1184 FastISel *
1185 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1186                                   const TargetLibraryInfo *libInfo) const {
1187   return ARM::createFastISel(funcInfo, libInfo);
1188 }
1189
1190 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1191   unsigned NumVals = N->getNumValues();
1192   if (!NumVals)
1193     return Sched::RegPressure;
1194
1195   for (unsigned i = 0; i != NumVals; ++i) {
1196     EVT VT = N->getValueType(i);
1197     if (VT == MVT::Glue || VT == MVT::Other)
1198       continue;
1199     if (VT.isFloatingPoint() || VT.isVector())
1200       return Sched::ILP;
1201   }
1202
1203   if (!N->isMachineOpcode())
1204     return Sched::RegPressure;
1205
1206   // Load are scheduled for latency even if there instruction itinerary
1207   // is not available.
1208   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1209   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1210
1211   if (MCID.getNumDefs() == 0)
1212     return Sched::RegPressure;
1213   if (!Itins->isEmpty() &&
1214       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1215     return Sched::ILP;
1216
1217   return Sched::RegPressure;
1218 }
1219
1220 //===----------------------------------------------------------------------===//
1221 // Lowering Code
1222 //===----------------------------------------------------------------------===//
1223
1224 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1225 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1226   switch (CC) {
1227   default: llvm_unreachable("Unknown condition code!");
1228   case ISD::SETNE:  return ARMCC::NE;
1229   case ISD::SETEQ:  return ARMCC::EQ;
1230   case ISD::SETGT:  return ARMCC::GT;
1231   case ISD::SETGE:  return ARMCC::GE;
1232   case ISD::SETLT:  return ARMCC::LT;
1233   case ISD::SETLE:  return ARMCC::LE;
1234   case ISD::SETUGT: return ARMCC::HI;
1235   case ISD::SETUGE: return ARMCC::HS;
1236   case ISD::SETULT: return ARMCC::LO;
1237   case ISD::SETULE: return ARMCC::LS;
1238   }
1239 }
1240
1241 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1242 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1243                         ARMCC::CondCodes &CondCode2) {
1244   CondCode2 = ARMCC::AL;
1245   switch (CC) {
1246   default: llvm_unreachable("Unknown FP condition!");
1247   case ISD::SETEQ:
1248   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1249   case ISD::SETGT:
1250   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1251   case ISD::SETGE:
1252   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1253   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1254   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1255   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1256   case ISD::SETO:   CondCode = ARMCC::VC; break;
1257   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1258   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1259   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1260   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1261   case ISD::SETLT:
1262   case ISD::SETULT: CondCode = ARMCC::LT; break;
1263   case ISD::SETLE:
1264   case ISD::SETULE: CondCode = ARMCC::LE; break;
1265   case ISD::SETNE:
1266   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1267   }
1268 }
1269
1270 //===----------------------------------------------------------------------===//
1271 //                      Calling Convention Implementation
1272 //===----------------------------------------------------------------------===//
1273
1274 #include "ARMGenCallingConv.inc"
1275
1276 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1277 /// account presence of floating point hardware and calling convention
1278 /// limitations, such as support for variadic functions.
1279 CallingConv::ID
1280 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1281                                            bool isVarArg) const {
1282   switch (CC) {
1283   default:
1284     llvm_unreachable("Unsupported calling convention");
1285   case CallingConv::ARM_AAPCS:
1286   case CallingConv::ARM_APCS:
1287   case CallingConv::GHC:
1288     return CC;
1289   case CallingConv::ARM_AAPCS_VFP:
1290     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1291   case CallingConv::C:
1292     if (!Subtarget->isAAPCS_ABI())
1293       return CallingConv::ARM_APCS;
1294     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1295              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1296              !isVarArg)
1297       return CallingConv::ARM_AAPCS_VFP;
1298     else
1299       return CallingConv::ARM_AAPCS;
1300   case CallingConv::Fast:
1301     if (!Subtarget->isAAPCS_ABI()) {
1302       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1303         return CallingConv::Fast;
1304       return CallingConv::ARM_APCS;
1305     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1306       return CallingConv::ARM_AAPCS_VFP;
1307     else
1308       return CallingConv::ARM_AAPCS;
1309   }
1310 }
1311
1312 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1313 /// CallingConvention.
1314 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1315                                                  bool Return,
1316                                                  bool isVarArg) const {
1317   switch (getEffectiveCallingConv(CC, isVarArg)) {
1318   default:
1319     llvm_unreachable("Unsupported calling convention");
1320   case CallingConv::ARM_APCS:
1321     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1322   case CallingConv::ARM_AAPCS:
1323     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1324   case CallingConv::ARM_AAPCS_VFP:
1325     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1326   case CallingConv::Fast:
1327     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1328   case CallingConv::GHC:
1329     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1330   }
1331 }
1332
1333 /// LowerCallResult - Lower the result values of a call into the
1334 /// appropriate copies out of appropriate physical registers.
1335 SDValue
1336 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1337                                    CallingConv::ID CallConv, bool isVarArg,
1338                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1339                                    SDLoc dl, SelectionDAG &DAG,
1340                                    SmallVectorImpl<SDValue> &InVals,
1341                                    bool isThisReturn, SDValue ThisVal) const {
1342
1343   // Assign locations to each value returned by this call.
1344   SmallVector<CCValAssign, 16> RVLocs;
1345   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1346                     *DAG.getContext(), Call);
1347   CCInfo.AnalyzeCallResult(Ins,
1348                            CCAssignFnForNode(CallConv, /* Return*/ true,
1349                                              isVarArg));
1350
1351   // Copy all of the result registers out of their specified physreg.
1352   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1353     CCValAssign VA = RVLocs[i];
1354
1355     // Pass 'this' value directly from the argument to return value, to avoid
1356     // reg unit interference
1357     if (i == 0 && isThisReturn) {
1358       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1359              "unexpected return calling convention register assignment");
1360       InVals.push_back(ThisVal);
1361       continue;
1362     }
1363
1364     SDValue Val;
1365     if (VA.needsCustom()) {
1366       // Handle f64 or half of a v2f64.
1367       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1368                                       InFlag);
1369       Chain = Lo.getValue(1);
1370       InFlag = Lo.getValue(2);
1371       VA = RVLocs[++i]; // skip ahead to next loc
1372       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1373                                       InFlag);
1374       Chain = Hi.getValue(1);
1375       InFlag = Hi.getValue(2);
1376       if (!Subtarget->isLittle())
1377         std::swap (Lo, Hi);
1378       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1379
1380       if (VA.getLocVT() == MVT::v2f64) {
1381         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1382         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1383                           DAG.getConstant(0, dl, MVT::i32));
1384
1385         VA = RVLocs[++i]; // skip ahead to next loc
1386         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1387         Chain = Lo.getValue(1);
1388         InFlag = Lo.getValue(2);
1389         VA = RVLocs[++i]; // skip ahead to next loc
1390         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1391         Chain = Hi.getValue(1);
1392         InFlag = Hi.getValue(2);
1393         if (!Subtarget->isLittle())
1394           std::swap (Lo, Hi);
1395         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1396         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1397                           DAG.getConstant(1, dl, MVT::i32));
1398       }
1399     } else {
1400       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1401                                InFlag);
1402       Chain = Val.getValue(1);
1403       InFlag = Val.getValue(2);
1404     }
1405
1406     switch (VA.getLocInfo()) {
1407     default: llvm_unreachable("Unknown loc info!");
1408     case CCValAssign::Full: break;
1409     case CCValAssign::BCvt:
1410       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1411       break;
1412     }
1413
1414     InVals.push_back(Val);
1415   }
1416
1417   return Chain;
1418 }
1419
1420 /// LowerMemOpCallTo - Store the argument to the stack.
1421 SDValue
1422 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1423                                     SDValue StackPtr, SDValue Arg,
1424                                     SDLoc dl, SelectionDAG &DAG,
1425                                     const CCValAssign &VA,
1426                                     ISD::ArgFlagsTy Flags) const {
1427   unsigned LocMemOffset = VA.getLocMemOffset();
1428   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1429   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1430   return DAG.getStore(Chain, dl, Arg, PtrOff,
1431                       MachinePointerInfo::getStack(LocMemOffset),
1432                       false, false, 0);
1433 }
1434
1435 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1436                                          SDValue Chain, SDValue &Arg,
1437                                          RegsToPassVector &RegsToPass,
1438                                          CCValAssign &VA, CCValAssign &NextVA,
1439                                          SDValue &StackPtr,
1440                                          SmallVectorImpl<SDValue> &MemOpChains,
1441                                          ISD::ArgFlagsTy Flags) const {
1442
1443   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1444                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1445   unsigned id = Subtarget->isLittle() ? 0 : 1;
1446   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1447
1448   if (NextVA.isRegLoc())
1449     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1450   else {
1451     assert(NextVA.isMemLoc());
1452     if (!StackPtr.getNode())
1453       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1454
1455     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1456                                            dl, DAG, NextVA,
1457                                            Flags));
1458   }
1459 }
1460
1461 /// LowerCall - Lowering a call into a callseq_start <-
1462 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1463 /// nodes.
1464 SDValue
1465 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1466                              SmallVectorImpl<SDValue> &InVals) const {
1467   SelectionDAG &DAG                     = CLI.DAG;
1468   SDLoc &dl                             = CLI.DL;
1469   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1470   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1471   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1472   SDValue Chain                         = CLI.Chain;
1473   SDValue Callee                        = CLI.Callee;
1474   bool &isTailCall                      = CLI.IsTailCall;
1475   CallingConv::ID CallConv              = CLI.CallConv;
1476   bool doesNotRet                       = CLI.DoesNotReturn;
1477   bool isVarArg                         = CLI.IsVarArg;
1478
1479   MachineFunction &MF = DAG.getMachineFunction();
1480   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1481   bool isThisReturn   = false;
1482   bool isSibCall      = false;
1483
1484   // Disable tail calls if they're not supported.
1485   if (!Subtarget->supportsTailCall() || MF.getTarget().Options.DisableTailCalls)
1486     isTailCall = false;
1487
1488   if (isTailCall) {
1489     // Check if it's really possible to do a tail call.
1490     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1491                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1492                                                    Outs, OutVals, Ins, DAG);
1493     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1494       report_fatal_error("failed to perform tail call elimination on a call "
1495                          "site marked musttail");
1496     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1497     // detected sibcalls.
1498     if (isTailCall) {
1499       ++NumTailCalls;
1500       isSibCall = true;
1501     }
1502   }
1503
1504   // Analyze operands of the call, assigning locations to each operand.
1505   SmallVector<CCValAssign, 16> ArgLocs;
1506   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1507                     *DAG.getContext(), Call);
1508   CCInfo.AnalyzeCallOperands(Outs,
1509                              CCAssignFnForNode(CallConv, /* Return*/ false,
1510                                                isVarArg));
1511
1512   // Get a count of how many bytes are to be pushed on the stack.
1513   unsigned NumBytes = CCInfo.getNextStackOffset();
1514
1515   // For tail calls, memory operands are available in our caller's stack.
1516   if (isSibCall)
1517     NumBytes = 0;
1518
1519   // Adjust the stack pointer for the new arguments...
1520   // These operations are automatically eliminated by the prolog/epilog pass
1521   if (!isSibCall)
1522     Chain = DAG.getCALLSEQ_START(Chain,
1523                                  DAG.getIntPtrConstant(NumBytes, dl, true), dl);
1524
1525   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1526
1527   RegsToPassVector RegsToPass;
1528   SmallVector<SDValue, 8> MemOpChains;
1529
1530   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1531   // of tail call optimization, arguments are handled later.
1532   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1533        i != e;
1534        ++i, ++realArgIdx) {
1535     CCValAssign &VA = ArgLocs[i];
1536     SDValue Arg = OutVals[realArgIdx];
1537     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1538     bool isByVal = Flags.isByVal();
1539
1540     // Promote the value if needed.
1541     switch (VA.getLocInfo()) {
1542     default: llvm_unreachable("Unknown loc info!");
1543     case CCValAssign::Full: break;
1544     case CCValAssign::SExt:
1545       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1546       break;
1547     case CCValAssign::ZExt:
1548       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1549       break;
1550     case CCValAssign::AExt:
1551       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1552       break;
1553     case CCValAssign::BCvt:
1554       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1555       break;
1556     }
1557
1558     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1559     if (VA.needsCustom()) {
1560       if (VA.getLocVT() == MVT::v2f64) {
1561         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1562                                   DAG.getConstant(0, dl, MVT::i32));
1563         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1564                                   DAG.getConstant(1, dl, MVT::i32));
1565
1566         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1567                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1568
1569         VA = ArgLocs[++i]; // skip ahead to next loc
1570         if (VA.isRegLoc()) {
1571           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1572                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1573         } else {
1574           assert(VA.isMemLoc());
1575
1576           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1577                                                  dl, DAG, VA, Flags));
1578         }
1579       } else {
1580         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1581                          StackPtr, MemOpChains, Flags);
1582       }
1583     } else if (VA.isRegLoc()) {
1584       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1585         assert(VA.getLocVT() == MVT::i32 &&
1586                "unexpected calling convention register assignment");
1587         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1588                "unexpected use of 'returned'");
1589         isThisReturn = true;
1590       }
1591       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1592     } else if (isByVal) {
1593       assert(VA.isMemLoc());
1594       unsigned offset = 0;
1595
1596       // True if this byval aggregate will be split between registers
1597       // and memory.
1598       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1599       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1600
1601       if (CurByValIdx < ByValArgsCount) {
1602
1603         unsigned RegBegin, RegEnd;
1604         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1605
1606         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1607         unsigned int i, j;
1608         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1609           SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1610           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1611           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1612                                      MachinePointerInfo(),
1613                                      false, false, false,
1614                                      DAG.InferPtrAlignment(AddArg));
1615           MemOpChains.push_back(Load.getValue(1));
1616           RegsToPass.push_back(std::make_pair(j, Load));
1617         }
1618
1619         // If parameter size outsides register area, "offset" value
1620         // helps us to calculate stack slot for remained part properly.
1621         offset = RegEnd - RegBegin;
1622
1623         CCInfo.nextInRegsParam();
1624       }
1625
1626       if (Flags.getByValSize() > 4*offset) {
1627         unsigned LocMemOffset = VA.getLocMemOffset();
1628         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1629         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1630                                   StkPtrOff);
1631         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1632         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1633         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1634                                            MVT::i32);
1635         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1636                                             MVT::i32);
1637
1638         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1639         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1640         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1641                                           Ops));
1642       }
1643     } else if (!isSibCall) {
1644       assert(VA.isMemLoc());
1645
1646       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1647                                              dl, DAG, VA, Flags));
1648     }
1649   }
1650
1651   if (!MemOpChains.empty())
1652     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1653
1654   // Build a sequence of copy-to-reg nodes chained together with token chain
1655   // and flag operands which copy the outgoing args into the appropriate regs.
1656   SDValue InFlag;
1657   // Tail call byval lowering might overwrite argument registers so in case of
1658   // tail call optimization the copies to registers are lowered later.
1659   if (!isTailCall)
1660     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1661       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1662                                RegsToPass[i].second, InFlag);
1663       InFlag = Chain.getValue(1);
1664     }
1665
1666   // For tail calls lower the arguments to the 'real' stack slot.
1667   if (isTailCall) {
1668     // Force all the incoming stack arguments to be loaded from the stack
1669     // before any new outgoing arguments are stored to the stack, because the
1670     // outgoing stack slots may alias the incoming argument stack slots, and
1671     // the alias isn't otherwise explicit. This is slightly more conservative
1672     // than necessary, because it means that each store effectively depends
1673     // on every argument instead of just those arguments it would clobber.
1674
1675     // Do not flag preceding copytoreg stuff together with the following stuff.
1676     InFlag = SDValue();
1677     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1678       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1679                                RegsToPass[i].second, InFlag);
1680       InFlag = Chain.getValue(1);
1681     }
1682     InFlag = SDValue();
1683   }
1684
1685   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1686   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1687   // node so that legalize doesn't hack it.
1688   bool isDirect = false;
1689   bool isARMFunc = false;
1690   bool isLocalARMFunc = false;
1691   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1692
1693   if (EnableARMLongCalls) {
1694     assert((Subtarget->isTargetWindows() ||
1695             getTargetMachine().getRelocationModel() == Reloc::Static) &&
1696            "long-calls with non-static relocation model!");
1697     // Handle a global address or an external symbol. If it's not one of
1698     // those, the target's already in a register, so we don't need to do
1699     // anything extra.
1700     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1701       const GlobalValue *GV = G->getGlobal();
1702       // Create a constant pool entry for the callee address
1703       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1704       ARMConstantPoolValue *CPV =
1705         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1706
1707       // Get the address of the callee into a register
1708       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1709       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1710       Callee = DAG.getLoad(getPointerTy(), dl,
1711                            DAG.getEntryNode(), CPAddr,
1712                            MachinePointerInfo::getConstantPool(),
1713                            false, false, false, 0);
1714     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1715       const char *Sym = S->getSymbol();
1716
1717       // Create a constant pool entry for the callee address
1718       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1719       ARMConstantPoolValue *CPV =
1720         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1721                                       ARMPCLabelIndex, 0);
1722       // Get the address of the callee into a register
1723       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1724       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1725       Callee = DAG.getLoad(getPointerTy(), dl,
1726                            DAG.getEntryNode(), CPAddr,
1727                            MachinePointerInfo::getConstantPool(),
1728                            false, false, false, 0);
1729     }
1730   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1731     const GlobalValue *GV = G->getGlobal();
1732     isDirect = true;
1733     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1734     bool isStub = (isExt && Subtarget->isTargetMachO()) &&
1735                    getTargetMachine().getRelocationModel() != Reloc::Static;
1736     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1737     // ARM call to a local ARM function is predicable.
1738     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1739     // tBX takes a register source operand.
1740     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1741       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1742       Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1743                            DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
1744                                                       0, ARMII::MO_NONLAZY));
1745       Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
1746                            MachinePointerInfo::getGOT(), false, false, true, 0);
1747     } else if (Subtarget->isTargetCOFF()) {
1748       assert(Subtarget->isTargetWindows() &&
1749              "Windows is the only supported COFF target");
1750       unsigned TargetFlags = GV->hasDLLImportStorageClass()
1751                                  ? ARMII::MO_DLLIMPORT
1752                                  : ARMII::MO_NO_FLAG;
1753       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), /*Offset=*/0,
1754                                           TargetFlags);
1755       if (GV->hasDLLImportStorageClass())
1756         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
1757                              DAG.getNode(ARMISD::Wrapper, dl, getPointerTy(),
1758                                          Callee), MachinePointerInfo::getGOT(),
1759                              false, false, false, 0);
1760     } else {
1761       // On ELF targets for PIC code, direct calls should go through the PLT
1762       unsigned OpFlags = 0;
1763       if (Subtarget->isTargetELF() &&
1764           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1765         OpFlags = ARMII::MO_PLT;
1766       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1767     }
1768   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1769     isDirect = true;
1770     bool isStub = Subtarget->isTargetMachO() &&
1771                   getTargetMachine().getRelocationModel() != Reloc::Static;
1772     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1773     // tBX takes a register source operand.
1774     const char *Sym = S->getSymbol();
1775     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1776       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1777       ARMConstantPoolValue *CPV =
1778         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1779                                       ARMPCLabelIndex, 4);
1780       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1781       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1782       Callee = DAG.getLoad(getPointerTy(), dl,
1783                            DAG.getEntryNode(), CPAddr,
1784                            MachinePointerInfo::getConstantPool(),
1785                            false, false, false, 0);
1786       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
1787       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1788                            getPointerTy(), Callee, PICLabel);
1789     } else {
1790       unsigned OpFlags = 0;
1791       // On ELF targets for PIC code, direct calls should go through the PLT
1792       if (Subtarget->isTargetELF() &&
1793                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1794         OpFlags = ARMII::MO_PLT;
1795       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1796     }
1797   }
1798
1799   // FIXME: handle tail calls differently.
1800   unsigned CallOpc;
1801   bool HasMinSizeAttr = MF.getFunction()->hasFnAttribute(Attribute::MinSize);
1802   if (Subtarget->isThumb()) {
1803     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1804       CallOpc = ARMISD::CALL_NOLINK;
1805     else
1806       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1807   } else {
1808     if (!isDirect && !Subtarget->hasV5TOps())
1809       CallOpc = ARMISD::CALL_NOLINK;
1810     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1811                // Emit regular call when code size is the priority
1812                !HasMinSizeAttr)
1813       // "mov lr, pc; b _foo" to avoid confusing the RSP
1814       CallOpc = ARMISD::CALL_NOLINK;
1815     else
1816       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1817   }
1818
1819   std::vector<SDValue> Ops;
1820   Ops.push_back(Chain);
1821   Ops.push_back(Callee);
1822
1823   // Add argument registers to the end of the list so that they are known live
1824   // into the call.
1825   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1826     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1827                                   RegsToPass[i].second.getValueType()));
1828
1829   // Add a register mask operand representing the call-preserved registers.
1830   if (!isTailCall) {
1831     const uint32_t *Mask;
1832     const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
1833     if (isThisReturn) {
1834       // For 'this' returns, use the R0-preserving mask if applicable
1835       Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
1836       if (!Mask) {
1837         // Set isThisReturn to false if the calling convention is not one that
1838         // allows 'returned' to be modeled in this way, so LowerCallResult does
1839         // not try to pass 'this' straight through
1840         isThisReturn = false;
1841         Mask = ARI->getCallPreservedMask(MF, CallConv);
1842       }
1843     } else
1844       Mask = ARI->getCallPreservedMask(MF, CallConv);
1845
1846     assert(Mask && "Missing call preserved mask for calling convention");
1847     Ops.push_back(DAG.getRegisterMask(Mask));
1848   }
1849
1850   if (InFlag.getNode())
1851     Ops.push_back(InFlag);
1852
1853   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1854   if (isTailCall) {
1855     MF.getFrameInfo()->setHasTailCall();
1856     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1857   }
1858
1859   // Returns a chain and a flag for retval copy to use.
1860   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1861   InFlag = Chain.getValue(1);
1862
1863   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
1864                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
1865   if (!Ins.empty())
1866     InFlag = Chain.getValue(1);
1867
1868   // Handle result values, copying them out of physregs into vregs that we
1869   // return.
1870   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1871                          InVals, isThisReturn,
1872                          isThisReturn ? OutVals[0] : SDValue());
1873 }
1874
1875 /// HandleByVal - Every parameter *after* a byval parameter is passed
1876 /// on the stack.  Remember the next parameter register to allocate,
1877 /// and then confiscate the rest of the parameter registers to insure
1878 /// this.
1879 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
1880                                     unsigned Align) const {
1881   assert((State->getCallOrPrologue() == Prologue ||
1882           State->getCallOrPrologue() == Call) &&
1883          "unhandled ParmContext");
1884
1885   // Byval (as with any stack) slots are always at least 4 byte aligned.
1886   Align = std::max(Align, 4U);
1887
1888   unsigned Reg = State->AllocateReg(GPRArgRegs);
1889   if (!Reg)
1890     return;
1891
1892   unsigned AlignInRegs = Align / 4;
1893   unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
1894   for (unsigned i = 0; i < Waste; ++i)
1895     Reg = State->AllocateReg(GPRArgRegs);
1896
1897   if (!Reg)
1898     return;
1899
1900   unsigned Excess = 4 * (ARM::R4 - Reg);
1901
1902   // Special case when NSAA != SP and parameter size greater than size of
1903   // all remained GPR regs. In that case we can't split parameter, we must
1904   // send it to stack. We also must set NCRN to R4, so waste all
1905   // remained registers.
1906   const unsigned NSAAOffset = State->getNextStackOffset();
1907   if (NSAAOffset != 0 && Size > Excess) {
1908     while (State->AllocateReg(GPRArgRegs))
1909       ;
1910     return;
1911   }
1912
1913   // First register for byval parameter is the first register that wasn't
1914   // allocated before this method call, so it would be "reg".
1915   // If parameter is small enough to be saved in range [reg, r4), then
1916   // the end (first after last) register would be reg + param-size-in-regs,
1917   // else parameter would be splitted between registers and stack,
1918   // end register would be r4 in this case.
1919   unsigned ByValRegBegin = Reg;
1920   unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
1921   State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1922   // Note, first register is allocated in the beginning of function already,
1923   // allocate remained amount of registers we need.
1924   for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
1925     State->AllocateReg(GPRArgRegs);
1926   // A byval parameter that is split between registers and memory needs its
1927   // size truncated here.
1928   // In the case where the entire structure fits in registers, we set the
1929   // size in memory to zero.
1930   Size = std::max<int>(Size - Excess, 0);
1931 }
1932
1933
1934 /// MatchingStackOffset - Return true if the given stack call argument is
1935 /// already available in the same position (relatively) of the caller's
1936 /// incoming argument stack.
1937 static
1938 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1939                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1940                          const TargetInstrInfo *TII) {
1941   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1942   int FI = INT_MAX;
1943   if (Arg.getOpcode() == ISD::CopyFromReg) {
1944     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1945     if (!TargetRegisterInfo::isVirtualRegister(VR))
1946       return false;
1947     MachineInstr *Def = MRI->getVRegDef(VR);
1948     if (!Def)
1949       return false;
1950     if (!Flags.isByVal()) {
1951       if (!TII->isLoadFromStackSlot(Def, FI))
1952         return false;
1953     } else {
1954       return false;
1955     }
1956   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1957     if (Flags.isByVal())
1958       // ByVal argument is passed in as a pointer but it's now being
1959       // dereferenced. e.g.
1960       // define @foo(%struct.X* %A) {
1961       //   tail call @bar(%struct.X* byval %A)
1962       // }
1963       return false;
1964     SDValue Ptr = Ld->getBasePtr();
1965     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1966     if (!FINode)
1967       return false;
1968     FI = FINode->getIndex();
1969   } else
1970     return false;
1971
1972   assert(FI != INT_MAX);
1973   if (!MFI->isFixedObjectIndex(FI))
1974     return false;
1975   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1976 }
1977
1978 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1979 /// for tail call optimization. Targets which want to do tail call
1980 /// optimization should implement this function.
1981 bool
1982 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1983                                                      CallingConv::ID CalleeCC,
1984                                                      bool isVarArg,
1985                                                      bool isCalleeStructRet,
1986                                                      bool isCallerStructRet,
1987                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1988                                     const SmallVectorImpl<SDValue> &OutVals,
1989                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1990                                                      SelectionDAG& DAG) const {
1991   const Function *CallerF = DAG.getMachineFunction().getFunction();
1992   CallingConv::ID CallerCC = CallerF->getCallingConv();
1993   bool CCMatch = CallerCC == CalleeCC;
1994
1995   // Look for obvious safe cases to perform tail call optimization that do not
1996   // require ABI changes. This is what gcc calls sibcall.
1997
1998   // Do not sibcall optimize vararg calls unless the call site is not passing
1999   // any arguments.
2000   if (isVarArg && !Outs.empty())
2001     return false;
2002
2003   // Exception-handling functions need a special set of instructions to indicate
2004   // a return to the hardware. Tail-calling another function would probably
2005   // break this.
2006   if (CallerF->hasFnAttribute("interrupt"))
2007     return false;
2008
2009   // Also avoid sibcall optimization if either caller or callee uses struct
2010   // return semantics.
2011   if (isCalleeStructRet || isCallerStructRet)
2012     return false;
2013
2014   // FIXME: Completely disable sibcall for Thumb1 since ThumbRegisterInfo::
2015   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
2016   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
2017   // support in the assembler and linker to be used. This would need to be
2018   // fixed to fully support tail calls in Thumb1.
2019   //
2020   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
2021   // LR.  This means if we need to reload LR, it takes an extra instructions,
2022   // which outweighs the value of the tail call; but here we don't know yet
2023   // whether LR is going to be used.  Probably the right approach is to
2024   // generate the tail call here and turn it back into CALL/RET in
2025   // emitEpilogue if LR is used.
2026
2027   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
2028   // but we need to make sure there are enough registers; the only valid
2029   // registers are the 4 used for parameters.  We don't currently do this
2030   // case.
2031   if (Subtarget->isThumb1Only())
2032     return false;
2033
2034   // Externally-defined functions with weak linkage should not be
2035   // tail-called on ARM when the OS does not support dynamic
2036   // pre-emption of symbols, as the AAELF spec requires normal calls
2037   // to undefined weak functions to be replaced with a NOP or jump to the
2038   // next instruction. The behaviour of branch instructions in this
2039   // situation (as used for tail calls) is implementation-defined, so we
2040   // cannot rely on the linker replacing the tail call with a return.
2041   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2042     const GlobalValue *GV = G->getGlobal();
2043     const Triple TT(getTargetMachine().getTargetTriple());
2044     if (GV->hasExternalWeakLinkage() &&
2045         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2046       return false;
2047   }
2048
2049   // If the calling conventions do not match, then we'd better make sure the
2050   // results are returned in the same way as what the caller expects.
2051   if (!CCMatch) {
2052     SmallVector<CCValAssign, 16> RVLocs1;
2053     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2054                        *DAG.getContext(), Call);
2055     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2056
2057     SmallVector<CCValAssign, 16> RVLocs2;
2058     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2059                        *DAG.getContext(), Call);
2060     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2061
2062     if (RVLocs1.size() != RVLocs2.size())
2063       return false;
2064     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2065       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2066         return false;
2067       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2068         return false;
2069       if (RVLocs1[i].isRegLoc()) {
2070         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2071           return false;
2072       } else {
2073         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2074           return false;
2075       }
2076     }
2077   }
2078
2079   // If Caller's vararg or byval argument has been split between registers and
2080   // stack, do not perform tail call, since part of the argument is in caller's
2081   // local frame.
2082   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2083                                       getInfo<ARMFunctionInfo>();
2084   if (AFI_Caller->getArgRegsSaveSize())
2085     return false;
2086
2087   // If the callee takes no arguments then go on to check the results of the
2088   // call.
2089   if (!Outs.empty()) {
2090     // Check if stack adjustment is needed. For now, do not do this if any
2091     // argument is passed on the stack.
2092     SmallVector<CCValAssign, 16> ArgLocs;
2093     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2094                       *DAG.getContext(), Call);
2095     CCInfo.AnalyzeCallOperands(Outs,
2096                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2097     if (CCInfo.getNextStackOffset()) {
2098       MachineFunction &MF = DAG.getMachineFunction();
2099
2100       // Check if the arguments are already laid out in the right way as
2101       // the caller's fixed stack objects.
2102       MachineFrameInfo *MFI = MF.getFrameInfo();
2103       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2104       const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2105       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2106            i != e;
2107            ++i, ++realArgIdx) {
2108         CCValAssign &VA = ArgLocs[i];
2109         EVT RegVT = VA.getLocVT();
2110         SDValue Arg = OutVals[realArgIdx];
2111         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2112         if (VA.getLocInfo() == CCValAssign::Indirect)
2113           return false;
2114         if (VA.needsCustom()) {
2115           // f64 and vector types are split into multiple registers or
2116           // register/stack-slot combinations.  The types will not match
2117           // the registers; give up on memory f64 refs until we figure
2118           // out what to do about this.
2119           if (!VA.isRegLoc())
2120             return false;
2121           if (!ArgLocs[++i].isRegLoc())
2122             return false;
2123           if (RegVT == MVT::v2f64) {
2124             if (!ArgLocs[++i].isRegLoc())
2125               return false;
2126             if (!ArgLocs[++i].isRegLoc())
2127               return false;
2128           }
2129         } else if (!VA.isRegLoc()) {
2130           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2131                                    MFI, MRI, TII))
2132             return false;
2133         }
2134       }
2135     }
2136   }
2137
2138   return true;
2139 }
2140
2141 bool
2142 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2143                                   MachineFunction &MF, bool isVarArg,
2144                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2145                                   LLVMContext &Context) const {
2146   SmallVector<CCValAssign, 16> RVLocs;
2147   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2148   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2149                                                     isVarArg));
2150 }
2151
2152 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2153                                     SDLoc DL, SelectionDAG &DAG) {
2154   const MachineFunction &MF = DAG.getMachineFunction();
2155   const Function *F = MF.getFunction();
2156
2157   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2158
2159   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2160   // version of the "preferred return address". These offsets affect the return
2161   // instruction if this is a return from PL1 without hypervisor extensions.
2162   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2163   //    SWI:     0      "subs pc, lr, #0"
2164   //    ABORT:   +4     "subs pc, lr, #4"
2165   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2166   // UNDEF varies depending on where the exception came from ARM or Thumb
2167   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2168
2169   int64_t LROffset;
2170   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2171       IntKind == "ABORT")
2172     LROffset = 4;
2173   else if (IntKind == "SWI" || IntKind == "UNDEF")
2174     LROffset = 0;
2175   else
2176     report_fatal_error("Unsupported interrupt attribute. If present, value "
2177                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2178
2179   RetOps.insert(RetOps.begin() + 1,
2180                 DAG.getConstant(LROffset, DL, MVT::i32, false));
2181
2182   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2183 }
2184
2185 SDValue
2186 ARMTargetLowering::LowerReturn(SDValue Chain,
2187                                CallingConv::ID CallConv, bool isVarArg,
2188                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2189                                const SmallVectorImpl<SDValue> &OutVals,
2190                                SDLoc dl, SelectionDAG &DAG) const {
2191
2192   // CCValAssign - represent the assignment of the return value to a location.
2193   SmallVector<CCValAssign, 16> RVLocs;
2194
2195   // CCState - Info about the registers and stack slots.
2196   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2197                     *DAG.getContext(), Call);
2198
2199   // Analyze outgoing return values.
2200   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2201                                                isVarArg));
2202
2203   SDValue Flag;
2204   SmallVector<SDValue, 4> RetOps;
2205   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2206   bool isLittleEndian = Subtarget->isLittle();
2207
2208   MachineFunction &MF = DAG.getMachineFunction();
2209   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2210   AFI->setReturnRegsCount(RVLocs.size());
2211
2212   // Copy the result values into the output registers.
2213   for (unsigned i = 0, realRVLocIdx = 0;
2214        i != RVLocs.size();
2215        ++i, ++realRVLocIdx) {
2216     CCValAssign &VA = RVLocs[i];
2217     assert(VA.isRegLoc() && "Can only return in registers!");
2218
2219     SDValue Arg = OutVals[realRVLocIdx];
2220
2221     switch (VA.getLocInfo()) {
2222     default: llvm_unreachable("Unknown loc info!");
2223     case CCValAssign::Full: break;
2224     case CCValAssign::BCvt:
2225       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2226       break;
2227     }
2228
2229     if (VA.needsCustom()) {
2230       if (VA.getLocVT() == MVT::v2f64) {
2231         // Extract the first half and return it in two registers.
2232         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2233                                    DAG.getConstant(0, dl, MVT::i32));
2234         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2235                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2236
2237         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2238                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2239                                  Flag);
2240         Flag = Chain.getValue(1);
2241         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2242         VA = RVLocs[++i]; // skip ahead to next loc
2243         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2244                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2245                                  Flag);
2246         Flag = Chain.getValue(1);
2247         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2248         VA = RVLocs[++i]; // skip ahead to next loc
2249
2250         // Extract the 2nd half and fall through to handle it as an f64 value.
2251         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2252                           DAG.getConstant(1, dl, MVT::i32));
2253       }
2254       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2255       // available.
2256       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2257                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2258       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2259                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2260                                Flag);
2261       Flag = Chain.getValue(1);
2262       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2263       VA = RVLocs[++i]; // skip ahead to next loc
2264       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2265                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2266                                Flag);
2267     } else
2268       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2269
2270     // Guarantee that all emitted copies are
2271     // stuck together, avoiding something bad.
2272     Flag = Chain.getValue(1);
2273     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2274   }
2275
2276   // Update chain and glue.
2277   RetOps[0] = Chain;
2278   if (Flag.getNode())
2279     RetOps.push_back(Flag);
2280
2281   // CPUs which aren't M-class use a special sequence to return from
2282   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2283   // though we use "subs pc, lr, #N").
2284   //
2285   // M-class CPUs actually use a normal return sequence with a special
2286   // (hardware-provided) value in LR, so the normal code path works.
2287   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2288       !Subtarget->isMClass()) {
2289     if (Subtarget->isThumb1Only())
2290       report_fatal_error("interrupt attribute is not supported in Thumb1");
2291     return LowerInterruptReturn(RetOps, dl, DAG);
2292   }
2293
2294   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2295 }
2296
2297 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2298   if (N->getNumValues() != 1)
2299     return false;
2300   if (!N->hasNUsesOfValue(1, 0))
2301     return false;
2302
2303   SDValue TCChain = Chain;
2304   SDNode *Copy = *N->use_begin();
2305   if (Copy->getOpcode() == ISD::CopyToReg) {
2306     // If the copy has a glue operand, we conservatively assume it isn't safe to
2307     // perform a tail call.
2308     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2309       return false;
2310     TCChain = Copy->getOperand(0);
2311   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2312     SDNode *VMov = Copy;
2313     // f64 returned in a pair of GPRs.
2314     SmallPtrSet<SDNode*, 2> Copies;
2315     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2316          UI != UE; ++UI) {
2317       if (UI->getOpcode() != ISD::CopyToReg)
2318         return false;
2319       Copies.insert(*UI);
2320     }
2321     if (Copies.size() > 2)
2322       return false;
2323
2324     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2325          UI != UE; ++UI) {
2326       SDValue UseChain = UI->getOperand(0);
2327       if (Copies.count(UseChain.getNode()))
2328         // Second CopyToReg
2329         Copy = *UI;
2330       else {
2331         // We are at the top of this chain.
2332         // If the copy has a glue operand, we conservatively assume it
2333         // isn't safe to perform a tail call.
2334         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2335           return false;
2336         // First CopyToReg
2337         TCChain = UseChain;
2338       }
2339     }
2340   } else if (Copy->getOpcode() == ISD::BITCAST) {
2341     // f32 returned in a single GPR.
2342     if (!Copy->hasOneUse())
2343       return false;
2344     Copy = *Copy->use_begin();
2345     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2346       return false;
2347     // If the copy has a glue operand, we conservatively assume it isn't safe to
2348     // perform a tail call.
2349     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2350       return false;
2351     TCChain = Copy->getOperand(0);
2352   } else {
2353     return false;
2354   }
2355
2356   bool HasRet = false;
2357   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2358        UI != UE; ++UI) {
2359     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2360         UI->getOpcode() != ARMISD::INTRET_FLAG)
2361       return false;
2362     HasRet = true;
2363   }
2364
2365   if (!HasRet)
2366     return false;
2367
2368   Chain = TCChain;
2369   return true;
2370 }
2371
2372 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2373   if (!Subtarget->supportsTailCall())
2374     return false;
2375
2376   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2377     return false;
2378
2379   return !Subtarget->isThumb1Only();
2380 }
2381
2382 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2383 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2384 // one of the above mentioned nodes. It has to be wrapped because otherwise
2385 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2386 // be used to form addressing mode. These wrapped nodes will be selected
2387 // into MOVi.
2388 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2389   EVT PtrVT = Op.getValueType();
2390   // FIXME there is no actual debug info here
2391   SDLoc dl(Op);
2392   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2393   SDValue Res;
2394   if (CP->isMachineConstantPoolEntry())
2395     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2396                                     CP->getAlignment());
2397   else
2398     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2399                                     CP->getAlignment());
2400   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2401 }
2402
2403 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2404   return MachineJumpTableInfo::EK_Inline;
2405 }
2406
2407 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2408                                              SelectionDAG &DAG) const {
2409   MachineFunction &MF = DAG.getMachineFunction();
2410   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2411   unsigned ARMPCLabelIndex = 0;
2412   SDLoc DL(Op);
2413   EVT PtrVT = getPointerTy();
2414   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2415   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2416   SDValue CPAddr;
2417   if (RelocM == Reloc::Static) {
2418     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2419   } else {
2420     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2421     ARMPCLabelIndex = AFI->createPICLabelUId();
2422     ARMConstantPoolValue *CPV =
2423       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2424                                       ARMCP::CPBlockAddress, PCAdj);
2425     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2426   }
2427   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2428   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2429                                MachinePointerInfo::getConstantPool(),
2430                                false, false, false, 0);
2431   if (RelocM == Reloc::Static)
2432     return Result;
2433   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2434   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2435 }
2436
2437 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2438 SDValue
2439 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2440                                                  SelectionDAG &DAG) const {
2441   SDLoc dl(GA);
2442   EVT PtrVT = getPointerTy();
2443   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2444   MachineFunction &MF = DAG.getMachineFunction();
2445   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2446   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2447   ARMConstantPoolValue *CPV =
2448     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2449                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2450   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2451   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2452   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2453                          MachinePointerInfo::getConstantPool(),
2454                          false, false, false, 0);
2455   SDValue Chain = Argument.getValue(1);
2456
2457   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2458   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2459
2460   // call __tls_get_addr.
2461   ArgListTy Args;
2462   ArgListEntry Entry;
2463   Entry.Node = Argument;
2464   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2465   Args.push_back(Entry);
2466
2467   // FIXME: is there useful debug info available here?
2468   TargetLowering::CallLoweringInfo CLI(DAG);
2469   CLI.setDebugLoc(dl).setChain(Chain)
2470     .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2471                DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2472                0);
2473
2474   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2475   return CallResult.first;
2476 }
2477
2478 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2479 // "local exec" model.
2480 SDValue
2481 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2482                                         SelectionDAG &DAG,
2483                                         TLSModel::Model model) const {
2484   const GlobalValue *GV = GA->getGlobal();
2485   SDLoc dl(GA);
2486   SDValue Offset;
2487   SDValue Chain = DAG.getEntryNode();
2488   EVT PtrVT = getPointerTy();
2489   // Get the Thread Pointer
2490   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2491
2492   if (model == TLSModel::InitialExec) {
2493     MachineFunction &MF = DAG.getMachineFunction();
2494     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2495     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2496     // Initial exec model.
2497     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2498     ARMConstantPoolValue *CPV =
2499       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2500                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2501                                       true);
2502     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2503     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2504     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2505                          MachinePointerInfo::getConstantPool(),
2506                          false, false, false, 0);
2507     Chain = Offset.getValue(1);
2508
2509     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2510     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2511
2512     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2513                          MachinePointerInfo::getConstantPool(),
2514                          false, false, false, 0);
2515   } else {
2516     // local exec model
2517     assert(model == TLSModel::LocalExec);
2518     ARMConstantPoolValue *CPV =
2519       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2520     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2521     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2522     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2523                          MachinePointerInfo::getConstantPool(),
2524                          false, false, false, 0);
2525   }
2526
2527   // The address of the thread local variable is the add of the thread
2528   // pointer with the offset of the variable.
2529   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2530 }
2531
2532 SDValue
2533 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2534   // TODO: implement the "local dynamic" model
2535   assert(Subtarget->isTargetELF() &&
2536          "TLS not implemented for non-ELF targets");
2537   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2538
2539   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2540
2541   switch (model) {
2542     case TLSModel::GeneralDynamic:
2543     case TLSModel::LocalDynamic:
2544       return LowerToTLSGeneralDynamicModel(GA, DAG);
2545     case TLSModel::InitialExec:
2546     case TLSModel::LocalExec:
2547       return LowerToTLSExecModels(GA, DAG, model);
2548   }
2549   llvm_unreachable("bogus TLS model");
2550 }
2551
2552 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2553                                                  SelectionDAG &DAG) const {
2554   EVT PtrVT = getPointerTy();
2555   SDLoc dl(Op);
2556   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2557   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2558     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2559     ARMConstantPoolValue *CPV =
2560       ARMConstantPoolConstant::Create(GV,
2561                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2562     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2563     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2564     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2565                                  CPAddr,
2566                                  MachinePointerInfo::getConstantPool(),
2567                                  false, false, false, 0);
2568     SDValue Chain = Result.getValue(1);
2569     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2570     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2571     if (!UseGOTOFF)
2572       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2573                            MachinePointerInfo::getGOT(),
2574                            false, false, false, 0);
2575     return Result;
2576   }
2577
2578   // If we have T2 ops, we can materialize the address directly via movt/movw
2579   // pair. This is always cheaper.
2580   if (Subtarget->useMovt(DAG.getMachineFunction())) {
2581     ++NumMovwMovt;
2582     // FIXME: Once remat is capable of dealing with instructions with register
2583     // operands, expand this into two nodes.
2584     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2585                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2586   } else {
2587     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2588     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2589     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2590                        MachinePointerInfo::getConstantPool(),
2591                        false, false, false, 0);
2592   }
2593 }
2594
2595 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2596                                                     SelectionDAG &DAG) const {
2597   EVT PtrVT = getPointerTy();
2598   SDLoc dl(Op);
2599   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2600   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2601
2602   if (Subtarget->useMovt(DAG.getMachineFunction()))
2603     ++NumMovwMovt;
2604
2605   // FIXME: Once remat is capable of dealing with instructions with register
2606   // operands, expand this into multiple nodes
2607   unsigned Wrapper =
2608       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2609
2610   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2611   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2612
2613   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2614     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2615                          MachinePointerInfo::getGOT(), false, false, false, 0);
2616   return Result;
2617 }
2618
2619 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2620                                                      SelectionDAG &DAG) const {
2621   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2622   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2623          "Windows on ARM expects to use movw/movt");
2624
2625   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2626   const ARMII::TOF TargetFlags =
2627     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2628   EVT PtrVT = getPointerTy();
2629   SDValue Result;
2630   SDLoc DL(Op);
2631
2632   ++NumMovwMovt;
2633
2634   // FIXME: Once remat is capable of dealing with instructions with register
2635   // operands, expand this into two nodes.
2636   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2637                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2638                                                   TargetFlags));
2639   if (GV->hasDLLImportStorageClass())
2640     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2641                          MachinePointerInfo::getGOT(), false, false, false, 0);
2642   return Result;
2643 }
2644
2645 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2646                                                     SelectionDAG &DAG) const {
2647   assert(Subtarget->isTargetELF() &&
2648          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2649   MachineFunction &MF = DAG.getMachineFunction();
2650   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2651   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2652   EVT PtrVT = getPointerTy();
2653   SDLoc dl(Op);
2654   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2655   ARMConstantPoolValue *CPV =
2656     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2657                                   ARMPCLabelIndex, PCAdj);
2658   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2659   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2660   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2661                                MachinePointerInfo::getConstantPool(),
2662                                false, false, false, 0);
2663   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2664   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2665 }
2666
2667 SDValue
2668 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2669   SDLoc dl(Op);
2670   SDValue Val = DAG.getConstant(0, dl, MVT::i32);
2671   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2672                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2673                      Op.getOperand(1), Val);
2674 }
2675
2676 SDValue
2677 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2678   SDLoc dl(Op);
2679   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2680                      Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
2681 }
2682
2683 SDValue
2684 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2685                                           const ARMSubtarget *Subtarget) const {
2686   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2687   SDLoc dl(Op);
2688   switch (IntNo) {
2689   default: return SDValue();    // Don't custom lower most intrinsics.
2690   case Intrinsic::arm_rbit: {
2691     assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2692            "RBIT intrinsic must have i32 type!");
2693     return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1));
2694   }
2695   case Intrinsic::arm_thread_pointer: {
2696     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2697     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2698   }
2699   case Intrinsic::eh_sjlj_lsda: {
2700     MachineFunction &MF = DAG.getMachineFunction();
2701     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2702     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2703     EVT PtrVT = getPointerTy();
2704     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2705     SDValue CPAddr;
2706     unsigned PCAdj = (RelocM != Reloc::PIC_)
2707       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2708     ARMConstantPoolValue *CPV =
2709       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2710                                       ARMCP::CPLSDA, PCAdj);
2711     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2712     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2713     SDValue Result =
2714       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2715                   MachinePointerInfo::getConstantPool(),
2716                   false, false, false, 0);
2717
2718     if (RelocM == Reloc::PIC_) {
2719       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2720       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2721     }
2722     return Result;
2723   }
2724   case Intrinsic::arm_neon_vmulls:
2725   case Intrinsic::arm_neon_vmullu: {
2726     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2727       ? ARMISD::VMULLs : ARMISD::VMULLu;
2728     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2729                        Op.getOperand(1), Op.getOperand(2));
2730   }
2731   }
2732 }
2733
2734 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2735                                  const ARMSubtarget *Subtarget) {
2736   // FIXME: handle "fence singlethread" more efficiently.
2737   SDLoc dl(Op);
2738   if (!Subtarget->hasDataBarrier()) {
2739     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2740     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2741     // here.
2742     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2743            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2744     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2745                        DAG.getConstant(0, dl, MVT::i32));
2746   }
2747
2748   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2749   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2750   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
2751   if (Subtarget->isMClass()) {
2752     // Only a full system barrier exists in the M-class architectures.
2753     Domain = ARM_MB::SY;
2754   } else if (Subtarget->isSwift() && Ord == Release) {
2755     // Swift happens to implement ISHST barriers in a way that's compatible with
2756     // Release semantics but weaker than ISH so we'd be fools not to use
2757     // it. Beware: other processors probably don't!
2758     Domain = ARM_MB::ISHST;
2759   }
2760
2761   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2762                      DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
2763                      DAG.getConstant(Domain, dl, MVT::i32));
2764 }
2765
2766 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2767                              const ARMSubtarget *Subtarget) {
2768   // ARM pre v5TE and Thumb1 does not have preload instructions.
2769   if (!(Subtarget->isThumb2() ||
2770         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2771     // Just preserve the chain.
2772     return Op.getOperand(0);
2773
2774   SDLoc dl(Op);
2775   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2776   if (!isRead &&
2777       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2778     // ARMv7 with MP extension has PLDW.
2779     return Op.getOperand(0);
2780
2781   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2782   if (Subtarget->isThumb()) {
2783     // Invert the bits.
2784     isRead = ~isRead & 1;
2785     isData = ~isData & 1;
2786   }
2787
2788   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2789                      Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
2790                      DAG.getConstant(isData, dl, MVT::i32));
2791 }
2792
2793 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2794   MachineFunction &MF = DAG.getMachineFunction();
2795   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2796
2797   // vastart just stores the address of the VarArgsFrameIndex slot into the
2798   // memory location argument.
2799   SDLoc dl(Op);
2800   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2801   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2802   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2803   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2804                       MachinePointerInfo(SV), false, false, 0);
2805 }
2806
2807 SDValue
2808 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2809                                         SDValue &Root, SelectionDAG &DAG,
2810                                         SDLoc dl) const {
2811   MachineFunction &MF = DAG.getMachineFunction();
2812   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2813
2814   const TargetRegisterClass *RC;
2815   if (AFI->isThumb1OnlyFunction())
2816     RC = &ARM::tGPRRegClass;
2817   else
2818     RC = &ARM::GPRRegClass;
2819
2820   // Transform the arguments stored in physical registers into virtual ones.
2821   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2822   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2823
2824   SDValue ArgValue2;
2825   if (NextVA.isMemLoc()) {
2826     MachineFrameInfo *MFI = MF.getFrameInfo();
2827     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2828
2829     // Create load node to retrieve arguments from the stack.
2830     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2831     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2832                             MachinePointerInfo::getFixedStack(FI),
2833                             false, false, false, 0);
2834   } else {
2835     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2836     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2837   }
2838   if (!Subtarget->isLittle())
2839     std::swap (ArgValue, ArgValue2);
2840   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2841 }
2842
2843 // The remaining GPRs hold either the beginning of variable-argument
2844 // data, or the beginning of an aggregate passed by value (usually
2845 // byval).  Either way, we allocate stack slots adjacent to the data
2846 // provided by our caller, and store the unallocated registers there.
2847 // If this is a variadic function, the va_list pointer will begin with
2848 // these values; otherwise, this reassembles a (byval) structure that
2849 // was split between registers and memory.
2850 // Return: The frame index registers were stored into.
2851 int
2852 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2853                                   SDLoc dl, SDValue &Chain,
2854                                   const Value *OrigArg,
2855                                   unsigned InRegsParamRecordIdx,
2856                                   int ArgOffset,
2857                                   unsigned ArgSize) const {
2858   // Currently, two use-cases possible:
2859   // Case #1. Non-var-args function, and we meet first byval parameter.
2860   //          Setup first unallocated register as first byval register;
2861   //          eat all remained registers
2862   //          (these two actions are performed by HandleByVal method).
2863   //          Then, here, we initialize stack frame with
2864   //          "store-reg" instructions.
2865   // Case #2. Var-args function, that doesn't contain byval parameters.
2866   //          The same: eat all remained unallocated registers,
2867   //          initialize stack frame.
2868
2869   MachineFunction &MF = DAG.getMachineFunction();
2870   MachineFrameInfo *MFI = MF.getFrameInfo();
2871   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2872   unsigned RBegin, REnd;
2873   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2874     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2875   } else {
2876     unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
2877     RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
2878     REnd = ARM::R4;
2879   }
2880
2881   if (REnd != RBegin)
2882     ArgOffset = -4 * (ARM::R4 - RBegin);
2883
2884   int FrameIndex = MFI->CreateFixedObject(ArgSize, ArgOffset, false);
2885   SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2886
2887   SmallVector<SDValue, 4> MemOps;
2888   const TargetRegisterClass *RC =
2889       AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
2890
2891   for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
2892     unsigned VReg = MF.addLiveIn(Reg, RC);
2893     SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2894     SDValue Store =
2895         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2896                      MachinePointerInfo(OrigArg, 4 * i), false, false, 0);
2897     MemOps.push_back(Store);
2898     FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2899                       DAG.getConstant(4, dl, getPointerTy()));
2900   }
2901
2902   if (!MemOps.empty())
2903     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2904   return FrameIndex;
2905 }
2906
2907 // Setup stack frame, the va_list pointer will start from.
2908 void
2909 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2910                                         SDLoc dl, SDValue &Chain,
2911                                         unsigned ArgOffset,
2912                                         unsigned TotalArgRegsSaveSize,
2913                                         bool ForceMutable) const {
2914   MachineFunction &MF = DAG.getMachineFunction();
2915   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2916
2917   // Try to store any remaining integer argument regs
2918   // to their spots on the stack so that they may be loaded by deferencing
2919   // the result of va_next.
2920   // If there is no regs to be stored, just point address after last
2921   // argument passed via stack.
2922   int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
2923                                   CCInfo.getInRegsParamsCount(),
2924                                   CCInfo.getNextStackOffset(), 4);
2925   AFI->setVarArgsFrameIndex(FrameIndex);
2926 }
2927
2928 SDValue
2929 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2930                                         CallingConv::ID CallConv, bool isVarArg,
2931                                         const SmallVectorImpl<ISD::InputArg>
2932                                           &Ins,
2933                                         SDLoc dl, SelectionDAG &DAG,
2934                                         SmallVectorImpl<SDValue> &InVals)
2935                                           const {
2936   MachineFunction &MF = DAG.getMachineFunction();
2937   MachineFrameInfo *MFI = MF.getFrameInfo();
2938
2939   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2940
2941   // Assign locations to all of the incoming arguments.
2942   SmallVector<CCValAssign, 16> ArgLocs;
2943   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2944                     *DAG.getContext(), Prologue);
2945   CCInfo.AnalyzeFormalArguments(Ins,
2946                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2947                                                   isVarArg));
2948
2949   SmallVector<SDValue, 16> ArgValues;
2950   SDValue ArgValue;
2951   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2952   unsigned CurArgIdx = 0;
2953
2954   // Initially ArgRegsSaveSize is zero.
2955   // Then we increase this value each time we meet byval parameter.
2956   // We also increase this value in case of varargs function.
2957   AFI->setArgRegsSaveSize(0);
2958
2959   // Calculate the amount of stack space that we need to allocate to store
2960   // byval and variadic arguments that are passed in registers.
2961   // We need to know this before we allocate the first byval or variadic
2962   // argument, as they will be allocated a stack slot below the CFA (Canonical
2963   // Frame Address, the stack pointer at entry to the function).
2964   unsigned ArgRegBegin = ARM::R4;
2965   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2966     if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
2967       break;
2968
2969     CCValAssign &VA = ArgLocs[i];
2970     unsigned Index = VA.getValNo();
2971     ISD::ArgFlagsTy Flags = Ins[Index].Flags;
2972     if (!Flags.isByVal())
2973       continue;
2974
2975     assert(VA.isMemLoc() && "unexpected byval pointer in reg");
2976     unsigned RBegin, REnd;
2977     CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
2978     ArgRegBegin = std::min(ArgRegBegin, RBegin);
2979
2980     CCInfo.nextInRegsParam();
2981   }
2982   CCInfo.rewindByValRegsInfo();
2983
2984   int lastInsIndex = -1;
2985   if (isVarArg && MFI->hasVAStart()) {
2986     unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
2987     if (RegIdx != array_lengthof(GPRArgRegs))
2988       ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
2989   }
2990
2991   unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
2992   AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
2993
2994   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2995     CCValAssign &VA = ArgLocs[i];
2996     if (Ins[VA.getValNo()].isOrigArg()) {
2997       std::advance(CurOrigArg,
2998                    Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
2999       CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3000     }
3001     // Arguments stored in registers.
3002     if (VA.isRegLoc()) {
3003       EVT RegVT = VA.getLocVT();
3004
3005       if (VA.needsCustom()) {
3006         // f64 and vector types are split up into multiple registers or
3007         // combinations of registers and stack slots.
3008         if (VA.getLocVT() == MVT::v2f64) {
3009           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3010                                                    Chain, DAG, dl);
3011           VA = ArgLocs[++i]; // skip ahead to next loc
3012           SDValue ArgValue2;
3013           if (VA.isMemLoc()) {
3014             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3015             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3016             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3017                                     MachinePointerInfo::getFixedStack(FI),
3018                                     false, false, false, 0);
3019           } else {
3020             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3021                                              Chain, DAG, dl);
3022           }
3023           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3024           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3025                                  ArgValue, ArgValue1,
3026                                  DAG.getIntPtrConstant(0, dl));
3027           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3028                                  ArgValue, ArgValue2,
3029                                  DAG.getIntPtrConstant(1, dl));
3030         } else
3031           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3032
3033       } else {
3034         const TargetRegisterClass *RC;
3035
3036         if (RegVT == MVT::f32)
3037           RC = &ARM::SPRRegClass;
3038         else if (RegVT == MVT::f64)
3039           RC = &ARM::DPRRegClass;
3040         else if (RegVT == MVT::v2f64)
3041           RC = &ARM::QPRRegClass;
3042         else if (RegVT == MVT::i32)
3043           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3044                                            : &ARM::GPRRegClass;
3045         else
3046           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3047
3048         // Transform the arguments in physical registers into virtual ones.
3049         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3050         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3051       }
3052
3053       // If this is an 8 or 16-bit value, it is really passed promoted
3054       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3055       // truncate to the right size.
3056       switch (VA.getLocInfo()) {
3057       default: llvm_unreachable("Unknown loc info!");
3058       case CCValAssign::Full: break;
3059       case CCValAssign::BCvt:
3060         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3061         break;
3062       case CCValAssign::SExt:
3063         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3064                                DAG.getValueType(VA.getValVT()));
3065         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3066         break;
3067       case CCValAssign::ZExt:
3068         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3069                                DAG.getValueType(VA.getValVT()));
3070         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3071         break;
3072       }
3073
3074       InVals.push_back(ArgValue);
3075
3076     } else { // VA.isRegLoc()
3077
3078       // sanity check
3079       assert(VA.isMemLoc());
3080       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3081
3082       int index = VA.getValNo();
3083
3084       // Some Ins[] entries become multiple ArgLoc[] entries.
3085       // Process them only once.
3086       if (index != lastInsIndex)
3087         {
3088           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3089           // FIXME: For now, all byval parameter objects are marked mutable.
3090           // This can be changed with more analysis.
3091           // In case of tail call optimization mark all arguments mutable.
3092           // Since they could be overwritten by lowering of arguments in case of
3093           // a tail call.
3094           if (Flags.isByVal()) {
3095             assert(Ins[index].isOrigArg() &&
3096                    "Byval arguments cannot be implicit");
3097             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3098
3099             int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, CurOrigArg,
3100                                             CurByValIndex, VA.getLocMemOffset(),
3101                                             Flags.getByValSize());
3102             InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3103             CCInfo.nextInRegsParam();
3104           } else {
3105             unsigned FIOffset = VA.getLocMemOffset();
3106             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3107                                             FIOffset, true);
3108
3109             // Create load nodes to retrieve arguments from the stack.
3110             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3111             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3112                                          MachinePointerInfo::getFixedStack(FI),
3113                                          false, false, false, 0));
3114           }
3115           lastInsIndex = index;
3116         }
3117     }
3118   }
3119
3120   // varargs
3121   if (isVarArg && MFI->hasVAStart())
3122     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3123                          CCInfo.getNextStackOffset(),
3124                          TotalArgRegsSaveSize);
3125
3126   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3127
3128   return Chain;
3129 }
3130
3131 /// isFloatingPointZero - Return true if this is +0.0.
3132 static bool isFloatingPointZero(SDValue Op) {
3133   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3134     return CFP->getValueAPF().isPosZero();
3135   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3136     // Maybe this has already been legalized into the constant pool?
3137     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3138       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3139       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3140         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3141           return CFP->getValueAPF().isPosZero();
3142     }
3143   } else if (Op->getOpcode() == ISD::BITCAST &&
3144              Op->getValueType(0) == MVT::f64) {
3145     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3146     // created by LowerConstantFP().
3147     SDValue BitcastOp = Op->getOperand(0);
3148     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM) {
3149       SDValue MoveOp = BitcastOp->getOperand(0);
3150       if (MoveOp->getOpcode() == ISD::TargetConstant &&
3151           cast<ConstantSDNode>(MoveOp)->getZExtValue() == 0) {
3152         return true;
3153       }
3154     }
3155   }
3156   return false;
3157 }
3158
3159 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3160 /// the given operands.
3161 SDValue
3162 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3163                              SDValue &ARMcc, SelectionDAG &DAG,
3164                              SDLoc dl) const {
3165   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3166     unsigned C = RHSC->getZExtValue();
3167     if (!isLegalICmpImmediate(C)) {
3168       // Constant does not fit, try adjusting it by one?
3169       switch (CC) {
3170       default: break;
3171       case ISD::SETLT:
3172       case ISD::SETGE:
3173         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3174           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3175           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3176         }
3177         break;
3178       case ISD::SETULT:
3179       case ISD::SETUGE:
3180         if (C != 0 && isLegalICmpImmediate(C-1)) {
3181           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3182           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3183         }
3184         break;
3185       case ISD::SETLE:
3186       case ISD::SETGT:
3187         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3188           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3189           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3190         }
3191         break;
3192       case ISD::SETULE:
3193       case ISD::SETUGT:
3194         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3195           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3196           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3197         }
3198         break;
3199       }
3200     }
3201   }
3202
3203   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3204   ARMISD::NodeType CompareType;
3205   switch (CondCode) {
3206   default:
3207     CompareType = ARMISD::CMP;
3208     break;
3209   case ARMCC::EQ:
3210   case ARMCC::NE:
3211     // Uses only Z Flag
3212     CompareType = ARMISD::CMPZ;
3213     break;
3214   }
3215   ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3216   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3217 }
3218
3219 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3220 SDValue
3221 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3222                              SDLoc dl) const {
3223   assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3224   SDValue Cmp;
3225   if (!isFloatingPointZero(RHS))
3226     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3227   else
3228     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3229   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3230 }
3231
3232 /// duplicateCmp - Glue values can have only one use, so this function
3233 /// duplicates a comparison node.
3234 SDValue
3235 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3236   unsigned Opc = Cmp.getOpcode();
3237   SDLoc DL(Cmp);
3238   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3239     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3240
3241   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3242   Cmp = Cmp.getOperand(0);
3243   Opc = Cmp.getOpcode();
3244   if (Opc == ARMISD::CMPFP)
3245     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3246   else {
3247     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3248     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3249   }
3250   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3251 }
3252
3253 std::pair<SDValue, SDValue>
3254 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3255                                  SDValue &ARMcc) const {
3256   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3257
3258   SDValue Value, OverflowCmp;
3259   SDValue LHS = Op.getOperand(0);
3260   SDValue RHS = Op.getOperand(1);
3261   SDLoc dl(Op);
3262
3263   // FIXME: We are currently always generating CMPs because we don't support
3264   // generating CMN through the backend. This is not as good as the natural
3265   // CMP case because it causes a register dependency and cannot be folded
3266   // later.
3267
3268   switch (Op.getOpcode()) {
3269   default:
3270     llvm_unreachable("Unknown overflow instruction!");
3271   case ISD::SADDO:
3272     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3273     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3274     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3275     break;
3276   case ISD::UADDO:
3277     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3278     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3279     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3280     break;
3281   case ISD::SSUBO:
3282     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3283     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3284     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3285     break;
3286   case ISD::USUBO:
3287     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3288     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3289     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3290     break;
3291   } // switch (...)
3292
3293   return std::make_pair(Value, OverflowCmp);
3294 }
3295
3296
3297 SDValue
3298 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3299   // Let legalize expand this if it isn't a legal type yet.
3300   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3301     return SDValue();
3302
3303   SDValue Value, OverflowCmp;
3304   SDValue ARMcc;
3305   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3306   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3307   SDLoc dl(Op);
3308   // We use 0 and 1 as false and true values.
3309   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3310   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3311   EVT VT = Op.getValueType();
3312
3313   SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
3314                                  ARMcc, CCR, OverflowCmp);
3315
3316   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3317   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
3318 }
3319
3320
3321 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3322   SDValue Cond = Op.getOperand(0);
3323   SDValue SelectTrue = Op.getOperand(1);
3324   SDValue SelectFalse = Op.getOperand(2);
3325   SDLoc dl(Op);
3326   unsigned Opc = Cond.getOpcode();
3327
3328   if (Cond.getResNo() == 1 &&
3329       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3330        Opc == ISD::USUBO)) {
3331     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3332       return SDValue();
3333
3334     SDValue Value, OverflowCmp;
3335     SDValue ARMcc;
3336     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3337     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3338     EVT VT = Op.getValueType();
3339
3340     return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
3341                    OverflowCmp, DAG);
3342   }
3343
3344   // Convert:
3345   //
3346   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3347   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3348   //
3349   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3350     const ConstantSDNode *CMOVTrue =
3351       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3352     const ConstantSDNode *CMOVFalse =
3353       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3354
3355     if (CMOVTrue && CMOVFalse) {
3356       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3357       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3358
3359       SDValue True;
3360       SDValue False;
3361       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3362         True = SelectTrue;
3363         False = SelectFalse;
3364       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3365         True = SelectFalse;
3366         False = SelectTrue;
3367       }
3368
3369       if (True.getNode() && False.getNode()) {
3370         EVT VT = Op.getValueType();
3371         SDValue ARMcc = Cond.getOperand(2);
3372         SDValue CCR = Cond.getOperand(3);
3373         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3374         assert(True.getValueType() == VT);
3375         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3376       }
3377     }
3378   }
3379
3380   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3381   // undefined bits before doing a full-word comparison with zero.
3382   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3383                      DAG.getConstant(1, dl, Cond.getValueType()));
3384
3385   return DAG.getSelectCC(dl, Cond,
3386                          DAG.getConstant(0, dl, Cond.getValueType()),
3387                          SelectTrue, SelectFalse, ISD::SETNE);
3388 }
3389
3390 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3391                                  bool &swpCmpOps, bool &swpVselOps) {
3392   // Start by selecting the GE condition code for opcodes that return true for
3393   // 'equality'
3394   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3395       CC == ISD::SETULE)
3396     CondCode = ARMCC::GE;
3397
3398   // and GT for opcodes that return false for 'equality'.
3399   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3400            CC == ISD::SETULT)
3401     CondCode = ARMCC::GT;
3402
3403   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3404   // to swap the compare operands.
3405   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3406       CC == ISD::SETULT)
3407     swpCmpOps = true;
3408
3409   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3410   // If we have an unordered opcode, we need to swap the operands to the VSEL
3411   // instruction (effectively negating the condition).
3412   //
3413   // This also has the effect of swapping which one of 'less' or 'greater'
3414   // returns true, so we also swap the compare operands. It also switches
3415   // whether we return true for 'equality', so we compensate by picking the
3416   // opposite condition code to our original choice.
3417   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3418       CC == ISD::SETUGT) {
3419     swpCmpOps = !swpCmpOps;
3420     swpVselOps = !swpVselOps;
3421     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3422   }
3423
3424   // 'ordered' is 'anything but unordered', so use the VS condition code and
3425   // swap the VSEL operands.
3426   if (CC == ISD::SETO) {
3427     CondCode = ARMCC::VS;
3428     swpVselOps = true;
3429   }
3430
3431   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3432   // code and swap the VSEL operands.
3433   if (CC == ISD::SETUNE) {
3434     CondCode = ARMCC::EQ;
3435     swpVselOps = true;
3436   }
3437 }
3438
3439 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3440                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3441                                    SDValue Cmp, SelectionDAG &DAG) const {
3442   if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3443     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3444                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3445     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3446                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3447
3448     SDValue TrueLow = TrueVal.getValue(0);
3449     SDValue TrueHigh = TrueVal.getValue(1);
3450     SDValue FalseLow = FalseVal.getValue(0);
3451     SDValue FalseHigh = FalseVal.getValue(1);
3452
3453     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3454                               ARMcc, CCR, Cmp);
3455     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3456                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
3457
3458     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3459   } else {
3460     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3461                        Cmp);
3462   }
3463 }
3464
3465 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3466   EVT VT = Op.getValueType();
3467   SDValue LHS = Op.getOperand(0);
3468   SDValue RHS = Op.getOperand(1);
3469   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3470   SDValue TrueVal = Op.getOperand(2);
3471   SDValue FalseVal = Op.getOperand(3);
3472   SDLoc dl(Op);
3473
3474   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3475     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3476                                                     dl);
3477
3478     // If softenSetCCOperands only returned one value, we should compare it to
3479     // zero.
3480     if (!RHS.getNode()) {
3481       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3482       CC = ISD::SETNE;
3483     }
3484   }
3485
3486   if (LHS.getValueType() == MVT::i32) {
3487     // Try to generate VSEL on ARMv8.
3488     // The VSEL instruction can't use all the usual ARM condition
3489     // codes: it only has two bits to select the condition code, so it's
3490     // constrained to use only GE, GT, VS and EQ.
3491     //
3492     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3493     // swap the operands of the previous compare instruction (effectively
3494     // inverting the compare condition, swapping 'less' and 'greater') and
3495     // sometimes need to swap the operands to the VSEL (which inverts the
3496     // condition in the sense of firing whenever the previous condition didn't)
3497     if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3498                                     TrueVal.getValueType() == MVT::f64)) {
3499       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3500       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3501           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3502         CC = ISD::getSetCCInverse(CC, true);
3503         std::swap(TrueVal, FalseVal);
3504       }
3505     }
3506
3507     SDValue ARMcc;
3508     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3509     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3510     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3511   }
3512
3513   ARMCC::CondCodes CondCode, CondCode2;
3514   FPCCToARMCC(CC, CondCode, CondCode2);
3515
3516   // Try to generate VMAXNM/VMINNM on ARMv8.
3517   if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3518                                   TrueVal.getValueType() == MVT::f64)) {
3519     // We can use VMAXNM/VMINNM for a compare followed by a select with the
3520     // same operands, as follows:
3521     //   c = fcmp [?gt, ?ge, ?lt, ?le] a, b
3522     //   select c, a, b
3523     // In NoNaNsFPMath the CC will have been changed from, e.g., 'ogt' to 'gt'.
3524     bool swapSides = false;
3525     if (!getTargetMachine().Options.NoNaNsFPMath) {
3526       // transformability may depend on which way around we compare
3527       switch (CC) {
3528       default:
3529         break;
3530       case ISD::SETOGT:
3531       case ISD::SETOGE:
3532       case ISD::SETOLT:
3533       case ISD::SETOLE:
3534         // the non-NaN should be RHS
3535         swapSides = DAG.isKnownNeverNaN(LHS) && !DAG.isKnownNeverNaN(RHS);
3536         break;
3537       case ISD::SETUGT:
3538       case ISD::SETUGE:
3539       case ISD::SETULT:
3540       case ISD::SETULE:
3541         // the non-NaN should be LHS
3542         swapSides = DAG.isKnownNeverNaN(RHS) && !DAG.isKnownNeverNaN(LHS);
3543         break;
3544       }
3545     }
3546     swapSides = swapSides || (LHS == FalseVal && RHS == TrueVal);
3547     if (swapSides) {
3548       CC = ISD::getSetCCSwappedOperands(CC);
3549       std::swap(LHS, RHS);
3550     }
3551     if (LHS == TrueVal && RHS == FalseVal) {
3552       bool canTransform = true;
3553       // FIXME: FastMathFlags::noSignedZeros() doesn't appear reachable from here
3554       if (!getTargetMachine().Options.UnsafeFPMath &&
3555           !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
3556         const ConstantFPSDNode *Zero;
3557         switch (CC) {
3558         default:
3559           break;
3560         case ISD::SETOGT:
3561         case ISD::SETUGT:
3562         case ISD::SETGT:
3563           // RHS must not be -0
3564           canTransform = (Zero = dyn_cast<ConstantFPSDNode>(RHS)) &&
3565                          !Zero->isNegative();
3566           break;
3567         case ISD::SETOGE:
3568         case ISD::SETUGE:
3569         case ISD::SETGE:
3570           // LHS must not be -0
3571           canTransform = (Zero = dyn_cast<ConstantFPSDNode>(LHS)) &&
3572                          !Zero->isNegative();
3573           break;
3574         case ISD::SETOLT:
3575         case ISD::SETULT:
3576         case ISD::SETLT:
3577           // RHS must not be +0
3578           canTransform = (Zero = dyn_cast<ConstantFPSDNode>(RHS)) &&
3579                           Zero->isNegative();
3580           break;
3581         case ISD::SETOLE:
3582         case ISD::SETULE:
3583         case ISD::SETLE:
3584           // LHS must not be +0
3585           canTransform = (Zero = dyn_cast<ConstantFPSDNode>(LHS)) &&
3586                           Zero->isNegative();
3587           break;
3588         }
3589       }
3590       if (canTransform) {
3591         // Note: If one of the elements in a pair is a number and the other
3592         // element is NaN, the corresponding result element is the number.
3593         // This is consistent with the IEEE 754-2008 standard.
3594         // Therefore, a > b ? a : b <=> vmax(a,b), if b is constant and a is NaN
3595         switch (CC) {
3596         default:
3597           break;
3598         case ISD::SETOGT:
3599         case ISD::SETOGE:
3600           if (!DAG.isKnownNeverNaN(RHS))
3601             break;
3602           return DAG.getNode(ARMISD::VMAXNM, dl, VT, LHS, RHS);
3603         case ISD::SETUGT:
3604         case ISD::SETUGE:
3605           if (!DAG.isKnownNeverNaN(LHS))
3606             break;
3607         case ISD::SETGT:
3608         case ISD::SETGE:
3609           return DAG.getNode(ARMISD::VMAXNM, dl, VT, LHS, RHS);
3610         case ISD::SETOLT:
3611         case ISD::SETOLE:
3612           if (!DAG.isKnownNeverNaN(RHS))
3613             break;
3614           return DAG.getNode(ARMISD::VMINNM, dl, VT, LHS, RHS);
3615         case ISD::SETULT:
3616         case ISD::SETULE:
3617           if (!DAG.isKnownNeverNaN(LHS))
3618             break;
3619         case ISD::SETLT:
3620         case ISD::SETLE:
3621           return DAG.getNode(ARMISD::VMINNM, dl, VT, LHS, RHS);
3622         }
3623       }
3624     }
3625
3626     bool swpCmpOps = false;
3627     bool swpVselOps = false;
3628     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3629
3630     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3631         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3632       if (swpCmpOps)
3633         std::swap(LHS, RHS);
3634       if (swpVselOps)
3635         std::swap(TrueVal, FalseVal);
3636     }
3637   }
3638
3639   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3640   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3641   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3642   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3643   if (CondCode2 != ARMCC::AL) {
3644     SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
3645     // FIXME: Needs another CMP because flag can have but one use.
3646     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3647     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3648   }
3649   return Result;
3650 }
3651
3652 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3653 /// to morph to an integer compare sequence.
3654 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3655                            const ARMSubtarget *Subtarget) {
3656   SDNode *N = Op.getNode();
3657   if (!N->hasOneUse())
3658     // Otherwise it requires moving the value from fp to integer registers.
3659     return false;
3660   if (!N->getNumValues())
3661     return false;
3662   EVT VT = Op.getValueType();
3663   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3664     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3665     // vmrs are very slow, e.g. cortex-a8.
3666     return false;
3667
3668   if (isFloatingPointZero(Op)) {
3669     SeenZero = true;
3670     return true;
3671   }
3672   return ISD::isNormalLoad(N);
3673 }
3674
3675 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3676   if (isFloatingPointZero(Op))
3677     return DAG.getConstant(0, SDLoc(Op), MVT::i32);
3678
3679   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3680     return DAG.getLoad(MVT::i32, SDLoc(Op),
3681                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3682                        Ld->isVolatile(), Ld->isNonTemporal(),
3683                        Ld->isInvariant(), Ld->getAlignment());
3684
3685   llvm_unreachable("Unknown VFP cmp argument!");
3686 }
3687
3688 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3689                            SDValue &RetVal1, SDValue &RetVal2) {
3690   SDLoc dl(Op);
3691
3692   if (isFloatingPointZero(Op)) {
3693     RetVal1 = DAG.getConstant(0, dl, MVT::i32);
3694     RetVal2 = DAG.getConstant(0, dl, MVT::i32);
3695     return;
3696   }
3697
3698   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3699     SDValue Ptr = Ld->getBasePtr();
3700     RetVal1 = DAG.getLoad(MVT::i32, dl,
3701                           Ld->getChain(), Ptr,
3702                           Ld->getPointerInfo(),
3703                           Ld->isVolatile(), Ld->isNonTemporal(),
3704                           Ld->isInvariant(), Ld->getAlignment());
3705
3706     EVT PtrType = Ptr.getValueType();
3707     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3708     SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
3709                                  PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
3710     RetVal2 = DAG.getLoad(MVT::i32, dl,
3711                           Ld->getChain(), NewPtr,
3712                           Ld->getPointerInfo().getWithOffset(4),
3713                           Ld->isVolatile(), Ld->isNonTemporal(),
3714                           Ld->isInvariant(), NewAlign);
3715     return;
3716   }
3717
3718   llvm_unreachable("Unknown VFP cmp argument!");
3719 }
3720
3721 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3722 /// f32 and even f64 comparisons to integer ones.
3723 SDValue
3724 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3725   SDValue Chain = Op.getOperand(0);
3726   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3727   SDValue LHS = Op.getOperand(2);
3728   SDValue RHS = Op.getOperand(3);
3729   SDValue Dest = Op.getOperand(4);
3730   SDLoc dl(Op);
3731
3732   bool LHSSeenZero = false;
3733   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3734   bool RHSSeenZero = false;
3735   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3736   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3737     // If unsafe fp math optimization is enabled and there are no other uses of
3738     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3739     // to an integer comparison.
3740     if (CC == ISD::SETOEQ)
3741       CC = ISD::SETEQ;
3742     else if (CC == ISD::SETUNE)
3743       CC = ISD::SETNE;
3744
3745     SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
3746     SDValue ARMcc;
3747     if (LHS.getValueType() == MVT::f32) {
3748       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3749                         bitcastf32Toi32(LHS, DAG), Mask);
3750       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3751                         bitcastf32Toi32(RHS, DAG), Mask);
3752       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3753       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3754       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3755                          Chain, Dest, ARMcc, CCR, Cmp);
3756     }
3757
3758     SDValue LHS1, LHS2;
3759     SDValue RHS1, RHS2;
3760     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3761     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3762     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3763     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3764     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3765     ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3766     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3767     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3768     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3769   }
3770
3771   return SDValue();
3772 }
3773
3774 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3775   SDValue Chain = Op.getOperand(0);
3776   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3777   SDValue LHS = Op.getOperand(2);
3778   SDValue RHS = Op.getOperand(3);
3779   SDValue Dest = Op.getOperand(4);
3780   SDLoc dl(Op);
3781
3782   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3783     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3784                                                     dl);
3785
3786     // If softenSetCCOperands only returned one value, we should compare it to
3787     // zero.
3788     if (!RHS.getNode()) {
3789       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3790       CC = ISD::SETNE;
3791     }
3792   }
3793
3794   if (LHS.getValueType() == MVT::i32) {
3795     SDValue ARMcc;
3796     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3797     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3798     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3799                        Chain, Dest, ARMcc, CCR, Cmp);
3800   }
3801
3802   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3803
3804   if (getTargetMachine().Options.UnsafeFPMath &&
3805       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3806        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3807     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3808     if (Result.getNode())
3809       return Result;
3810   }
3811
3812   ARMCC::CondCodes CondCode, CondCode2;
3813   FPCCToARMCC(CC, CondCode, CondCode2);
3814
3815   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3816   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3817   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3818   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3819   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3820   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3821   if (CondCode2 != ARMCC::AL) {
3822     ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
3823     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3824     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3825   }
3826   return Res;
3827 }
3828
3829 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3830   SDValue Chain = Op.getOperand(0);
3831   SDValue Table = Op.getOperand(1);
3832   SDValue Index = Op.getOperand(2);
3833   SDLoc dl(Op);
3834
3835   EVT PTy = getPointerTy();
3836   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3837   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3838   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
3839   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
3840   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3841   if (Subtarget->isThumb2()) {
3842     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3843     // which does another jump to the destination. This also makes it easier
3844     // to translate it to TBB / TBH later.
3845     // FIXME: This might not work if the function is extremely large.
3846     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3847                        Addr, Op.getOperand(2), JTI);
3848   }
3849   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3850     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3851                        MachinePointerInfo::getJumpTable(),
3852                        false, false, false, 0);
3853     Chain = Addr.getValue(1);
3854     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3855     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3856   } else {
3857     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3858                        MachinePointerInfo::getJumpTable(),
3859                        false, false, false, 0);
3860     Chain = Addr.getValue(1);
3861     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3862   }
3863 }
3864
3865 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3866   EVT VT = Op.getValueType();
3867   SDLoc dl(Op);
3868
3869   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3870     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3871       return Op;
3872     return DAG.UnrollVectorOp(Op.getNode());
3873   }
3874
3875   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3876          "Invalid type for custom lowering!");
3877   if (VT != MVT::v4i16)
3878     return DAG.UnrollVectorOp(Op.getNode());
3879
3880   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3881   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3882 }
3883
3884 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3885   EVT VT = Op.getValueType();
3886   if (VT.isVector())
3887     return LowerVectorFP_TO_INT(Op, DAG);
3888   if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3889     RTLIB::Libcall LC;
3890     if (Op.getOpcode() == ISD::FP_TO_SINT)
3891       LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
3892                               Op.getValueType());
3893     else
3894       LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
3895                               Op.getValueType());
3896     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3897                        /*isSigned*/ false, SDLoc(Op)).first;
3898   }
3899
3900   return Op;
3901 }
3902
3903 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3904   EVT VT = Op.getValueType();
3905   SDLoc dl(Op);
3906
3907   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3908     if (VT.getVectorElementType() == MVT::f32)
3909       return Op;
3910     return DAG.UnrollVectorOp(Op.getNode());
3911   }
3912
3913   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3914          "Invalid type for custom lowering!");
3915   if (VT != MVT::v4f32)
3916     return DAG.UnrollVectorOp(Op.getNode());
3917
3918   unsigned CastOpc;
3919   unsigned Opc;
3920   switch (Op.getOpcode()) {
3921   default: llvm_unreachable("Invalid opcode!");
3922   case ISD::SINT_TO_FP:
3923     CastOpc = ISD::SIGN_EXTEND;
3924     Opc = ISD::SINT_TO_FP;
3925     break;
3926   case ISD::UINT_TO_FP:
3927     CastOpc = ISD::ZERO_EXTEND;
3928     Opc = ISD::UINT_TO_FP;
3929     break;
3930   }
3931
3932   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3933   return DAG.getNode(Opc, dl, VT, Op);
3934 }
3935
3936 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
3937   EVT VT = Op.getValueType();
3938   if (VT.isVector())
3939     return LowerVectorINT_TO_FP(Op, DAG);
3940   if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
3941     RTLIB::Libcall LC;
3942     if (Op.getOpcode() == ISD::SINT_TO_FP)
3943       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
3944                               Op.getValueType());
3945     else
3946       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
3947                               Op.getValueType());
3948     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3949                        /*isSigned*/ false, SDLoc(Op)).first;
3950   }
3951
3952   return Op;
3953 }
3954
3955 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3956   // Implement fcopysign with a fabs and a conditional fneg.
3957   SDValue Tmp0 = Op.getOperand(0);
3958   SDValue Tmp1 = Op.getOperand(1);
3959   SDLoc dl(Op);
3960   EVT VT = Op.getValueType();
3961   EVT SrcVT = Tmp1.getValueType();
3962   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3963     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3964   bool UseNEON = !InGPR && Subtarget->hasNEON();
3965
3966   if (UseNEON) {
3967     // Use VBSL to copy the sign bit.
3968     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3969     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3970                                DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
3971     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3972     if (VT == MVT::f64)
3973       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3974                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3975                          DAG.getConstant(32, dl, MVT::i32));
3976     else /*if (VT == MVT::f32)*/
3977       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3978     if (SrcVT == MVT::f32) {
3979       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3980       if (VT == MVT::f64)
3981         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3982                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3983                            DAG.getConstant(32, dl, MVT::i32));
3984     } else if (VT == MVT::f32)
3985       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3986                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3987                          DAG.getConstant(32, dl, MVT::i32));
3988     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3989     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3990
3991     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3992                                             dl, MVT::i32);
3993     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3994     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3995                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3996
3997     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3998                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3999                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4000     if (VT == MVT::f32) {
4001       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4002       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4003                         DAG.getConstant(0, dl, MVT::i32));
4004     } else {
4005       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4006     }
4007
4008     return Res;
4009   }
4010
4011   // Bitcast operand 1 to i32.
4012   if (SrcVT == MVT::f64)
4013     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4014                        Tmp1).getValue(1);
4015   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4016
4017   // Or in the signbit with integer operations.
4018   SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
4019   SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4020   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4021   if (VT == MVT::f32) {
4022     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4023                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4024     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4025                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4026   }
4027
4028   // f64: Or the high part with signbit and then combine two parts.
4029   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4030                      Tmp0);
4031   SDValue Lo = Tmp0.getValue(0);
4032   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4033   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4034   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4035 }
4036
4037 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4038   MachineFunction &MF = DAG.getMachineFunction();
4039   MachineFrameInfo *MFI = MF.getFrameInfo();
4040   MFI->setReturnAddressIsTaken(true);
4041
4042   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4043     return SDValue();
4044
4045   EVT VT = Op.getValueType();
4046   SDLoc dl(Op);
4047   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4048   if (Depth) {
4049     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4050     SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
4051     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4052                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4053                        MachinePointerInfo(), false, false, false, 0);
4054   }
4055
4056   // Return LR, which contains the return address. Mark it an implicit live-in.
4057   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4058   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4059 }
4060
4061 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4062   const ARMBaseRegisterInfo &ARI =
4063     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4064   MachineFunction &MF = DAG.getMachineFunction();
4065   MachineFrameInfo *MFI = MF.getFrameInfo();
4066   MFI->setFrameAddressIsTaken(true);
4067
4068   EVT VT = Op.getValueType();
4069   SDLoc dl(Op);  // FIXME probably not meaningful
4070   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4071   unsigned FrameReg = ARI.getFrameRegister(MF);
4072   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4073   while (Depth--)
4074     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4075                             MachinePointerInfo(),
4076                             false, false, false, 0);
4077   return FrameAddr;
4078 }
4079
4080 // FIXME? Maybe this could be a TableGen attribute on some registers and
4081 // this table could be generated automatically from RegInfo.
4082 unsigned ARMTargetLowering::getRegisterByName(const char* RegName,
4083                                               EVT VT) const {
4084   unsigned Reg = StringSwitch<unsigned>(RegName)
4085                        .Case("sp", ARM::SP)
4086                        .Default(0);
4087   if (Reg)
4088     return Reg;
4089   report_fatal_error("Invalid register name global variable");
4090 }
4091
4092 /// ExpandBITCAST - If the target supports VFP, this function is called to
4093 /// expand a bit convert where either the source or destination type is i64 to
4094 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
4095 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4096 /// vectors), since the legalizer won't know what to do with that.
4097 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4098   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4099   SDLoc dl(N);
4100   SDValue Op = N->getOperand(0);
4101
4102   // This function is only supposed to be called for i64 types, either as the
4103   // source or destination of the bit convert.
4104   EVT SrcVT = Op.getValueType();
4105   EVT DstVT = N->getValueType(0);
4106   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4107          "ExpandBITCAST called for non-i64 type");
4108
4109   // Turn i64->f64 into VMOVDRR.
4110   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4111     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4112                              DAG.getConstant(0, dl, MVT::i32));
4113     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4114                              DAG.getConstant(1, dl, MVT::i32));
4115     return DAG.getNode(ISD::BITCAST, dl, DstVT,
4116                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4117   }
4118
4119   // Turn f64->i64 into VMOVRRD.
4120   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4121     SDValue Cvt;
4122     if (TLI.isBigEndian() && SrcVT.isVector() &&
4123         SrcVT.getVectorNumElements() > 1)
4124       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4125                         DAG.getVTList(MVT::i32, MVT::i32),
4126                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4127     else
4128       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4129                         DAG.getVTList(MVT::i32, MVT::i32), Op);
4130     // Merge the pieces into a single i64 value.
4131     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4132   }
4133
4134   return SDValue();
4135 }
4136
4137 /// getZeroVector - Returns a vector of specified type with all zero elements.
4138 /// Zero vectors are used to represent vector negation and in those cases
4139 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
4140 /// not support i64 elements, so sometimes the zero vectors will need to be
4141 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
4142 /// zero vector.
4143 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4144   assert(VT.isVector() && "Expected a vector type");
4145   // The canonical modified immediate encoding of a zero vector is....0!
4146   SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
4147   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4148   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4149   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4150 }
4151
4152 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4153 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4154 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4155                                                 SelectionDAG &DAG) const {
4156   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4157   EVT VT = Op.getValueType();
4158   unsigned VTBits = VT.getSizeInBits();
4159   SDLoc dl(Op);
4160   SDValue ShOpLo = Op.getOperand(0);
4161   SDValue ShOpHi = Op.getOperand(1);
4162   SDValue ShAmt  = Op.getOperand(2);
4163   SDValue ARMcc;
4164   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4165
4166   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4167
4168   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4169                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4170   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4171   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4172                                    DAG.getConstant(VTBits, dl, MVT::i32));
4173   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4174   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4175   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4176
4177   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4178   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4179                           ISD::SETGE, ARMcc, DAG, dl);
4180   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4181   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4182                            CCR, Cmp);
4183
4184   SDValue Ops[2] = { Lo, Hi };
4185   return DAG.getMergeValues(Ops, dl);
4186 }
4187
4188 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4189 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4190 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4191                                                SelectionDAG &DAG) const {
4192   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4193   EVT VT = Op.getValueType();
4194   unsigned VTBits = VT.getSizeInBits();
4195   SDLoc dl(Op);
4196   SDValue ShOpLo = Op.getOperand(0);
4197   SDValue ShOpHi = Op.getOperand(1);
4198   SDValue ShAmt  = Op.getOperand(2);
4199   SDValue ARMcc;
4200
4201   assert(Op.getOpcode() == ISD::SHL_PARTS);
4202   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4203                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4204   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4205   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4206                                    DAG.getConstant(VTBits, dl, MVT::i32));
4207   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4208   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4209
4210   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4211   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4212   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4213                           ISD::SETGE, ARMcc, DAG, dl);
4214   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4215   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4216                            CCR, Cmp);
4217
4218   SDValue Ops[2] = { Lo, Hi };
4219   return DAG.getMergeValues(Ops, dl);
4220 }
4221
4222 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4223                                             SelectionDAG &DAG) const {
4224   // The rounding mode is in bits 23:22 of the FPSCR.
4225   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4226   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4227   // so that the shift + and get folded into a bitfield extract.
4228   SDLoc dl(Op);
4229   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4230                               DAG.getConstant(Intrinsic::arm_get_fpscr, dl,
4231                                               MVT::i32));
4232   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4233                                   DAG.getConstant(1U << 22, dl, MVT::i32));
4234   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4235                               DAG.getConstant(22, dl, MVT::i32));
4236   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4237                      DAG.getConstant(3, dl, MVT::i32));
4238 }
4239
4240 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4241                          const ARMSubtarget *ST) {
4242   EVT VT = N->getValueType(0);
4243   SDLoc dl(N);
4244
4245   if (!ST->hasV6T2Ops())
4246     return SDValue();
4247
4248   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4249   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4250 }
4251
4252 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4253 /// for each 16-bit element from operand, repeated.  The basic idea is to
4254 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4255 ///
4256 /// Trace for v4i16:
4257 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
4258 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4259 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4260 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4261 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
4262 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
4263 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4264 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
4265 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4266   EVT VT = N->getValueType(0);
4267   SDLoc DL(N);
4268
4269   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4270   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4271   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4272   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4273   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4274   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4275 }
4276
4277 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4278 /// bit-count for each 16-bit element from the operand.  We need slightly
4279 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4280 /// 64/128-bit registers.
4281 ///
4282 /// Trace for v4i16:
4283 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
4284 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4285 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
4286 /// v4i16:Extracted = [k0    k1    k2    k3    ]
4287 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4288   EVT VT = N->getValueType(0);
4289   SDLoc DL(N);
4290
4291   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4292   if (VT.is64BitVector()) {
4293     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4294     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4295                        DAG.getIntPtrConstant(0, DL));
4296   } else {
4297     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4298                                     BitCounts, DAG.getIntPtrConstant(0, DL));
4299     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4300   }
4301 }
4302
4303 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4304 /// bit-count for each 32-bit element from the operand.  The idea here is
4305 /// to split the vector into 16-bit elements, leverage the 16-bit count
4306 /// routine, and then combine the results.
4307 ///
4308 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4309 /// input    = [v0    v1    ] (vi: 32-bit elements)
4310 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4311 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4312 /// vrev: N0 = [k1 k0 k3 k2 ]
4313 ///            [k0 k1 k2 k3 ]
4314 ///       N1 =+[k1 k0 k3 k2 ]
4315 ///            [k0 k2 k1 k3 ]
4316 ///       N2 =+[k1 k3 k0 k2 ]
4317 ///            [k0    k2    k1    k3    ]
4318 /// Extended =+[k1    k3    k0    k2    ]
4319 ///            [k0    k2    ]
4320 /// Extracted=+[k1    k3    ]
4321 ///
4322 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4323   EVT VT = N->getValueType(0);
4324   SDLoc DL(N);
4325
4326   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4327
4328   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4329   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4330   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4331   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4332   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4333
4334   if (VT.is64BitVector()) {
4335     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4336     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4337                        DAG.getIntPtrConstant(0, DL));
4338   } else {
4339     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4340                                     DAG.getIntPtrConstant(0, DL));
4341     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4342   }
4343 }
4344
4345 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4346                           const ARMSubtarget *ST) {
4347   EVT VT = N->getValueType(0);
4348
4349   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4350   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4351           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4352          "Unexpected type for custom ctpop lowering");
4353
4354   if (VT.getVectorElementType() == MVT::i32)
4355     return lowerCTPOP32BitElements(N, DAG);
4356   else
4357     return lowerCTPOP16BitElements(N, DAG);
4358 }
4359
4360 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4361                           const ARMSubtarget *ST) {
4362   EVT VT = N->getValueType(0);
4363   SDLoc dl(N);
4364
4365   if (!VT.isVector())
4366     return SDValue();
4367
4368   // Lower vector shifts on NEON to use VSHL.
4369   assert(ST->hasNEON() && "unexpected vector shift");
4370
4371   // Left shifts translate directly to the vshiftu intrinsic.
4372   if (N->getOpcode() == ISD::SHL)
4373     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4374                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
4375                                        MVT::i32),
4376                        N->getOperand(0), N->getOperand(1));
4377
4378   assert((N->getOpcode() == ISD::SRA ||
4379           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4380
4381   // NEON uses the same intrinsics for both left and right shifts.  For
4382   // right shifts, the shift amounts are negative, so negate the vector of
4383   // shift amounts.
4384   EVT ShiftVT = N->getOperand(1).getValueType();
4385   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4386                                      getZeroVector(ShiftVT, DAG, dl),
4387                                      N->getOperand(1));
4388   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4389                              Intrinsic::arm_neon_vshifts :
4390                              Intrinsic::arm_neon_vshiftu);
4391   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4392                      DAG.getConstant(vshiftInt, dl, MVT::i32),
4393                      N->getOperand(0), NegatedCount);
4394 }
4395
4396 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4397                                 const ARMSubtarget *ST) {
4398   EVT VT = N->getValueType(0);
4399   SDLoc dl(N);
4400
4401   // We can get here for a node like i32 = ISD::SHL i32, i64
4402   if (VT != MVT::i64)
4403     return SDValue();
4404
4405   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4406          "Unknown shift to lower!");
4407
4408   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4409   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4410       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4411     return SDValue();
4412
4413   // If we are in thumb mode, we don't have RRX.
4414   if (ST->isThumb1Only()) return SDValue();
4415
4416   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4417   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4418                            DAG.getConstant(0, dl, MVT::i32));
4419   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4420                            DAG.getConstant(1, dl, MVT::i32));
4421
4422   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4423   // captures the result into a carry flag.
4424   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4425   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4426
4427   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4428   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4429
4430   // Merge the pieces into a single i64 value.
4431  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4432 }
4433
4434 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4435   SDValue TmpOp0, TmpOp1;
4436   bool Invert = false;
4437   bool Swap = false;
4438   unsigned Opc = 0;
4439
4440   SDValue Op0 = Op.getOperand(0);
4441   SDValue Op1 = Op.getOperand(1);
4442   SDValue CC = Op.getOperand(2);
4443   EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
4444   EVT VT = Op.getValueType();
4445   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4446   SDLoc dl(Op);
4447
4448   if (Op1.getValueType().isFloatingPoint()) {
4449     switch (SetCCOpcode) {
4450     default: llvm_unreachable("Illegal FP comparison");
4451     case ISD::SETUNE:
4452     case ISD::SETNE:  Invert = true; // Fallthrough
4453     case ISD::SETOEQ:
4454     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4455     case ISD::SETOLT:
4456     case ISD::SETLT: Swap = true; // Fallthrough
4457     case ISD::SETOGT:
4458     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4459     case ISD::SETOLE:
4460     case ISD::SETLE:  Swap = true; // Fallthrough
4461     case ISD::SETOGE:
4462     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4463     case ISD::SETUGE: Swap = true; // Fallthrough
4464     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4465     case ISD::SETUGT: Swap = true; // Fallthrough
4466     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4467     case ISD::SETUEQ: Invert = true; // Fallthrough
4468     case ISD::SETONE:
4469       // Expand this to (OLT | OGT).
4470       TmpOp0 = Op0;
4471       TmpOp1 = Op1;
4472       Opc = ISD::OR;
4473       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4474       Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
4475       break;
4476     case ISD::SETUO: Invert = true; // Fallthrough
4477     case ISD::SETO:
4478       // Expand this to (OLT | OGE).
4479       TmpOp0 = Op0;
4480       TmpOp1 = Op1;
4481       Opc = ISD::OR;
4482       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4483       Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
4484       break;
4485     }
4486   } else {
4487     // Integer comparisons.
4488     switch (SetCCOpcode) {
4489     default: llvm_unreachable("Illegal integer comparison");
4490     case ISD::SETNE:  Invert = true;
4491     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4492     case ISD::SETLT:  Swap = true;
4493     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4494     case ISD::SETLE:  Swap = true;
4495     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4496     case ISD::SETULT: Swap = true;
4497     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4498     case ISD::SETULE: Swap = true;
4499     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4500     }
4501
4502     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4503     if (Opc == ARMISD::VCEQ) {
4504
4505       SDValue AndOp;
4506       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4507         AndOp = Op0;
4508       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4509         AndOp = Op1;
4510
4511       // Ignore bitconvert.
4512       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4513         AndOp = AndOp.getOperand(0);
4514
4515       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4516         Opc = ARMISD::VTST;
4517         Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
4518         Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
4519         Invert = !Invert;
4520       }
4521     }
4522   }
4523
4524   if (Swap)
4525     std::swap(Op0, Op1);
4526
4527   // If one of the operands is a constant vector zero, attempt to fold the
4528   // comparison to a specialized compare-against-zero form.
4529   SDValue SingleOp;
4530   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4531     SingleOp = Op0;
4532   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4533     if (Opc == ARMISD::VCGE)
4534       Opc = ARMISD::VCLEZ;
4535     else if (Opc == ARMISD::VCGT)
4536       Opc = ARMISD::VCLTZ;
4537     SingleOp = Op1;
4538   }
4539
4540   SDValue Result;
4541   if (SingleOp.getNode()) {
4542     switch (Opc) {
4543     case ARMISD::VCEQ:
4544       Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
4545     case ARMISD::VCGE:
4546       Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
4547     case ARMISD::VCLEZ:
4548       Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
4549     case ARMISD::VCGT:
4550       Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
4551     case ARMISD::VCLTZ:
4552       Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
4553     default:
4554       Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4555     }
4556   } else {
4557      Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4558   }
4559
4560   Result = DAG.getSExtOrTrunc(Result, dl, VT);
4561
4562   if (Invert)
4563     Result = DAG.getNOT(dl, Result, VT);
4564
4565   return Result;
4566 }
4567
4568 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4569 /// valid vector constant for a NEON instruction with a "modified immediate"
4570 /// operand (e.g., VMOV).  If so, return the encoded value.
4571 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4572                                  unsigned SplatBitSize, SelectionDAG &DAG,
4573                                  SDLoc dl, EVT &VT, bool is128Bits,
4574                                  NEONModImmType type) {
4575   unsigned OpCmode, Imm;
4576
4577   // SplatBitSize is set to the smallest size that splats the vector, so a
4578   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4579   // immediate instructions others than VMOV do not support the 8-bit encoding
4580   // of a zero vector, and the default encoding of zero is supposed to be the
4581   // 32-bit version.
4582   if (SplatBits == 0)
4583     SplatBitSize = 32;
4584
4585   switch (SplatBitSize) {
4586   case 8:
4587     if (type != VMOVModImm)
4588       return SDValue();
4589     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4590     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4591     OpCmode = 0xe;
4592     Imm = SplatBits;
4593     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4594     break;
4595
4596   case 16:
4597     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4598     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4599     if ((SplatBits & ~0xff) == 0) {
4600       // Value = 0x00nn: Op=x, Cmode=100x.
4601       OpCmode = 0x8;
4602       Imm = SplatBits;
4603       break;
4604     }
4605     if ((SplatBits & ~0xff00) == 0) {
4606       // Value = 0xnn00: Op=x, Cmode=101x.
4607       OpCmode = 0xa;
4608       Imm = SplatBits >> 8;
4609       break;
4610     }
4611     return SDValue();
4612
4613   case 32:
4614     // NEON's 32-bit VMOV supports splat values where:
4615     // * only one byte is nonzero, or
4616     // * the least significant byte is 0xff and the second byte is nonzero, or
4617     // * the least significant 2 bytes are 0xff and the third is nonzero.
4618     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4619     if ((SplatBits & ~0xff) == 0) {
4620       // Value = 0x000000nn: Op=x, Cmode=000x.
4621       OpCmode = 0;
4622       Imm = SplatBits;
4623       break;
4624     }
4625     if ((SplatBits & ~0xff00) == 0) {
4626       // Value = 0x0000nn00: Op=x, Cmode=001x.
4627       OpCmode = 0x2;
4628       Imm = SplatBits >> 8;
4629       break;
4630     }
4631     if ((SplatBits & ~0xff0000) == 0) {
4632       // Value = 0x00nn0000: Op=x, Cmode=010x.
4633       OpCmode = 0x4;
4634       Imm = SplatBits >> 16;
4635       break;
4636     }
4637     if ((SplatBits & ~0xff000000) == 0) {
4638       // Value = 0xnn000000: Op=x, Cmode=011x.
4639       OpCmode = 0x6;
4640       Imm = SplatBits >> 24;
4641       break;
4642     }
4643
4644     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4645     if (type == OtherModImm) return SDValue();
4646
4647     if ((SplatBits & ~0xffff) == 0 &&
4648         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4649       // Value = 0x0000nnff: Op=x, Cmode=1100.
4650       OpCmode = 0xc;
4651       Imm = SplatBits >> 8;
4652       break;
4653     }
4654
4655     if ((SplatBits & ~0xffffff) == 0 &&
4656         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4657       // Value = 0x00nnffff: Op=x, Cmode=1101.
4658       OpCmode = 0xd;
4659       Imm = SplatBits >> 16;
4660       break;
4661     }
4662
4663     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4664     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4665     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4666     // and fall through here to test for a valid 64-bit splat.  But, then the
4667     // caller would also need to check and handle the change in size.
4668     return SDValue();
4669
4670   case 64: {
4671     if (type != VMOVModImm)
4672       return SDValue();
4673     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4674     uint64_t BitMask = 0xff;
4675     uint64_t Val = 0;
4676     unsigned ImmMask = 1;
4677     Imm = 0;
4678     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4679       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4680         Val |= BitMask;
4681         Imm |= ImmMask;
4682       } else if ((SplatBits & BitMask) != 0) {
4683         return SDValue();
4684       }
4685       BitMask <<= 8;
4686       ImmMask <<= 1;
4687     }
4688
4689     if (DAG.getTargetLoweringInfo().isBigEndian())
4690       // swap higher and lower 32 bit word
4691       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4692
4693     // Op=1, Cmode=1110.
4694     OpCmode = 0x1e;
4695     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4696     break;
4697   }
4698
4699   default:
4700     llvm_unreachable("unexpected size for isNEONModifiedImm");
4701   }
4702
4703   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4704   return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
4705 }
4706
4707 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4708                                            const ARMSubtarget *ST) const {
4709   if (!ST->hasVFP3())
4710     return SDValue();
4711
4712   bool IsDouble = Op.getValueType() == MVT::f64;
4713   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4714
4715   // Use the default (constant pool) lowering for double constants when we have
4716   // an SP-only FPU
4717   if (IsDouble && Subtarget->isFPOnlySP())
4718     return SDValue();
4719
4720   // Try splatting with a VMOV.f32...
4721   APFloat FPVal = CFP->getValueAPF();
4722   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4723
4724   if (ImmVal != -1) {
4725     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4726       // We have code in place to select a valid ConstantFP already, no need to
4727       // do any mangling.
4728       return Op;
4729     }
4730
4731     // It's a float and we are trying to use NEON operations where
4732     // possible. Lower it to a splat followed by an extract.
4733     SDLoc DL(Op);
4734     SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
4735     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4736                                       NewVal);
4737     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4738                        DAG.getConstant(0, DL, MVT::i32));
4739   }
4740
4741   // The rest of our options are NEON only, make sure that's allowed before
4742   // proceeding..
4743   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4744     return SDValue();
4745
4746   EVT VMovVT;
4747   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4748
4749   // It wouldn't really be worth bothering for doubles except for one very
4750   // important value, which does happen to match: 0.0. So make sure we don't do
4751   // anything stupid.
4752   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4753     return SDValue();
4754
4755   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4756   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
4757                                      VMovVT, false, VMOVModImm);
4758   if (NewVal != SDValue()) {
4759     SDLoc DL(Op);
4760     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4761                                       NewVal);
4762     if (IsDouble)
4763       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4764
4765     // It's a float: cast and extract a vector element.
4766     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4767                                        VecConstant);
4768     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4769                        DAG.getConstant(0, DL, MVT::i32));
4770   }
4771
4772   // Finally, try a VMVN.i32
4773   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
4774                              false, VMVNModImm);
4775   if (NewVal != SDValue()) {
4776     SDLoc DL(Op);
4777     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4778
4779     if (IsDouble)
4780       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4781
4782     // It's a float: cast and extract a vector element.
4783     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4784                                        VecConstant);
4785     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4786                        DAG.getConstant(0, DL, MVT::i32));
4787   }
4788
4789   return SDValue();
4790 }
4791
4792 // check if an VEXT instruction can handle the shuffle mask when the
4793 // vector sources of the shuffle are the same.
4794 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4795   unsigned NumElts = VT.getVectorNumElements();
4796
4797   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4798   if (M[0] < 0)
4799     return false;
4800
4801   Imm = M[0];
4802
4803   // If this is a VEXT shuffle, the immediate value is the index of the first
4804   // element.  The other shuffle indices must be the successive elements after
4805   // the first one.
4806   unsigned ExpectedElt = Imm;
4807   for (unsigned i = 1; i < NumElts; ++i) {
4808     // Increment the expected index.  If it wraps around, just follow it
4809     // back to index zero and keep going.
4810     ++ExpectedElt;
4811     if (ExpectedElt == NumElts)
4812       ExpectedElt = 0;
4813
4814     if (M[i] < 0) continue; // ignore UNDEF indices
4815     if (ExpectedElt != static_cast<unsigned>(M[i]))
4816       return false;
4817   }
4818
4819   return true;
4820 }
4821
4822
4823 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4824                        bool &ReverseVEXT, unsigned &Imm) {
4825   unsigned NumElts = VT.getVectorNumElements();
4826   ReverseVEXT = false;
4827
4828   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4829   if (M[0] < 0)
4830     return false;
4831
4832   Imm = M[0];
4833
4834   // If this is a VEXT shuffle, the immediate value is the index of the first
4835   // element.  The other shuffle indices must be the successive elements after
4836   // the first one.
4837   unsigned ExpectedElt = Imm;
4838   for (unsigned i = 1; i < NumElts; ++i) {
4839     // Increment the expected index.  If it wraps around, it may still be
4840     // a VEXT but the source vectors must be swapped.
4841     ExpectedElt += 1;
4842     if (ExpectedElt == NumElts * 2) {
4843       ExpectedElt = 0;
4844       ReverseVEXT = true;
4845     }
4846
4847     if (M[i] < 0) continue; // ignore UNDEF indices
4848     if (ExpectedElt != static_cast<unsigned>(M[i]))
4849       return false;
4850   }
4851
4852   // Adjust the index value if the source operands will be swapped.
4853   if (ReverseVEXT)
4854     Imm -= NumElts;
4855
4856   return true;
4857 }
4858
4859 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4860 /// instruction with the specified blocksize.  (The order of the elements
4861 /// within each block of the vector is reversed.)
4862 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4863   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4864          "Only possible block sizes for VREV are: 16, 32, 64");
4865
4866   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4867   if (EltSz == 64)
4868     return false;
4869
4870   unsigned NumElts = VT.getVectorNumElements();
4871   unsigned BlockElts = M[0] + 1;
4872   // If the first shuffle index is UNDEF, be optimistic.
4873   if (M[0] < 0)
4874     BlockElts = BlockSize / EltSz;
4875
4876   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4877     return false;
4878
4879   for (unsigned i = 0; i < NumElts; ++i) {
4880     if (M[i] < 0) continue; // ignore UNDEF indices
4881     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4882       return false;
4883   }
4884
4885   return true;
4886 }
4887
4888 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4889   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4890   // range, then 0 is placed into the resulting vector. So pretty much any mask
4891   // of 8 elements can work here.
4892   return VT == MVT::v8i8 && M.size() == 8;
4893 }
4894
4895 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4896   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4897   if (EltSz == 64)
4898     return false;
4899
4900   unsigned NumElts = VT.getVectorNumElements();
4901   WhichResult = (M[0] == 0 ? 0 : 1);
4902   for (unsigned i = 0; i < NumElts; i += 2) {
4903     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4904         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4905       return false;
4906   }
4907   return true;
4908 }
4909
4910 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4911 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4912 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4913 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4914   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4915   if (EltSz == 64)
4916     return false;
4917
4918   unsigned NumElts = VT.getVectorNumElements();
4919   WhichResult = (M[0] == 0 ? 0 : 1);
4920   for (unsigned i = 0; i < NumElts; i += 2) {
4921     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4922         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4923       return false;
4924   }
4925   return true;
4926 }
4927
4928 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4929   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4930   if (EltSz == 64)
4931     return false;
4932
4933   unsigned NumElts = VT.getVectorNumElements();
4934   WhichResult = (M[0] == 0 ? 0 : 1);
4935   for (unsigned i = 0; i != NumElts; ++i) {
4936     if (M[i] < 0) continue; // ignore UNDEF indices
4937     if ((unsigned) M[i] != 2 * i + WhichResult)
4938       return false;
4939   }
4940
4941   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4942   if (VT.is64BitVector() && EltSz == 32)
4943     return false;
4944
4945   return true;
4946 }
4947
4948 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4949 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4950 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4951 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4952   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4953   if (EltSz == 64)
4954     return false;
4955
4956   unsigned Half = VT.getVectorNumElements() / 2;
4957   WhichResult = (M[0] == 0 ? 0 : 1);
4958   for (unsigned j = 0; j != 2; ++j) {
4959     unsigned Idx = WhichResult;
4960     for (unsigned i = 0; i != Half; ++i) {
4961       int MIdx = M[i + j * Half];
4962       if (MIdx >= 0 && (unsigned) MIdx != Idx)
4963         return false;
4964       Idx += 2;
4965     }
4966   }
4967
4968   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4969   if (VT.is64BitVector() && EltSz == 32)
4970     return false;
4971
4972   return true;
4973 }
4974
4975 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4976   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4977   if (EltSz == 64)
4978     return false;
4979
4980   unsigned NumElts = VT.getVectorNumElements();
4981   WhichResult = (M[0] == 0 ? 0 : 1);
4982   unsigned Idx = WhichResult * NumElts / 2;
4983   for (unsigned i = 0; i != NumElts; i += 2) {
4984     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4985         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4986       return false;
4987     Idx += 1;
4988   }
4989
4990   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4991   if (VT.is64BitVector() && EltSz == 32)
4992     return false;
4993
4994   return true;
4995 }
4996
4997 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4998 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4999 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5000 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5001   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5002   if (EltSz == 64)
5003     return false;
5004
5005   unsigned NumElts = VT.getVectorNumElements();
5006   WhichResult = (M[0] == 0 ? 0 : 1);
5007   unsigned Idx = WhichResult * NumElts / 2;
5008   for (unsigned i = 0; i != NumElts; i += 2) {
5009     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
5010         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
5011       return false;
5012     Idx += 1;
5013   }
5014
5015   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5016   if (VT.is64BitVector() && EltSz == 32)
5017     return false;
5018
5019   return true;
5020 }
5021
5022 /// \return true if this is a reverse operation on an vector.
5023 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5024   unsigned NumElts = VT.getVectorNumElements();
5025   // Make sure the mask has the right size.
5026   if (NumElts != M.size())
5027       return false;
5028
5029   // Look for <15, ..., 3, -1, 1, 0>.
5030   for (unsigned i = 0; i != NumElts; ++i)
5031     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5032       return false;
5033
5034   return true;
5035 }
5036
5037 // If N is an integer constant that can be moved into a register in one
5038 // instruction, return an SDValue of such a constant (will become a MOV
5039 // instruction).  Otherwise return null.
5040 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5041                                      const ARMSubtarget *ST, SDLoc dl) {
5042   uint64_t Val;
5043   if (!isa<ConstantSDNode>(N))
5044     return SDValue();
5045   Val = cast<ConstantSDNode>(N)->getZExtValue();
5046
5047   if (ST->isThumb1Only()) {
5048     if (Val <= 255 || ~Val <= 255)
5049       return DAG.getConstant(Val, dl, MVT::i32);
5050   } else {
5051     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5052       return DAG.getConstant(Val, dl, MVT::i32);
5053   }
5054   return SDValue();
5055 }
5056
5057 // If this is a case we can't handle, return null and let the default
5058 // expansion code take care of it.
5059 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5060                                              const ARMSubtarget *ST) const {
5061   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5062   SDLoc dl(Op);
5063   EVT VT = Op.getValueType();
5064
5065   APInt SplatBits, SplatUndef;
5066   unsigned SplatBitSize;
5067   bool HasAnyUndefs;
5068   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5069     if (SplatBitSize <= 64) {
5070       // Check if an immediate VMOV works.
5071       EVT VmovVT;
5072       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5073                                       SplatUndef.getZExtValue(), SplatBitSize,
5074                                       DAG, dl, VmovVT, VT.is128BitVector(),
5075                                       VMOVModImm);
5076       if (Val.getNode()) {
5077         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5078         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5079       }
5080
5081       // Try an immediate VMVN.
5082       uint64_t NegatedImm = (~SplatBits).getZExtValue();
5083       Val = isNEONModifiedImm(NegatedImm,
5084                                       SplatUndef.getZExtValue(), SplatBitSize,
5085                                       DAG, dl, VmovVT, VT.is128BitVector(),
5086                                       VMVNModImm);
5087       if (Val.getNode()) {
5088         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5089         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5090       }
5091
5092       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5093       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5094         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5095         if (ImmVal != -1) {
5096           SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
5097           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5098         }
5099       }
5100     }
5101   }
5102
5103   // Scan through the operands to see if only one value is used.
5104   //
5105   // As an optimisation, even if more than one value is used it may be more
5106   // profitable to splat with one value then change some lanes.
5107   //
5108   // Heuristically we decide to do this if the vector has a "dominant" value,
5109   // defined as splatted to more than half of the lanes.
5110   unsigned NumElts = VT.getVectorNumElements();
5111   bool isOnlyLowElement = true;
5112   bool usesOnlyOneValue = true;
5113   bool hasDominantValue = false;
5114   bool isConstant = true;
5115
5116   // Map of the number of times a particular SDValue appears in the
5117   // element list.
5118   DenseMap<SDValue, unsigned> ValueCounts;
5119   SDValue Value;
5120   for (unsigned i = 0; i < NumElts; ++i) {
5121     SDValue V = Op.getOperand(i);
5122     if (V.getOpcode() == ISD::UNDEF)
5123       continue;
5124     if (i > 0)
5125       isOnlyLowElement = false;
5126     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5127       isConstant = false;
5128
5129     ValueCounts.insert(std::make_pair(V, 0));
5130     unsigned &Count = ValueCounts[V];
5131
5132     // Is this value dominant? (takes up more than half of the lanes)
5133     if (++Count > (NumElts / 2)) {
5134       hasDominantValue = true;
5135       Value = V;
5136     }
5137   }
5138   if (ValueCounts.size() != 1)
5139     usesOnlyOneValue = false;
5140   if (!Value.getNode() && ValueCounts.size() > 0)
5141     Value = ValueCounts.begin()->first;
5142
5143   if (ValueCounts.size() == 0)
5144     return DAG.getUNDEF(VT);
5145
5146   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5147   // Keep going if we are hitting this case.
5148   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5149     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5150
5151   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5152
5153   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
5154   // i32 and try again.
5155   if (hasDominantValue && EltSize <= 32) {
5156     if (!isConstant) {
5157       SDValue N;
5158
5159       // If we are VDUPing a value that comes directly from a vector, that will
5160       // cause an unnecessary move to and from a GPR, where instead we could
5161       // just use VDUPLANE. We can only do this if the lane being extracted
5162       // is at a constant index, as the VDUP from lane instructions only have
5163       // constant-index forms.
5164       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5165           isa<ConstantSDNode>(Value->getOperand(1))) {
5166         // We need to create a new undef vector to use for the VDUPLANE if the
5167         // size of the vector from which we get the value is different than the
5168         // size of the vector that we need to create. We will insert the element
5169         // such that the register coalescer will remove unnecessary copies.
5170         if (VT != Value->getOperand(0).getValueType()) {
5171           ConstantSDNode *constIndex;
5172           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5173           assert(constIndex && "The index is not a constant!");
5174           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5175                              VT.getVectorNumElements();
5176           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5177                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5178                         Value, DAG.getConstant(index, dl, MVT::i32)),
5179                            DAG.getConstant(index, dl, MVT::i32));
5180         } else
5181           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5182                         Value->getOperand(0), Value->getOperand(1));
5183       } else
5184         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5185
5186       if (!usesOnlyOneValue) {
5187         // The dominant value was splatted as 'N', but we now have to insert
5188         // all differing elements.
5189         for (unsigned I = 0; I < NumElts; ++I) {
5190           if (Op.getOperand(I) == Value)
5191             continue;
5192           SmallVector<SDValue, 3> Ops;
5193           Ops.push_back(N);
5194           Ops.push_back(Op.getOperand(I));
5195           Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
5196           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5197         }
5198       }
5199       return N;
5200     }
5201     if (VT.getVectorElementType().isFloatingPoint()) {
5202       SmallVector<SDValue, 8> Ops;
5203       for (unsigned i = 0; i < NumElts; ++i)
5204         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5205                                   Op.getOperand(i)));
5206       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5207       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5208       Val = LowerBUILD_VECTOR(Val, DAG, ST);
5209       if (Val.getNode())
5210         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5211     }
5212     if (usesOnlyOneValue) {
5213       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5214       if (isConstant && Val.getNode())
5215         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5216     }
5217   }
5218
5219   // If all elements are constants and the case above didn't get hit, fall back
5220   // to the default expansion, which will generate a load from the constant
5221   // pool.
5222   if (isConstant)
5223     return SDValue();
5224
5225   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5226   if (NumElts >= 4) {
5227     SDValue shuffle = ReconstructShuffle(Op, DAG);
5228     if (shuffle != SDValue())
5229       return shuffle;
5230   }
5231
5232   // Vectors with 32- or 64-bit elements can be built by directly assigning
5233   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
5234   // will be legalized.
5235   if (EltSize >= 32) {
5236     // Do the expansion with floating-point types, since that is what the VFP
5237     // registers are defined to use, and since i64 is not legal.
5238     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5239     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5240     SmallVector<SDValue, 8> Ops;
5241     for (unsigned i = 0; i < NumElts; ++i)
5242       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5243     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5244     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5245   }
5246
5247   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5248   // know the default expansion would otherwise fall back on something even
5249   // worse. For a vector with one or two non-undef values, that's
5250   // scalar_to_vector for the elements followed by a shuffle (provided the
5251   // shuffle is valid for the target) and materialization element by element
5252   // on the stack followed by a load for everything else.
5253   if (!isConstant && !usesOnlyOneValue) {
5254     SDValue Vec = DAG.getUNDEF(VT);
5255     for (unsigned i = 0 ; i < NumElts; ++i) {
5256       SDValue V = Op.getOperand(i);
5257       if (V.getOpcode() == ISD::UNDEF)
5258         continue;
5259       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
5260       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5261     }
5262     return Vec;
5263   }
5264
5265   return SDValue();
5266 }
5267
5268 // Gather data to see if the operation can be modelled as a
5269 // shuffle in combination with VEXTs.
5270 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5271                                               SelectionDAG &DAG) const {
5272   SDLoc dl(Op);
5273   EVT VT = Op.getValueType();
5274   unsigned NumElts = VT.getVectorNumElements();
5275
5276   SmallVector<SDValue, 2> SourceVecs;
5277   SmallVector<unsigned, 2> MinElts;
5278   SmallVector<unsigned, 2> MaxElts;
5279
5280   for (unsigned i = 0; i < NumElts; ++i) {
5281     SDValue V = Op.getOperand(i);
5282     if (V.getOpcode() == ISD::UNDEF)
5283       continue;
5284     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5285       // A shuffle can only come from building a vector from various
5286       // elements of other vectors.
5287       return SDValue();
5288     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5289                VT.getVectorElementType()) {
5290       // This code doesn't know how to handle shuffles where the vector
5291       // element types do not match (this happens because type legalization
5292       // promotes the return type of EXTRACT_VECTOR_ELT).
5293       // FIXME: It might be appropriate to extend this code to handle
5294       // mismatched types.
5295       return SDValue();
5296     }
5297
5298     // Record this extraction against the appropriate vector if possible...
5299     SDValue SourceVec = V.getOperand(0);
5300     // If the element number isn't a constant, we can't effectively
5301     // analyze what's going on.
5302     if (!isa<ConstantSDNode>(V.getOperand(1)))
5303       return SDValue();
5304     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5305     bool FoundSource = false;
5306     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5307       if (SourceVecs[j] == SourceVec) {
5308         if (MinElts[j] > EltNo)
5309           MinElts[j] = EltNo;
5310         if (MaxElts[j] < EltNo)
5311           MaxElts[j] = EltNo;
5312         FoundSource = true;
5313         break;
5314       }
5315     }
5316
5317     // Or record a new source if not...
5318     if (!FoundSource) {
5319       SourceVecs.push_back(SourceVec);
5320       MinElts.push_back(EltNo);
5321       MaxElts.push_back(EltNo);
5322     }
5323   }
5324
5325   // Currently only do something sane when at most two source vectors
5326   // involved.
5327   if (SourceVecs.size() > 2)
5328     return SDValue();
5329
5330   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5331   int VEXTOffsets[2] = {0, 0};
5332
5333   // This loop extracts the usage patterns of the source vectors
5334   // and prepares appropriate SDValues for a shuffle if possible.
5335   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5336     if (SourceVecs[i].getValueType() == VT) {
5337       // No VEXT necessary
5338       ShuffleSrcs[i] = SourceVecs[i];
5339       VEXTOffsets[i] = 0;
5340       continue;
5341     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5342       // It probably isn't worth padding out a smaller vector just to
5343       // break it down again in a shuffle.
5344       return SDValue();
5345     }
5346
5347     // Since only 64-bit and 128-bit vectors are legal on ARM and
5348     // we've eliminated the other cases...
5349     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5350            "unexpected vector sizes in ReconstructShuffle");
5351
5352     if (MaxElts[i] - MinElts[i] >= NumElts) {
5353       // Span too large for a VEXT to cope
5354       return SDValue();
5355     }
5356
5357     if (MinElts[i] >= NumElts) {
5358       // The extraction can just take the second half
5359       VEXTOffsets[i] = NumElts;
5360       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5361                                    SourceVecs[i],
5362                                    DAG.getIntPtrConstant(NumElts, dl));
5363     } else if (MaxElts[i] < NumElts) {
5364       // The extraction can just take the first half
5365       VEXTOffsets[i] = 0;
5366       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5367                                    SourceVecs[i],
5368                                    DAG.getIntPtrConstant(0, dl));
5369     } else {
5370       // An actual VEXT is needed
5371       VEXTOffsets[i] = MinElts[i];
5372       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5373                                      SourceVecs[i],
5374                                      DAG.getIntPtrConstant(0, dl));
5375       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5376                                      SourceVecs[i],
5377                                      DAG.getIntPtrConstant(NumElts, dl));
5378       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5379                                    DAG.getConstant(VEXTOffsets[i], dl,
5380                                                    MVT::i32));
5381     }
5382   }
5383
5384   SmallVector<int, 8> Mask;
5385
5386   for (unsigned i = 0; i < NumElts; ++i) {
5387     SDValue Entry = Op.getOperand(i);
5388     if (Entry.getOpcode() == ISD::UNDEF) {
5389       Mask.push_back(-1);
5390       continue;
5391     }
5392
5393     SDValue ExtractVec = Entry.getOperand(0);
5394     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5395                                           .getOperand(1))->getSExtValue();
5396     if (ExtractVec == SourceVecs[0]) {
5397       Mask.push_back(ExtractElt - VEXTOffsets[0]);
5398     } else {
5399       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5400     }
5401   }
5402
5403   // Final check before we try to produce nonsense...
5404   if (isShuffleMaskLegal(Mask, VT))
5405     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5406                                 &Mask[0]);
5407
5408   return SDValue();
5409 }
5410
5411 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5412 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5413 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5414 /// are assumed to be legal.
5415 bool
5416 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5417                                       EVT VT) const {
5418   if (VT.getVectorNumElements() == 4 &&
5419       (VT.is128BitVector() || VT.is64BitVector())) {
5420     unsigned PFIndexes[4];
5421     for (unsigned i = 0; i != 4; ++i) {
5422       if (M[i] < 0)
5423         PFIndexes[i] = 8;
5424       else
5425         PFIndexes[i] = M[i];
5426     }
5427
5428     // Compute the index in the perfect shuffle table.
5429     unsigned PFTableIndex =
5430       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5431     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5432     unsigned Cost = (PFEntry >> 30);
5433
5434     if (Cost <= 4)
5435       return true;
5436   }
5437
5438   bool ReverseVEXT;
5439   unsigned Imm, WhichResult;
5440
5441   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5442   return (EltSize >= 32 ||
5443           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5444           isVREVMask(M, VT, 64) ||
5445           isVREVMask(M, VT, 32) ||
5446           isVREVMask(M, VT, 16) ||
5447           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5448           isVTBLMask(M, VT) ||
5449           isVTRNMask(M, VT, WhichResult) ||
5450           isVUZPMask(M, VT, WhichResult) ||
5451           isVZIPMask(M, VT, WhichResult) ||
5452           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5453           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5454           isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5455           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5456 }
5457
5458 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5459 /// the specified operations to build the shuffle.
5460 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5461                                       SDValue RHS, SelectionDAG &DAG,
5462                                       SDLoc dl) {
5463   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5464   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5465   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5466
5467   enum {
5468     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5469     OP_VREV,
5470     OP_VDUP0,
5471     OP_VDUP1,
5472     OP_VDUP2,
5473     OP_VDUP3,
5474     OP_VEXT1,
5475     OP_VEXT2,
5476     OP_VEXT3,
5477     OP_VUZPL, // VUZP, left result
5478     OP_VUZPR, // VUZP, right result
5479     OP_VZIPL, // VZIP, left result
5480     OP_VZIPR, // VZIP, right result
5481     OP_VTRNL, // VTRN, left result
5482     OP_VTRNR  // VTRN, right result
5483   };
5484
5485   if (OpNum == OP_COPY) {
5486     if (LHSID == (1*9+2)*9+3) return LHS;
5487     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5488     return RHS;
5489   }
5490
5491   SDValue OpLHS, OpRHS;
5492   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5493   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5494   EVT VT = OpLHS.getValueType();
5495
5496   switch (OpNum) {
5497   default: llvm_unreachable("Unknown shuffle opcode!");
5498   case OP_VREV:
5499     // VREV divides the vector in half and swaps within the half.
5500     if (VT.getVectorElementType() == MVT::i32 ||
5501         VT.getVectorElementType() == MVT::f32)
5502       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5503     // vrev <4 x i16> -> VREV32
5504     if (VT.getVectorElementType() == MVT::i16)
5505       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5506     // vrev <4 x i8> -> VREV16
5507     assert(VT.getVectorElementType() == MVT::i8);
5508     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5509   case OP_VDUP0:
5510   case OP_VDUP1:
5511   case OP_VDUP2:
5512   case OP_VDUP3:
5513     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5514                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
5515   case OP_VEXT1:
5516   case OP_VEXT2:
5517   case OP_VEXT3:
5518     return DAG.getNode(ARMISD::VEXT, dl, VT,
5519                        OpLHS, OpRHS,
5520                        DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
5521   case OP_VUZPL:
5522   case OP_VUZPR:
5523     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5524                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5525   case OP_VZIPL:
5526   case OP_VZIPR:
5527     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5528                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5529   case OP_VTRNL:
5530   case OP_VTRNR:
5531     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5532                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5533   }
5534 }
5535
5536 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5537                                        ArrayRef<int> ShuffleMask,
5538                                        SelectionDAG &DAG) {
5539   // Check to see if we can use the VTBL instruction.
5540   SDValue V1 = Op.getOperand(0);
5541   SDValue V2 = Op.getOperand(1);
5542   SDLoc DL(Op);
5543
5544   SmallVector<SDValue, 8> VTBLMask;
5545   for (ArrayRef<int>::iterator
5546          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5547     VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
5548
5549   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5550     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5551                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5552
5553   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5554                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5555 }
5556
5557 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5558                                                       SelectionDAG &DAG) {
5559   SDLoc DL(Op);
5560   SDValue OpLHS = Op.getOperand(0);
5561   EVT VT = OpLHS.getValueType();
5562
5563   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5564          "Expect an v8i16/v16i8 type");
5565   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5566   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5567   // extract the first 8 bytes into the top double word and the last 8 bytes
5568   // into the bottom double word. The v8i16 case is similar.
5569   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5570   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5571                      DAG.getConstant(ExtractNum, DL, MVT::i32));
5572 }
5573
5574 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5575   SDValue V1 = Op.getOperand(0);
5576   SDValue V2 = Op.getOperand(1);
5577   SDLoc dl(Op);
5578   EVT VT = Op.getValueType();
5579   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5580
5581   // Convert shuffles that are directly supported on NEON to target-specific
5582   // DAG nodes, instead of keeping them as shuffles and matching them again
5583   // during code selection.  This is more efficient and avoids the possibility
5584   // of inconsistencies between legalization and selection.
5585   // FIXME: floating-point vectors should be canonicalized to integer vectors
5586   // of the same time so that they get CSEd properly.
5587   ArrayRef<int> ShuffleMask = SVN->getMask();
5588
5589   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5590   if (EltSize <= 32) {
5591     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5592       int Lane = SVN->getSplatIndex();
5593       // If this is undef splat, generate it via "just" vdup, if possible.
5594       if (Lane == -1) Lane = 0;
5595
5596       // Test if V1 is a SCALAR_TO_VECTOR.
5597       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5598         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5599       }
5600       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5601       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5602       // reaches it).
5603       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5604           !isa<ConstantSDNode>(V1.getOperand(0))) {
5605         bool IsScalarToVector = true;
5606         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5607           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5608             IsScalarToVector = false;
5609             break;
5610           }
5611         if (IsScalarToVector)
5612           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5613       }
5614       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5615                          DAG.getConstant(Lane, dl, MVT::i32));
5616     }
5617
5618     bool ReverseVEXT;
5619     unsigned Imm;
5620     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5621       if (ReverseVEXT)
5622         std::swap(V1, V2);
5623       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5624                          DAG.getConstant(Imm, dl, MVT::i32));
5625     }
5626
5627     if (isVREVMask(ShuffleMask, VT, 64))
5628       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5629     if (isVREVMask(ShuffleMask, VT, 32))
5630       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5631     if (isVREVMask(ShuffleMask, VT, 16))
5632       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5633
5634     if (V2->getOpcode() == ISD::UNDEF &&
5635         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5636       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5637                          DAG.getConstant(Imm, dl, MVT::i32));
5638     }
5639
5640     // Check for Neon shuffles that modify both input vectors in place.
5641     // If both results are used, i.e., if there are two shuffles with the same
5642     // source operands and with masks corresponding to both results of one of
5643     // these operations, DAG memoization will ensure that a single node is
5644     // used for both shuffles.
5645     unsigned WhichResult;
5646     if (isVTRNMask(ShuffleMask, VT, WhichResult))
5647       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5648                          V1, V2).getValue(WhichResult);
5649     if (isVUZPMask(ShuffleMask, VT, WhichResult))
5650       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5651                          V1, V2).getValue(WhichResult);
5652     if (isVZIPMask(ShuffleMask, VT, WhichResult))
5653       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5654                          V1, V2).getValue(WhichResult);
5655
5656     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5657       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5658                          V1, V1).getValue(WhichResult);
5659     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5660       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5661                          V1, V1).getValue(WhichResult);
5662     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5663       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5664                          V1, V1).getValue(WhichResult);
5665   }
5666
5667   // If the shuffle is not directly supported and it has 4 elements, use
5668   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5669   unsigned NumElts = VT.getVectorNumElements();
5670   if (NumElts == 4) {
5671     unsigned PFIndexes[4];
5672     for (unsigned i = 0; i != 4; ++i) {
5673       if (ShuffleMask[i] < 0)
5674         PFIndexes[i] = 8;
5675       else
5676         PFIndexes[i] = ShuffleMask[i];
5677     }
5678
5679     // Compute the index in the perfect shuffle table.
5680     unsigned PFTableIndex =
5681       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5682     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5683     unsigned Cost = (PFEntry >> 30);
5684
5685     if (Cost <= 4)
5686       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5687   }
5688
5689   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5690   if (EltSize >= 32) {
5691     // Do the expansion with floating-point types, since that is what the VFP
5692     // registers are defined to use, and since i64 is not legal.
5693     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5694     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5695     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5696     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5697     SmallVector<SDValue, 8> Ops;
5698     for (unsigned i = 0; i < NumElts; ++i) {
5699       if (ShuffleMask[i] < 0)
5700         Ops.push_back(DAG.getUNDEF(EltVT));
5701       else
5702         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5703                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
5704                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5705                                                   dl, MVT::i32)));
5706     }
5707     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5708     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5709   }
5710
5711   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5712     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5713
5714   if (VT == MVT::v8i8) {
5715     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5716     if (NewOp.getNode())
5717       return NewOp;
5718   }
5719
5720   return SDValue();
5721 }
5722
5723 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5724   // INSERT_VECTOR_ELT is legal only for immediate indexes.
5725   SDValue Lane = Op.getOperand(2);
5726   if (!isa<ConstantSDNode>(Lane))
5727     return SDValue();
5728
5729   return Op;
5730 }
5731
5732 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5733   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5734   SDValue Lane = Op.getOperand(1);
5735   if (!isa<ConstantSDNode>(Lane))
5736     return SDValue();
5737
5738   SDValue Vec = Op.getOperand(0);
5739   if (Op.getValueType() == MVT::i32 &&
5740       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5741     SDLoc dl(Op);
5742     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5743   }
5744
5745   return Op;
5746 }
5747
5748 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5749   // The only time a CONCAT_VECTORS operation can have legal types is when
5750   // two 64-bit vectors are concatenated to a 128-bit vector.
5751   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5752          "unexpected CONCAT_VECTORS");
5753   SDLoc dl(Op);
5754   SDValue Val = DAG.getUNDEF(MVT::v2f64);
5755   SDValue Op0 = Op.getOperand(0);
5756   SDValue Op1 = Op.getOperand(1);
5757   if (Op0.getOpcode() != ISD::UNDEF)
5758     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5759                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5760                       DAG.getIntPtrConstant(0, dl));
5761   if (Op1.getOpcode() != ISD::UNDEF)
5762     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5763                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5764                       DAG.getIntPtrConstant(1, dl));
5765   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5766 }
5767
5768 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5769 /// element has been zero/sign-extended, depending on the isSigned parameter,
5770 /// from an integer type half its size.
5771 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5772                                    bool isSigned) {
5773   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5774   EVT VT = N->getValueType(0);
5775   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5776     SDNode *BVN = N->getOperand(0).getNode();
5777     if (BVN->getValueType(0) != MVT::v4i32 ||
5778         BVN->getOpcode() != ISD::BUILD_VECTOR)
5779       return false;
5780     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5781     unsigned HiElt = 1 - LoElt;
5782     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5783     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5784     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5785     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5786     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5787       return false;
5788     if (isSigned) {
5789       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5790           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5791         return true;
5792     } else {
5793       if (Hi0->isNullValue() && Hi1->isNullValue())
5794         return true;
5795     }
5796     return false;
5797   }
5798
5799   if (N->getOpcode() != ISD::BUILD_VECTOR)
5800     return false;
5801
5802   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5803     SDNode *Elt = N->getOperand(i).getNode();
5804     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5805       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5806       unsigned HalfSize = EltSize / 2;
5807       if (isSigned) {
5808         if (!isIntN(HalfSize, C->getSExtValue()))
5809           return false;
5810       } else {
5811         if (!isUIntN(HalfSize, C->getZExtValue()))
5812           return false;
5813       }
5814       continue;
5815     }
5816     return false;
5817   }
5818
5819   return true;
5820 }
5821
5822 /// isSignExtended - Check if a node is a vector value that is sign-extended
5823 /// or a constant BUILD_VECTOR with sign-extended elements.
5824 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5825   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5826     return true;
5827   if (isExtendedBUILD_VECTOR(N, DAG, true))
5828     return true;
5829   return false;
5830 }
5831
5832 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5833 /// or a constant BUILD_VECTOR with zero-extended elements.
5834 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5835   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5836     return true;
5837   if (isExtendedBUILD_VECTOR(N, DAG, false))
5838     return true;
5839   return false;
5840 }
5841
5842 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5843   if (OrigVT.getSizeInBits() >= 64)
5844     return OrigVT;
5845
5846   assert(OrigVT.isSimple() && "Expecting a simple value type");
5847
5848   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5849   switch (OrigSimpleTy) {
5850   default: llvm_unreachable("Unexpected Vector Type");
5851   case MVT::v2i8:
5852   case MVT::v2i16:
5853      return MVT::v2i32;
5854   case MVT::v4i8:
5855     return  MVT::v4i16;
5856   }
5857 }
5858
5859 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5860 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5861 /// We insert the required extension here to get the vector to fill a D register.
5862 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5863                                             const EVT &OrigTy,
5864                                             const EVT &ExtTy,
5865                                             unsigned ExtOpcode) {
5866   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5867   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5868   // 64-bits we need to insert a new extension so that it will be 64-bits.
5869   assert(ExtTy.is128BitVector() && "Unexpected extension size");
5870   if (OrigTy.getSizeInBits() >= 64)
5871     return N;
5872
5873   // Must extend size to at least 64 bits to be used as an operand for VMULL.
5874   EVT NewVT = getExtensionTo64Bits(OrigTy);
5875
5876   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5877 }
5878
5879 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5880 /// does not do any sign/zero extension. If the original vector is less
5881 /// than 64 bits, an appropriate extension will be added after the load to
5882 /// reach a total size of 64 bits. We have to add the extension separately
5883 /// because ARM does not have a sign/zero extending load for vectors.
5884 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5885   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5886
5887   // The load already has the right type.
5888   if (ExtendedTy == LD->getMemoryVT())
5889     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5890                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5891                 LD->isNonTemporal(), LD->isInvariant(),
5892                 LD->getAlignment());
5893
5894   // We need to create a zextload/sextload. We cannot just create a load
5895   // followed by a zext/zext node because LowerMUL is also run during normal
5896   // operation legalization where we can't create illegal types.
5897   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5898                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5899                         LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
5900                         LD->isNonTemporal(), LD->getAlignment());
5901 }
5902
5903 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5904 /// extending load, or BUILD_VECTOR with extended elements, return the
5905 /// unextended value. The unextended vector should be 64 bits so that it can
5906 /// be used as an operand to a VMULL instruction. If the original vector size
5907 /// before extension is less than 64 bits we add a an extension to resize
5908 /// the vector to 64 bits.
5909 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5910   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5911     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5912                                         N->getOperand(0)->getValueType(0),
5913                                         N->getValueType(0),
5914                                         N->getOpcode());
5915
5916   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5917     return SkipLoadExtensionForVMULL(LD, DAG);
5918
5919   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
5920   // have been legalized as a BITCAST from v4i32.
5921   if (N->getOpcode() == ISD::BITCAST) {
5922     SDNode *BVN = N->getOperand(0).getNode();
5923     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5924            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5925     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5926     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5927                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5928   }
5929   // Construct a new BUILD_VECTOR with elements truncated to half the size.
5930   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5931   EVT VT = N->getValueType(0);
5932   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5933   unsigned NumElts = VT.getVectorNumElements();
5934   MVT TruncVT = MVT::getIntegerVT(EltSize);
5935   SmallVector<SDValue, 8> Ops;
5936   SDLoc dl(N);
5937   for (unsigned i = 0; i != NumElts; ++i) {
5938     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5939     const APInt &CInt = C->getAPIntValue();
5940     // Element types smaller than 32 bits are not legal, so use i32 elements.
5941     // The values are implicitly truncated so sext vs. zext doesn't matter.
5942     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
5943   }
5944   return DAG.getNode(ISD::BUILD_VECTOR, dl,
5945                      MVT::getVectorVT(TruncVT, NumElts), Ops);
5946 }
5947
5948 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5949   unsigned Opcode = N->getOpcode();
5950   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5951     SDNode *N0 = N->getOperand(0).getNode();
5952     SDNode *N1 = N->getOperand(1).getNode();
5953     return N0->hasOneUse() && N1->hasOneUse() &&
5954       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5955   }
5956   return false;
5957 }
5958
5959 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5960   unsigned Opcode = N->getOpcode();
5961   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5962     SDNode *N0 = N->getOperand(0).getNode();
5963     SDNode *N1 = N->getOperand(1).getNode();
5964     return N0->hasOneUse() && N1->hasOneUse() &&
5965       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5966   }
5967   return false;
5968 }
5969
5970 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5971   // Multiplications are only custom-lowered for 128-bit vectors so that
5972   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
5973   EVT VT = Op.getValueType();
5974   assert(VT.is128BitVector() && VT.isInteger() &&
5975          "unexpected type for custom-lowering ISD::MUL");
5976   SDNode *N0 = Op.getOperand(0).getNode();
5977   SDNode *N1 = Op.getOperand(1).getNode();
5978   unsigned NewOpc = 0;
5979   bool isMLA = false;
5980   bool isN0SExt = isSignExtended(N0, DAG);
5981   bool isN1SExt = isSignExtended(N1, DAG);
5982   if (isN0SExt && isN1SExt)
5983     NewOpc = ARMISD::VMULLs;
5984   else {
5985     bool isN0ZExt = isZeroExtended(N0, DAG);
5986     bool isN1ZExt = isZeroExtended(N1, DAG);
5987     if (isN0ZExt && isN1ZExt)
5988       NewOpc = ARMISD::VMULLu;
5989     else if (isN1SExt || isN1ZExt) {
5990       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5991       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5992       if (isN1SExt && isAddSubSExt(N0, DAG)) {
5993         NewOpc = ARMISD::VMULLs;
5994         isMLA = true;
5995       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5996         NewOpc = ARMISD::VMULLu;
5997         isMLA = true;
5998       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5999         std::swap(N0, N1);
6000         NewOpc = ARMISD::VMULLu;
6001         isMLA = true;
6002       }
6003     }
6004
6005     if (!NewOpc) {
6006       if (VT == MVT::v2i64)
6007         // Fall through to expand this.  It is not legal.
6008         return SDValue();
6009       else
6010         // Other vector multiplications are legal.
6011         return Op;
6012     }
6013   }
6014
6015   // Legalize to a VMULL instruction.
6016   SDLoc DL(Op);
6017   SDValue Op0;
6018   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
6019   if (!isMLA) {
6020     Op0 = SkipExtensionForVMULL(N0, DAG);
6021     assert(Op0.getValueType().is64BitVector() &&
6022            Op1.getValueType().is64BitVector() &&
6023            "unexpected types for extended operands to VMULL");
6024     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
6025   }
6026
6027   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
6028   // isel lowering to take advantage of no-stall back to back vmul + vmla.
6029   //   vmull q0, d4, d6
6030   //   vmlal q0, d5, d6
6031   // is faster than
6032   //   vaddl q0, d4, d5
6033   //   vmovl q1, d6
6034   //   vmul  q0, q0, q1
6035   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
6036   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
6037   EVT Op1VT = Op1.getValueType();
6038   return DAG.getNode(N0->getOpcode(), DL, VT,
6039                      DAG.getNode(NewOpc, DL, VT,
6040                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
6041                      DAG.getNode(NewOpc, DL, VT,
6042                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
6043 }
6044
6045 static SDValue
6046 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
6047   // Convert to float
6048   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
6049   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
6050   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
6051   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
6052   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
6053   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
6054   // Get reciprocal estimate.
6055   // float4 recip = vrecpeq_f32(yf);
6056   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6057                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6058                    Y);
6059   // Because char has a smaller range than uchar, we can actually get away
6060   // without any newton steps.  This requires that we use a weird bias
6061   // of 0xb000, however (again, this has been exhaustively tested).
6062   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
6063   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
6064   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
6065   Y = DAG.getConstant(0xb000, dl, MVT::i32);
6066   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
6067   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6068   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6069   // Convert back to short.
6070   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6071   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6072   return X;
6073 }
6074
6075 static SDValue
6076 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
6077   SDValue N2;
6078   // Convert to float.
6079   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6080   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6081   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6082   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6083   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6084   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6085
6086   // Use reciprocal estimate and one refinement step.
6087   // float4 recip = vrecpeq_f32(yf);
6088   // recip *= vrecpsq_f32(yf, recip);
6089   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6090                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6091                    N1);
6092   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6093                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6094                    N1, N2);
6095   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6096   // Because short has a smaller range than ushort, we can actually get away
6097   // with only a single newton step.  This requires that we use a weird bias
6098   // of 89, however (again, this has been exhaustively tested).
6099   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6100   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6101   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6102   N1 = DAG.getConstant(0x89, dl, MVT::i32);
6103   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6104   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6105   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6106   // Convert back to integer and return.
6107   // return vmovn_s32(vcvt_s32_f32(result));
6108   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6109   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6110   return N0;
6111 }
6112
6113 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6114   EVT VT = Op.getValueType();
6115   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6116          "unexpected type for custom-lowering ISD::SDIV");
6117
6118   SDLoc dl(Op);
6119   SDValue N0 = Op.getOperand(0);
6120   SDValue N1 = Op.getOperand(1);
6121   SDValue N2, N3;
6122
6123   if (VT == MVT::v8i8) {
6124     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6125     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6126
6127     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6128                      DAG.getIntPtrConstant(4, dl));
6129     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6130                      DAG.getIntPtrConstant(4, dl));
6131     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6132                      DAG.getIntPtrConstant(0, dl));
6133     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6134                      DAG.getIntPtrConstant(0, dl));
6135
6136     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6137     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6138
6139     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6140     N0 = LowerCONCAT_VECTORS(N0, DAG);
6141
6142     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6143     return N0;
6144   }
6145   return LowerSDIV_v4i16(N0, N1, dl, DAG);
6146 }
6147
6148 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6149   EVT VT = Op.getValueType();
6150   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6151          "unexpected type for custom-lowering ISD::UDIV");
6152
6153   SDLoc dl(Op);
6154   SDValue N0 = Op.getOperand(0);
6155   SDValue N1 = Op.getOperand(1);
6156   SDValue N2, N3;
6157
6158   if (VT == MVT::v8i8) {
6159     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6160     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6161
6162     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6163                      DAG.getIntPtrConstant(4, dl));
6164     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6165                      DAG.getIntPtrConstant(4, dl));
6166     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6167                      DAG.getIntPtrConstant(0, dl));
6168     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6169                      DAG.getIntPtrConstant(0, dl));
6170
6171     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6172     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6173
6174     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6175     N0 = LowerCONCAT_VECTORS(N0, DAG);
6176
6177     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6178                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
6179                                      MVT::i32),
6180                      N0);
6181     return N0;
6182   }
6183
6184   // v4i16 sdiv ... Convert to float.
6185   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6186   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6187   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6188   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6189   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6190   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6191
6192   // Use reciprocal estimate and two refinement steps.
6193   // float4 recip = vrecpeq_f32(yf);
6194   // recip *= vrecpsq_f32(yf, recip);
6195   // recip *= vrecpsq_f32(yf, recip);
6196   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6197                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6198                    BN1);
6199   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6200                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6201                    BN1, N2);
6202   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6203   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6204                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6205                    BN1, N2);
6206   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6207   // Simply multiplying by the reciprocal estimate can leave us a few ulps
6208   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6209   // and that it will never cause us to return an answer too large).
6210   // float4 result = as_float4(as_int4(xf*recip) + 2);
6211   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6212   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6213   N1 = DAG.getConstant(2, dl, MVT::i32);
6214   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6215   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6216   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6217   // Convert back to integer and return.
6218   // return vmovn_u32(vcvt_s32_f32(result));
6219   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6220   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6221   return N0;
6222 }
6223
6224 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6225   EVT VT = Op.getNode()->getValueType(0);
6226   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6227
6228   unsigned Opc;
6229   bool ExtraOp = false;
6230   switch (Op.getOpcode()) {
6231   default: llvm_unreachable("Invalid code");
6232   case ISD::ADDC: Opc = ARMISD::ADDC; break;
6233   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6234   case ISD::SUBC: Opc = ARMISD::SUBC; break;
6235   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6236   }
6237
6238   if (!ExtraOp)
6239     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6240                        Op.getOperand(1));
6241   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6242                      Op.getOperand(1), Op.getOperand(2));
6243 }
6244
6245 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6246   assert(Subtarget->isTargetDarwin());
6247
6248   // For iOS, we want to call an alternative entry point: __sincos_stret,
6249   // return values are passed via sret.
6250   SDLoc dl(Op);
6251   SDValue Arg = Op.getOperand(0);
6252   EVT ArgVT = Arg.getValueType();
6253   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6254
6255   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6256   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6257
6258   // Pair of floats / doubles used to pass the result.
6259   StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
6260
6261   // Create stack object for sret.
6262   const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
6263   const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
6264   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6265   SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
6266
6267   ArgListTy Args;
6268   ArgListEntry Entry;
6269
6270   Entry.Node = SRet;
6271   Entry.Ty = RetTy->getPointerTo();
6272   Entry.isSExt = false;
6273   Entry.isZExt = false;
6274   Entry.isSRet = true;
6275   Args.push_back(Entry);
6276
6277   Entry.Node = Arg;
6278   Entry.Ty = ArgTy;
6279   Entry.isSExt = false;
6280   Entry.isZExt = false;
6281   Args.push_back(Entry);
6282
6283   const char *LibcallName  = (ArgVT == MVT::f64)
6284   ? "__sincos_stret" : "__sincosf_stret";
6285   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
6286
6287   TargetLowering::CallLoweringInfo CLI(DAG);
6288   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6289     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6290                std::move(Args), 0)
6291     .setDiscardResult();
6292
6293   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6294
6295   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6296                                 MachinePointerInfo(), false, false, false, 0);
6297
6298   // Address of cos field.
6299   SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
6300                             DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
6301   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6302                                 MachinePointerInfo(), false, false, false, 0);
6303
6304   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6305   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6306                      LoadSin.getValue(0), LoadCos.getValue(0));
6307 }
6308
6309 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6310   // Monotonic load/store is legal for all targets
6311   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6312     return Op;
6313
6314   // Acquire/Release load/store is not legal for targets without a
6315   // dmb or equivalent available.
6316   return SDValue();
6317 }
6318
6319 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6320                                     SmallVectorImpl<SDValue> &Results,
6321                                     SelectionDAG &DAG,
6322                                     const ARMSubtarget *Subtarget) {
6323   SDLoc DL(N);
6324   SDValue Cycles32, OutChain;
6325
6326   if (Subtarget->hasPerfMon()) {
6327     // Under Power Management extensions, the cycle-count is:
6328     //    mrc p15, #0, <Rt>, c9, c13, #0
6329     SDValue Ops[] = { N->getOperand(0), // Chain
6330                       DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
6331                       DAG.getConstant(15, DL, MVT::i32),
6332                       DAG.getConstant(0, DL, MVT::i32),
6333                       DAG.getConstant(9, DL, MVT::i32),
6334                       DAG.getConstant(13, DL, MVT::i32),
6335                       DAG.getConstant(0, DL, MVT::i32)
6336     };
6337
6338     Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6339                            DAG.getVTList(MVT::i32, MVT::Other), Ops);
6340     OutChain = Cycles32.getValue(1);
6341   } else {
6342     // Intrinsic is defined to return 0 on unsupported platforms. Technically
6343     // there are older ARM CPUs that have implementation-specific ways of
6344     // obtaining this information (FIXME!).
6345     Cycles32 = DAG.getConstant(0, DL, MVT::i32);
6346     OutChain = DAG.getEntryNode();
6347   }
6348
6349
6350   SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6351                                  Cycles32, DAG.getConstant(0, DL, MVT::i32));
6352   Results.push_back(Cycles64);
6353   Results.push_back(OutChain);
6354 }
6355
6356 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6357   switch (Op.getOpcode()) {
6358   default: llvm_unreachable("Don't know how to custom lower this!");
6359   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6360   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6361   case ISD::GlobalAddress:
6362     switch (Subtarget->getTargetTriple().getObjectFormat()) {
6363     default: llvm_unreachable("unknown object format");
6364     case Triple::COFF:
6365       return LowerGlobalAddressWindows(Op, DAG);
6366     case Triple::ELF:
6367       return LowerGlobalAddressELF(Op, DAG);
6368     case Triple::MachO:
6369       return LowerGlobalAddressDarwin(Op, DAG);
6370     }
6371   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6372   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6373   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6374   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6375   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6376   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6377   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6378   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6379   case ISD::SINT_TO_FP:
6380   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6381   case ISD::FP_TO_SINT:
6382   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6383   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6384   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6385   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6386   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6387   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6388   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6389   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6390                                                                Subtarget);
6391   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6392   case ISD::SHL:
6393   case ISD::SRL:
6394   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6395   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6396   case ISD::SRL_PARTS:
6397   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6398   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6399   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6400   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6401   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6402   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6403   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6404   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6405   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6406   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6407   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6408   case ISD::MUL:           return LowerMUL(Op, DAG);
6409   case ISD::SDIV:          return LowerSDIV(Op, DAG);
6410   case ISD::UDIV:          return LowerUDIV(Op, DAG);
6411   case ISD::ADDC:
6412   case ISD::ADDE:
6413   case ISD::SUBC:
6414   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6415   case ISD::SADDO:
6416   case ISD::UADDO:
6417   case ISD::SSUBO:
6418   case ISD::USUBO:
6419     return LowerXALUO(Op, DAG);
6420   case ISD::ATOMIC_LOAD:
6421   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6422   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6423   case ISD::SDIVREM:
6424   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6425   case ISD::DYNAMIC_STACKALLOC:
6426     if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6427       return LowerDYNAMIC_STACKALLOC(Op, DAG);
6428     llvm_unreachable("Don't know how to custom lower this!");
6429   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6430   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6431   }
6432 }
6433
6434 /// ReplaceNodeResults - Replace the results of node with an illegal result
6435 /// type with new values built out of custom code.
6436 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6437                                            SmallVectorImpl<SDValue>&Results,
6438                                            SelectionDAG &DAG) const {
6439   SDValue Res;
6440   switch (N->getOpcode()) {
6441   default:
6442     llvm_unreachable("Don't know how to custom expand this!");
6443   case ISD::BITCAST:
6444     Res = ExpandBITCAST(N, DAG);
6445     break;
6446   case ISD::SRL:
6447   case ISD::SRA:
6448     Res = Expand64BitShift(N, DAG, Subtarget);
6449     break;
6450   case ISD::READCYCLECOUNTER:
6451     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6452     return;
6453   }
6454   if (Res.getNode())
6455     Results.push_back(Res);
6456 }
6457
6458 //===----------------------------------------------------------------------===//
6459 //                           ARM Scheduler Hooks
6460 //===----------------------------------------------------------------------===//
6461
6462 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6463 /// registers the function context.
6464 void ARMTargetLowering::
6465 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6466                        MachineBasicBlock *DispatchBB, int FI) const {
6467   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6468   DebugLoc dl = MI->getDebugLoc();
6469   MachineFunction *MF = MBB->getParent();
6470   MachineRegisterInfo *MRI = &MF->getRegInfo();
6471   MachineConstantPool *MCP = MF->getConstantPool();
6472   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6473   const Function *F = MF->getFunction();
6474
6475   bool isThumb = Subtarget->isThumb();
6476   bool isThumb2 = Subtarget->isThumb2();
6477
6478   unsigned PCLabelId = AFI->createPICLabelUId();
6479   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6480   ARMConstantPoolValue *CPV =
6481     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6482   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6483
6484   const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
6485                                            : &ARM::GPRRegClass;
6486
6487   // Grab constant pool and fixed stack memory operands.
6488   MachineMemOperand *CPMMO =
6489     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6490                              MachineMemOperand::MOLoad, 4, 4);
6491
6492   MachineMemOperand *FIMMOSt =
6493     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6494                              MachineMemOperand::MOStore, 4, 4);
6495
6496   // Load the address of the dispatch MBB into the jump buffer.
6497   if (isThumb2) {
6498     // Incoming value: jbuf
6499     //   ldr.n  r5, LCPI1_1
6500     //   orr    r5, r5, #1
6501     //   add    r5, pc
6502     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6503     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6504     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6505                    .addConstantPoolIndex(CPI)
6506                    .addMemOperand(CPMMO));
6507     // Set the low bit because of thumb mode.
6508     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6509     AddDefaultCC(
6510       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6511                      .addReg(NewVReg1, RegState::Kill)
6512                      .addImm(0x01)));
6513     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6514     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6515       .addReg(NewVReg2, RegState::Kill)
6516       .addImm(PCLabelId);
6517     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6518                    .addReg(NewVReg3, RegState::Kill)
6519                    .addFrameIndex(FI)
6520                    .addImm(36)  // &jbuf[1] :: pc
6521                    .addMemOperand(FIMMOSt));
6522   } else if (isThumb) {
6523     // Incoming value: jbuf
6524     //   ldr.n  r1, LCPI1_4
6525     //   add    r1, pc
6526     //   mov    r2, #1
6527     //   orrs   r1, r2
6528     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6529     //   str    r1, [r2]
6530     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6531     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6532                    .addConstantPoolIndex(CPI)
6533                    .addMemOperand(CPMMO));
6534     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6535     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6536       .addReg(NewVReg1, RegState::Kill)
6537       .addImm(PCLabelId);
6538     // Set the low bit because of thumb mode.
6539     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6540     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6541                    .addReg(ARM::CPSR, RegState::Define)
6542                    .addImm(1));
6543     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6544     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6545                    .addReg(ARM::CPSR, RegState::Define)
6546                    .addReg(NewVReg2, RegState::Kill)
6547                    .addReg(NewVReg3, RegState::Kill));
6548     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6549     BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
6550             .addFrameIndex(FI)
6551             .addImm(36); // &jbuf[1] :: pc
6552     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6553                    .addReg(NewVReg4, RegState::Kill)
6554                    .addReg(NewVReg5, RegState::Kill)
6555                    .addImm(0)
6556                    .addMemOperand(FIMMOSt));
6557   } else {
6558     // Incoming value: jbuf
6559     //   ldr  r1, LCPI1_1
6560     //   add  r1, pc, r1
6561     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6562     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6563     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6564                    .addConstantPoolIndex(CPI)
6565                    .addImm(0)
6566                    .addMemOperand(CPMMO));
6567     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6568     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6569                    .addReg(NewVReg1, RegState::Kill)
6570                    .addImm(PCLabelId));
6571     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6572                    .addReg(NewVReg2, RegState::Kill)
6573                    .addFrameIndex(FI)
6574                    .addImm(36)  // &jbuf[1] :: pc
6575                    .addMemOperand(FIMMOSt));
6576   }
6577 }
6578
6579 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr *MI,
6580                                               MachineBasicBlock *MBB) const {
6581   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6582   DebugLoc dl = MI->getDebugLoc();
6583   MachineFunction *MF = MBB->getParent();
6584   MachineRegisterInfo *MRI = &MF->getRegInfo();
6585   MachineFrameInfo *MFI = MF->getFrameInfo();
6586   int FI = MFI->getFunctionContextIndex();
6587
6588   const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
6589                                                         : &ARM::GPRnopcRegClass;
6590
6591   // Get a mapping of the call site numbers to all of the landing pads they're
6592   // associated with.
6593   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6594   unsigned MaxCSNum = 0;
6595   MachineModuleInfo &MMI = MF->getMMI();
6596   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6597        ++BB) {
6598     if (!BB->isLandingPad()) continue;
6599
6600     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6601     // pad.
6602     for (MachineBasicBlock::iterator
6603            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6604       if (!II->isEHLabel()) continue;
6605
6606       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6607       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6608
6609       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6610       for (SmallVectorImpl<unsigned>::iterator
6611              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6612            CSI != CSE; ++CSI) {
6613         CallSiteNumToLPad[*CSI].push_back(BB);
6614         MaxCSNum = std::max(MaxCSNum, *CSI);
6615       }
6616       break;
6617     }
6618   }
6619
6620   // Get an ordered list of the machine basic blocks for the jump table.
6621   std::vector<MachineBasicBlock*> LPadList;
6622   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6623   LPadList.reserve(CallSiteNumToLPad.size());
6624   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6625     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6626     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6627            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6628       LPadList.push_back(*II);
6629       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6630     }
6631   }
6632
6633   assert(!LPadList.empty() &&
6634          "No landing pad destinations for the dispatch jump table!");
6635
6636   // Create the jump table and associated information.
6637   MachineJumpTableInfo *JTI =
6638     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6639   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6640   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6641
6642   // Create the MBBs for the dispatch code.
6643
6644   // Shove the dispatch's address into the return slot in the function context.
6645   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6646   DispatchBB->setIsLandingPad();
6647
6648   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6649   unsigned trap_opcode;
6650   if (Subtarget->isThumb())
6651     trap_opcode = ARM::tTRAP;
6652   else
6653     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6654
6655   BuildMI(TrapBB, dl, TII->get(trap_opcode));
6656   DispatchBB->addSuccessor(TrapBB);
6657
6658   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6659   DispatchBB->addSuccessor(DispContBB);
6660
6661   // Insert and MBBs.
6662   MF->insert(MF->end(), DispatchBB);
6663   MF->insert(MF->end(), DispContBB);
6664   MF->insert(MF->end(), TrapBB);
6665
6666   // Insert code into the entry block that creates and registers the function
6667   // context.
6668   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6669
6670   MachineMemOperand *FIMMOLd =
6671     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6672                              MachineMemOperand::MOLoad |
6673                              MachineMemOperand::MOVolatile, 4, 4);
6674
6675   MachineInstrBuilder MIB;
6676   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6677
6678   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6679   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6680
6681   // Add a register mask with no preserved registers.  This results in all
6682   // registers being marked as clobbered.
6683   MIB.addRegMask(RI.getNoPreservedMask());
6684
6685   unsigned NumLPads = LPadList.size();
6686   if (Subtarget->isThumb2()) {
6687     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6688     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6689                    .addFrameIndex(FI)
6690                    .addImm(4)
6691                    .addMemOperand(FIMMOLd));
6692
6693     if (NumLPads < 256) {
6694       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6695                      .addReg(NewVReg1)
6696                      .addImm(LPadList.size()));
6697     } else {
6698       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6699       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6700                      .addImm(NumLPads & 0xFFFF));
6701
6702       unsigned VReg2 = VReg1;
6703       if ((NumLPads & 0xFFFF0000) != 0) {
6704         VReg2 = MRI->createVirtualRegister(TRC);
6705         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6706                        .addReg(VReg1)
6707                        .addImm(NumLPads >> 16));
6708       }
6709
6710       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6711                      .addReg(NewVReg1)
6712                      .addReg(VReg2));
6713     }
6714
6715     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6716       .addMBB(TrapBB)
6717       .addImm(ARMCC::HI)
6718       .addReg(ARM::CPSR);
6719
6720     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6721     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6722                    .addJumpTableIndex(MJTI));
6723
6724     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6725     AddDefaultCC(
6726       AddDefaultPred(
6727         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6728         .addReg(NewVReg3, RegState::Kill)
6729         .addReg(NewVReg1)
6730         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6731
6732     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6733       .addReg(NewVReg4, RegState::Kill)
6734       .addReg(NewVReg1)
6735       .addJumpTableIndex(MJTI);
6736   } else if (Subtarget->isThumb()) {
6737     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6738     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6739                    .addFrameIndex(FI)
6740                    .addImm(1)
6741                    .addMemOperand(FIMMOLd));
6742
6743     if (NumLPads < 256) {
6744       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6745                      .addReg(NewVReg1)
6746                      .addImm(NumLPads));
6747     } else {
6748       MachineConstantPool *ConstantPool = MF->getConstantPool();
6749       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6750       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6751
6752       // MachineConstantPool wants an explicit alignment.
6753       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6754       if (Align == 0)
6755         Align = getDataLayout()->getTypeAllocSize(C->getType());
6756       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6757
6758       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6759       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6760                      .addReg(VReg1, RegState::Define)
6761                      .addConstantPoolIndex(Idx));
6762       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6763                      .addReg(NewVReg1)
6764                      .addReg(VReg1));
6765     }
6766
6767     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6768       .addMBB(TrapBB)
6769       .addImm(ARMCC::HI)
6770       .addReg(ARM::CPSR);
6771
6772     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6773     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6774                    .addReg(ARM::CPSR, RegState::Define)
6775                    .addReg(NewVReg1)
6776                    .addImm(2));
6777
6778     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6779     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6780                    .addJumpTableIndex(MJTI));
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   } else {
6811     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6812     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6813                    .addFrameIndex(FI)
6814                    .addImm(4)
6815                    .addMemOperand(FIMMOLd));
6816
6817     if (NumLPads < 256) {
6818       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6819                      .addReg(NewVReg1)
6820                      .addImm(NumLPads));
6821     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6822       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6823       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6824                      .addImm(NumLPads & 0xFFFF));
6825
6826       unsigned VReg2 = VReg1;
6827       if ((NumLPads & 0xFFFF0000) != 0) {
6828         VReg2 = MRI->createVirtualRegister(TRC);
6829         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6830                        .addReg(VReg1)
6831                        .addImm(NumLPads >> 16));
6832       }
6833
6834       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6835                      .addReg(NewVReg1)
6836                      .addReg(VReg2));
6837     } else {
6838       MachineConstantPool *ConstantPool = MF->getConstantPool();
6839       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6840       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6841
6842       // MachineConstantPool wants an explicit alignment.
6843       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6844       if (Align == 0)
6845         Align = getDataLayout()->getTypeAllocSize(C->getType());
6846       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6847
6848       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6849       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6850                      .addReg(VReg1, RegState::Define)
6851                      .addConstantPoolIndex(Idx)
6852                      .addImm(0));
6853       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6854                      .addReg(NewVReg1)
6855                      .addReg(VReg1, RegState::Kill));
6856     }
6857
6858     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6859       .addMBB(TrapBB)
6860       .addImm(ARMCC::HI)
6861       .addReg(ARM::CPSR);
6862
6863     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6864     AddDefaultCC(
6865       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6866                      .addReg(NewVReg1)
6867                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6868     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6869     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6870                    .addJumpTableIndex(MJTI));
6871
6872     MachineMemOperand *JTMMOLd =
6873       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6874                                MachineMemOperand::MOLoad, 4, 4);
6875     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6876     AddDefaultPred(
6877       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6878       .addReg(NewVReg3, RegState::Kill)
6879       .addReg(NewVReg4)
6880       .addImm(0)
6881       .addMemOperand(JTMMOLd));
6882
6883     if (RelocM == Reloc::PIC_) {
6884       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6885         .addReg(NewVReg5, RegState::Kill)
6886         .addReg(NewVReg4)
6887         .addJumpTableIndex(MJTI);
6888     } else {
6889       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6890         .addReg(NewVReg5, RegState::Kill)
6891         .addJumpTableIndex(MJTI);
6892     }
6893   }
6894
6895   // Add the jump table entries as successors to the MBB.
6896   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6897   for (std::vector<MachineBasicBlock*>::iterator
6898          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6899     MachineBasicBlock *CurMBB = *I;
6900     if (SeenMBBs.insert(CurMBB).second)
6901       DispContBB->addSuccessor(CurMBB);
6902   }
6903
6904   // N.B. the order the invoke BBs are processed in doesn't matter here.
6905   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
6906   SmallVector<MachineBasicBlock*, 64> MBBLPads;
6907   for (MachineBasicBlock *BB : InvokeBBs) {
6908
6909     // Remove the landing pad successor from the invoke block and replace it
6910     // with the new dispatch block.
6911     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6912                                                   BB->succ_end());
6913     while (!Successors.empty()) {
6914       MachineBasicBlock *SMBB = Successors.pop_back_val();
6915       if (SMBB->isLandingPad()) {
6916         BB->removeSuccessor(SMBB);
6917         MBBLPads.push_back(SMBB);
6918       }
6919     }
6920
6921     BB->addSuccessor(DispatchBB);
6922
6923     // Find the invoke call and mark all of the callee-saved registers as
6924     // 'implicit defined' so that they're spilled. This prevents code from
6925     // moving instructions to before the EH block, where they will never be
6926     // executed.
6927     for (MachineBasicBlock::reverse_iterator
6928            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6929       if (!II->isCall()) continue;
6930
6931       DenseMap<unsigned, bool> DefRegs;
6932       for (MachineInstr::mop_iterator
6933              OI = II->operands_begin(), OE = II->operands_end();
6934            OI != OE; ++OI) {
6935         if (!OI->isReg()) continue;
6936         DefRegs[OI->getReg()] = true;
6937       }
6938
6939       MachineInstrBuilder MIB(*MF, &*II);
6940
6941       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6942         unsigned Reg = SavedRegs[i];
6943         if (Subtarget->isThumb2() &&
6944             !ARM::tGPRRegClass.contains(Reg) &&
6945             !ARM::hGPRRegClass.contains(Reg))
6946           continue;
6947         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6948           continue;
6949         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6950           continue;
6951         if (!DefRegs[Reg])
6952           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6953       }
6954
6955       break;
6956     }
6957   }
6958
6959   // Mark all former landing pads as non-landing pads. The dispatch is the only
6960   // landing pad now.
6961   for (SmallVectorImpl<MachineBasicBlock*>::iterator
6962          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6963     (*I)->setIsLandingPad(false);
6964
6965   // The instruction is gone now.
6966   MI->eraseFromParent();
6967 }
6968
6969 static
6970 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6971   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6972        E = MBB->succ_end(); I != E; ++I)
6973     if (*I != Succ)
6974       return *I;
6975   llvm_unreachable("Expecting a BB with two successors!");
6976 }
6977
6978 /// Return the load opcode for a given load size. If load size >= 8,
6979 /// neon opcode will be returned.
6980 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
6981   if (LdSize >= 8)
6982     return LdSize == 16 ? ARM::VLD1q32wb_fixed
6983                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
6984   if (IsThumb1)
6985     return LdSize == 4 ? ARM::tLDRi
6986                        : LdSize == 2 ? ARM::tLDRHi
6987                                      : LdSize == 1 ? ARM::tLDRBi : 0;
6988   if (IsThumb2)
6989     return LdSize == 4 ? ARM::t2LDR_POST
6990                        : LdSize == 2 ? ARM::t2LDRH_POST
6991                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
6992   return LdSize == 4 ? ARM::LDR_POST_IMM
6993                      : LdSize == 2 ? ARM::LDRH_POST
6994                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
6995 }
6996
6997 /// Return the store opcode for a given store size. If store size >= 8,
6998 /// neon opcode will be returned.
6999 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7000   if (StSize >= 8)
7001     return StSize == 16 ? ARM::VST1q32wb_fixed
7002                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7003   if (IsThumb1)
7004     return StSize == 4 ? ARM::tSTRi
7005                        : StSize == 2 ? ARM::tSTRHi
7006                                      : StSize == 1 ? ARM::tSTRBi : 0;
7007   if (IsThumb2)
7008     return StSize == 4 ? ARM::t2STR_POST
7009                        : StSize == 2 ? ARM::t2STRH_POST
7010                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
7011   return StSize == 4 ? ARM::STR_POST_IMM
7012                      : StSize == 2 ? ARM::STRH_POST
7013                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7014 }
7015
7016 /// Emit a post-increment load operation with given size. The instructions
7017 /// will be added to BB at Pos.
7018 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7019                        const TargetInstrInfo *TII, DebugLoc dl,
7020                        unsigned LdSize, unsigned Data, unsigned AddrIn,
7021                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7022   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7023   assert(LdOpc != 0 && "Should have a load opcode");
7024   if (LdSize >= 8) {
7025     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7026                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7027                        .addImm(0));
7028   } else if (IsThumb1) {
7029     // load + update AddrIn
7030     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7031                        .addReg(AddrIn).addImm(0));
7032     MachineInstrBuilder MIB =
7033         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7034     MIB = AddDefaultT1CC(MIB);
7035     MIB.addReg(AddrIn).addImm(LdSize);
7036     AddDefaultPred(MIB);
7037   } else if (IsThumb2) {
7038     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7039                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7040                        .addImm(LdSize));
7041   } else { // arm
7042     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7043                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7044                        .addReg(0).addImm(LdSize));
7045   }
7046 }
7047
7048 /// Emit a post-increment store operation with given size. The instructions
7049 /// will be added to BB at Pos.
7050 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7051                        const TargetInstrInfo *TII, DebugLoc dl,
7052                        unsigned StSize, unsigned Data, unsigned AddrIn,
7053                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7054   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7055   assert(StOpc != 0 && "Should have a store opcode");
7056   if (StSize >= 8) {
7057     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7058                        .addReg(AddrIn).addImm(0).addReg(Data));
7059   } else if (IsThumb1) {
7060     // store + update AddrIn
7061     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7062                        .addReg(AddrIn).addImm(0));
7063     MachineInstrBuilder MIB =
7064         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7065     MIB = AddDefaultT1CC(MIB);
7066     MIB.addReg(AddrIn).addImm(StSize);
7067     AddDefaultPred(MIB);
7068   } else if (IsThumb2) {
7069     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7070                        .addReg(Data).addReg(AddrIn).addImm(StSize));
7071   } else { // arm
7072     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7073                        .addReg(Data).addReg(AddrIn).addReg(0)
7074                        .addImm(StSize));
7075   }
7076 }
7077
7078 MachineBasicBlock *
7079 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7080                                    MachineBasicBlock *BB) const {
7081   // This pseudo instruction has 3 operands: dst, src, size
7082   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7083   // Otherwise, we will generate unrolled scalar copies.
7084   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7085   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7086   MachineFunction::iterator It = BB;
7087   ++It;
7088
7089   unsigned dest = MI->getOperand(0).getReg();
7090   unsigned src = MI->getOperand(1).getReg();
7091   unsigned SizeVal = MI->getOperand(2).getImm();
7092   unsigned Align = MI->getOperand(3).getImm();
7093   DebugLoc dl = MI->getDebugLoc();
7094
7095   MachineFunction *MF = BB->getParent();
7096   MachineRegisterInfo &MRI = MF->getRegInfo();
7097   unsigned UnitSize = 0;
7098   const TargetRegisterClass *TRC = nullptr;
7099   const TargetRegisterClass *VecTRC = nullptr;
7100
7101   bool IsThumb1 = Subtarget->isThumb1Only();
7102   bool IsThumb2 = Subtarget->isThumb2();
7103
7104   if (Align & 1) {
7105     UnitSize = 1;
7106   } else if (Align & 2) {
7107     UnitSize = 2;
7108   } else {
7109     // Check whether we can use NEON instructions.
7110     if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
7111         Subtarget->hasNEON()) {
7112       if ((Align % 16 == 0) && SizeVal >= 16)
7113         UnitSize = 16;
7114       else if ((Align % 8 == 0) && SizeVal >= 8)
7115         UnitSize = 8;
7116     }
7117     // Can't use NEON instructions.
7118     if (UnitSize == 0)
7119       UnitSize = 4;
7120   }
7121
7122   // Select the correct opcode and register class for unit size load/store
7123   bool IsNeon = UnitSize >= 8;
7124   TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
7125   if (IsNeon)
7126     VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
7127                             : UnitSize == 8 ? &ARM::DPRRegClass
7128                                             : nullptr;
7129
7130   unsigned BytesLeft = SizeVal % UnitSize;
7131   unsigned LoopSize = SizeVal - BytesLeft;
7132
7133   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7134     // Use LDR and STR to copy.
7135     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7136     // [destOut] = STR_POST(scratch, destIn, UnitSize)
7137     unsigned srcIn = src;
7138     unsigned destIn = dest;
7139     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7140       unsigned srcOut = MRI.createVirtualRegister(TRC);
7141       unsigned destOut = MRI.createVirtualRegister(TRC);
7142       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7143       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7144                  IsThumb1, IsThumb2);
7145       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7146                  IsThumb1, IsThumb2);
7147       srcIn = srcOut;
7148       destIn = destOut;
7149     }
7150
7151     // Handle the leftover bytes with LDRB and STRB.
7152     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7153     // [destOut] = STRB_POST(scratch, destIn, 1)
7154     for (unsigned i = 0; i < BytesLeft; i++) {
7155       unsigned srcOut = MRI.createVirtualRegister(TRC);
7156       unsigned destOut = MRI.createVirtualRegister(TRC);
7157       unsigned scratch = MRI.createVirtualRegister(TRC);
7158       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7159                  IsThumb1, IsThumb2);
7160       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7161                  IsThumb1, IsThumb2);
7162       srcIn = srcOut;
7163       destIn = destOut;
7164     }
7165     MI->eraseFromParent();   // The instruction is gone now.
7166     return BB;
7167   }
7168
7169   // Expand the pseudo op to a loop.
7170   // thisMBB:
7171   //   ...
7172   //   movw varEnd, # --> with thumb2
7173   //   movt varEnd, #
7174   //   ldrcp varEnd, idx --> without thumb2
7175   //   fallthrough --> loopMBB
7176   // loopMBB:
7177   //   PHI varPhi, varEnd, varLoop
7178   //   PHI srcPhi, src, srcLoop
7179   //   PHI destPhi, dst, destLoop
7180   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7181   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7182   //   subs varLoop, varPhi, #UnitSize
7183   //   bne loopMBB
7184   //   fallthrough --> exitMBB
7185   // exitMBB:
7186   //   epilogue to handle left-over bytes
7187   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7188   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7189   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7190   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7191   MF->insert(It, loopMBB);
7192   MF->insert(It, exitMBB);
7193
7194   // Transfer the remainder of BB and its successor edges to exitMBB.
7195   exitMBB->splice(exitMBB->begin(), BB,
7196                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7197   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7198
7199   // Load an immediate to varEnd.
7200   unsigned varEnd = MRI.createVirtualRegister(TRC);
7201   if (Subtarget->useMovt(*MF)) {
7202     unsigned Vtmp = varEnd;
7203     if ((LoopSize & 0xFFFF0000) != 0)
7204       Vtmp = MRI.createVirtualRegister(TRC);
7205     AddDefaultPred(BuildMI(BB, dl,
7206                            TII->get(IsThumb2 ? ARM::t2MOVi16 : ARM::MOVi16),
7207                            Vtmp).addImm(LoopSize & 0xFFFF));
7208
7209     if ((LoopSize & 0xFFFF0000) != 0)
7210       AddDefaultPred(BuildMI(BB, dl,
7211                              TII->get(IsThumb2 ? ARM::t2MOVTi16 : ARM::MOVTi16),
7212                              varEnd)
7213                          .addReg(Vtmp)
7214                          .addImm(LoopSize >> 16));
7215   } else {
7216     MachineConstantPool *ConstantPool = MF->getConstantPool();
7217     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7218     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7219
7220     // MachineConstantPool wants an explicit alignment.
7221     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7222     if (Align == 0)
7223       Align = getDataLayout()->getTypeAllocSize(C->getType());
7224     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7225
7226     if (IsThumb1)
7227       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7228           varEnd, RegState::Define).addConstantPoolIndex(Idx));
7229     else
7230       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7231           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7232   }
7233   BB->addSuccessor(loopMBB);
7234
7235   // Generate the loop body:
7236   //   varPhi = PHI(varLoop, varEnd)
7237   //   srcPhi = PHI(srcLoop, src)
7238   //   destPhi = PHI(destLoop, dst)
7239   MachineBasicBlock *entryBB = BB;
7240   BB = loopMBB;
7241   unsigned varLoop = MRI.createVirtualRegister(TRC);
7242   unsigned varPhi = MRI.createVirtualRegister(TRC);
7243   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7244   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7245   unsigned destLoop = MRI.createVirtualRegister(TRC);
7246   unsigned destPhi = MRI.createVirtualRegister(TRC);
7247
7248   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7249     .addReg(varLoop).addMBB(loopMBB)
7250     .addReg(varEnd).addMBB(entryBB);
7251   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7252     .addReg(srcLoop).addMBB(loopMBB)
7253     .addReg(src).addMBB(entryBB);
7254   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7255     .addReg(destLoop).addMBB(loopMBB)
7256     .addReg(dest).addMBB(entryBB);
7257
7258   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7259   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7260   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7261   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7262              IsThumb1, IsThumb2);
7263   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7264              IsThumb1, IsThumb2);
7265
7266   // Decrement loop variable by UnitSize.
7267   if (IsThumb1) {
7268     MachineInstrBuilder MIB =
7269         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7270     MIB = AddDefaultT1CC(MIB);
7271     MIB.addReg(varPhi).addImm(UnitSize);
7272     AddDefaultPred(MIB);
7273   } else {
7274     MachineInstrBuilder MIB =
7275         BuildMI(*BB, BB->end(), dl,
7276                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7277     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7278     MIB->getOperand(5).setReg(ARM::CPSR);
7279     MIB->getOperand(5).setIsDef(true);
7280   }
7281   BuildMI(*BB, BB->end(), dl,
7282           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7283       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7284
7285   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7286   BB->addSuccessor(loopMBB);
7287   BB->addSuccessor(exitMBB);
7288
7289   // Add epilogue to handle BytesLeft.
7290   BB = exitMBB;
7291   MachineInstr *StartOfExit = exitMBB->begin();
7292
7293   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7294   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7295   unsigned srcIn = srcLoop;
7296   unsigned destIn = destLoop;
7297   for (unsigned i = 0; i < BytesLeft; i++) {
7298     unsigned srcOut = MRI.createVirtualRegister(TRC);
7299     unsigned destOut = MRI.createVirtualRegister(TRC);
7300     unsigned scratch = MRI.createVirtualRegister(TRC);
7301     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7302                IsThumb1, IsThumb2);
7303     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7304                IsThumb1, IsThumb2);
7305     srcIn = srcOut;
7306     destIn = destOut;
7307   }
7308
7309   MI->eraseFromParent();   // The instruction is gone now.
7310   return BB;
7311 }
7312
7313 MachineBasicBlock *
7314 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7315                                        MachineBasicBlock *MBB) const {
7316   const TargetMachine &TM = getTargetMachine();
7317   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
7318   DebugLoc DL = MI->getDebugLoc();
7319
7320   assert(Subtarget->isTargetWindows() &&
7321          "__chkstk is only supported on Windows");
7322   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7323
7324   // __chkstk takes the number of words to allocate on the stack in R4, and
7325   // returns the stack adjustment in number of bytes in R4.  This will not
7326   // clober any other registers (other than the obvious lr).
7327   //
7328   // Although, technically, IP should be considered a register which may be
7329   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
7330   // thumb-2 environment, so there is no interworking required.  As a result, we
7331   // do not expect a veneer to be emitted by the linker, clobbering IP.
7332   //
7333   // Each module receives its own copy of __chkstk, so no import thunk is
7334   // required, again, ensuring that IP is not clobbered.
7335   //
7336   // Finally, although some linkers may theoretically provide a trampoline for
7337   // out of range calls (which is quite common due to a 32M range limitation of
7338   // branches for Thumb), we can generate the long-call version via
7339   // -mcmodel=large, alleviating the need for the trampoline which may clobber
7340   // IP.
7341
7342   switch (TM.getCodeModel()) {
7343   case CodeModel::Small:
7344   case CodeModel::Medium:
7345   case CodeModel::Default:
7346   case CodeModel::Kernel:
7347     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7348       .addImm((unsigned)ARMCC::AL).addReg(0)
7349       .addExternalSymbol("__chkstk")
7350       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7351       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7352       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7353     break;
7354   case CodeModel::Large:
7355   case CodeModel::JITDefault: {
7356     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7357     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7358
7359     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7360       .addExternalSymbol("__chkstk");
7361     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7362       .addImm((unsigned)ARMCC::AL).addReg(0)
7363       .addReg(Reg, RegState::Kill)
7364       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7365       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7366       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7367     break;
7368   }
7369   }
7370
7371   AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7372                                       ARM::SP)
7373                               .addReg(ARM::SP).addReg(ARM::R4)));
7374
7375   MI->eraseFromParent();
7376   return MBB;
7377 }
7378
7379 MachineBasicBlock *
7380 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7381                                                MachineBasicBlock *BB) const {
7382   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7383   DebugLoc dl = MI->getDebugLoc();
7384   bool isThumb2 = Subtarget->isThumb2();
7385   switch (MI->getOpcode()) {
7386   default: {
7387     MI->dump();
7388     llvm_unreachable("Unexpected instr type to insert");
7389   }
7390   // The Thumb2 pre-indexed stores have the same MI operands, they just
7391   // define them differently in the .td files from the isel patterns, so
7392   // they need pseudos.
7393   case ARM::t2STR_preidx:
7394     MI->setDesc(TII->get(ARM::t2STR_PRE));
7395     return BB;
7396   case ARM::t2STRB_preidx:
7397     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7398     return BB;
7399   case ARM::t2STRH_preidx:
7400     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7401     return BB;
7402
7403   case ARM::STRi_preidx:
7404   case ARM::STRBi_preidx: {
7405     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7406       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7407     // Decode the offset.
7408     unsigned Offset = MI->getOperand(4).getImm();
7409     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7410     Offset = ARM_AM::getAM2Offset(Offset);
7411     if (isSub)
7412       Offset = -Offset;
7413
7414     MachineMemOperand *MMO = *MI->memoperands_begin();
7415     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7416       .addOperand(MI->getOperand(0))  // Rn_wb
7417       .addOperand(MI->getOperand(1))  // Rt
7418       .addOperand(MI->getOperand(2))  // Rn
7419       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7420       .addOperand(MI->getOperand(5))  // pred
7421       .addOperand(MI->getOperand(6))
7422       .addMemOperand(MMO);
7423     MI->eraseFromParent();
7424     return BB;
7425   }
7426   case ARM::STRr_preidx:
7427   case ARM::STRBr_preidx:
7428   case ARM::STRH_preidx: {
7429     unsigned NewOpc;
7430     switch (MI->getOpcode()) {
7431     default: llvm_unreachable("unexpected opcode!");
7432     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7433     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7434     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7435     }
7436     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7437     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7438       MIB.addOperand(MI->getOperand(i));
7439     MI->eraseFromParent();
7440     return BB;
7441   }
7442
7443   case ARM::tMOVCCr_pseudo: {
7444     // To "insert" a SELECT_CC instruction, we actually have to insert the
7445     // diamond control-flow pattern.  The incoming instruction knows the
7446     // destination vreg to set, the condition code register to branch on, the
7447     // true/false values to select between, and a branch opcode to use.
7448     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7449     MachineFunction::iterator It = BB;
7450     ++It;
7451
7452     //  thisMBB:
7453     //  ...
7454     //   TrueVal = ...
7455     //   cmpTY ccX, r1, r2
7456     //   bCC copy1MBB
7457     //   fallthrough --> copy0MBB
7458     MachineBasicBlock *thisMBB  = BB;
7459     MachineFunction *F = BB->getParent();
7460     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7461     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7462     F->insert(It, copy0MBB);
7463     F->insert(It, sinkMBB);
7464
7465     // Transfer the remainder of BB and its successor edges to sinkMBB.
7466     sinkMBB->splice(sinkMBB->begin(), BB,
7467                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7468     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7469
7470     BB->addSuccessor(copy0MBB);
7471     BB->addSuccessor(sinkMBB);
7472
7473     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7474       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7475
7476     //  copy0MBB:
7477     //   %FalseValue = ...
7478     //   # fallthrough to sinkMBB
7479     BB = copy0MBB;
7480
7481     // Update machine-CFG edges
7482     BB->addSuccessor(sinkMBB);
7483
7484     //  sinkMBB:
7485     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7486     //  ...
7487     BB = sinkMBB;
7488     BuildMI(*BB, BB->begin(), dl,
7489             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7490       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7491       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7492
7493     MI->eraseFromParent();   // The pseudo instruction is gone now.
7494     return BB;
7495   }
7496
7497   case ARM::BCCi64:
7498   case ARM::BCCZi64: {
7499     // If there is an unconditional branch to the other successor, remove it.
7500     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7501
7502     // Compare both parts that make up the double comparison separately for
7503     // equality.
7504     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7505
7506     unsigned LHS1 = MI->getOperand(1).getReg();
7507     unsigned LHS2 = MI->getOperand(2).getReg();
7508     if (RHSisZero) {
7509       AddDefaultPred(BuildMI(BB, dl,
7510                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7511                      .addReg(LHS1).addImm(0));
7512       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7513         .addReg(LHS2).addImm(0)
7514         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7515     } else {
7516       unsigned RHS1 = MI->getOperand(3).getReg();
7517       unsigned RHS2 = MI->getOperand(4).getReg();
7518       AddDefaultPred(BuildMI(BB, dl,
7519                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7520                      .addReg(LHS1).addReg(RHS1));
7521       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7522         .addReg(LHS2).addReg(RHS2)
7523         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7524     }
7525
7526     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7527     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7528     if (MI->getOperand(0).getImm() == ARMCC::NE)
7529       std::swap(destMBB, exitMBB);
7530
7531     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7532       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7533     if (isThumb2)
7534       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7535     else
7536       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7537
7538     MI->eraseFromParent();   // The pseudo instruction is gone now.
7539     return BB;
7540   }
7541
7542   case ARM::Int_eh_sjlj_setjmp:
7543   case ARM::Int_eh_sjlj_setjmp_nofp:
7544   case ARM::tInt_eh_sjlj_setjmp:
7545   case ARM::t2Int_eh_sjlj_setjmp:
7546   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7547     EmitSjLjDispatchBlock(MI, BB);
7548     return BB;
7549
7550   case ARM::ABS:
7551   case ARM::t2ABS: {
7552     // To insert an ABS instruction, we have to insert the
7553     // diamond control-flow pattern.  The incoming instruction knows the
7554     // source vreg to test against 0, the destination vreg to set,
7555     // the condition code register to branch on, the
7556     // true/false values to select between, and a branch opcode to use.
7557     // It transforms
7558     //     V1 = ABS V0
7559     // into
7560     //     V2 = MOVS V0
7561     //     BCC                      (branch to SinkBB if V0 >= 0)
7562     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7563     //     SinkBB: V1 = PHI(V2, V3)
7564     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7565     MachineFunction::iterator BBI = BB;
7566     ++BBI;
7567     MachineFunction *Fn = BB->getParent();
7568     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7569     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7570     Fn->insert(BBI, RSBBB);
7571     Fn->insert(BBI, SinkBB);
7572
7573     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7574     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7575     bool ABSSrcKIll = MI->getOperand(1).isKill();
7576     bool isThumb2 = Subtarget->isThumb2();
7577     MachineRegisterInfo &MRI = Fn->getRegInfo();
7578     // In Thumb mode S must not be specified if source register is the SP or
7579     // PC and if destination register is the SP, so restrict register class
7580     unsigned NewRsbDstReg =
7581       MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
7582
7583     // Transfer the remainder of BB and its successor edges to sinkMBB.
7584     SinkBB->splice(SinkBB->begin(), BB,
7585                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
7586     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7587
7588     BB->addSuccessor(RSBBB);
7589     BB->addSuccessor(SinkBB);
7590
7591     // fall through to SinkMBB
7592     RSBBB->addSuccessor(SinkBB);
7593
7594     // insert a cmp at the end of BB
7595     AddDefaultPred(BuildMI(BB, dl,
7596                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7597                    .addReg(ABSSrcReg).addImm(0));
7598
7599     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7600     BuildMI(BB, dl,
7601       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7602       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7603
7604     // insert rsbri in RSBBB
7605     // Note: BCC and rsbri will be converted into predicated rsbmi
7606     // by if-conversion pass
7607     BuildMI(*RSBBB, RSBBB->begin(), dl,
7608       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7609       .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
7610       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7611
7612     // insert PHI in SinkBB,
7613     // reuse ABSDstReg to not change uses of ABS instruction
7614     BuildMI(*SinkBB, SinkBB->begin(), dl,
7615       TII->get(ARM::PHI), ABSDstReg)
7616       .addReg(NewRsbDstReg).addMBB(RSBBB)
7617       .addReg(ABSSrcReg).addMBB(BB);
7618
7619     // remove ABS instruction
7620     MI->eraseFromParent();
7621
7622     // return last added BB
7623     return SinkBB;
7624   }
7625   case ARM::COPY_STRUCT_BYVAL_I32:
7626     ++NumLoopByVals;
7627     return EmitStructByval(MI, BB);
7628   case ARM::WIN__CHKSTK:
7629     return EmitLowered__chkstk(MI, BB);
7630   }
7631 }
7632
7633 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7634                                                       SDNode *Node) const {
7635   const MCInstrDesc *MCID = &MI->getDesc();
7636   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7637   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7638   // operand is still set to noreg. If needed, set the optional operand's
7639   // register to CPSR, and remove the redundant implicit def.
7640   //
7641   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7642
7643   // Rename pseudo opcodes.
7644   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7645   if (NewOpc) {
7646     const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
7647     MCID = &TII->get(NewOpc);
7648
7649     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7650            "converted opcode should be the same except for cc_out");
7651
7652     MI->setDesc(*MCID);
7653
7654     // Add the optional cc_out operand
7655     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7656   }
7657   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7658
7659   // Any ARM instruction that sets the 's' bit should specify an optional
7660   // "cc_out" operand in the last operand position.
7661   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7662     assert(!NewOpc && "Optional cc_out operand required");
7663     return;
7664   }
7665   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7666   // since we already have an optional CPSR def.
7667   bool definesCPSR = false;
7668   bool deadCPSR = false;
7669   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7670        i != e; ++i) {
7671     const MachineOperand &MO = MI->getOperand(i);
7672     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7673       definesCPSR = true;
7674       if (MO.isDead())
7675         deadCPSR = true;
7676       MI->RemoveOperand(i);
7677       break;
7678     }
7679   }
7680   if (!definesCPSR) {
7681     assert(!NewOpc && "Optional cc_out operand required");
7682     return;
7683   }
7684   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7685   if (deadCPSR) {
7686     assert(!MI->getOperand(ccOutIdx).getReg() &&
7687            "expect uninitialized optional cc_out operand");
7688     return;
7689   }
7690
7691   // If this instruction was defined with an optional CPSR def and its dag node
7692   // had a live implicit CPSR def, then activate the optional CPSR def.
7693   MachineOperand &MO = MI->getOperand(ccOutIdx);
7694   MO.setReg(ARM::CPSR);
7695   MO.setIsDef(true);
7696 }
7697
7698 //===----------------------------------------------------------------------===//
7699 //                           ARM Optimization Hooks
7700 //===----------------------------------------------------------------------===//
7701
7702 // Helper function that checks if N is a null or all ones constant.
7703 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7704   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7705   if (!C)
7706     return false;
7707   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7708 }
7709
7710 // Return true if N is conditionally 0 or all ones.
7711 // Detects these expressions where cc is an i1 value:
7712 //
7713 //   (select cc 0, y)   [AllOnes=0]
7714 //   (select cc y, 0)   [AllOnes=0]
7715 //   (zext cc)          [AllOnes=0]
7716 //   (sext cc)          [AllOnes=0/1]
7717 //   (select cc -1, y)  [AllOnes=1]
7718 //   (select cc y, -1)  [AllOnes=1]
7719 //
7720 // Invert is set when N is the null/all ones constant when CC is false.
7721 // OtherOp is set to the alternative value of N.
7722 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7723                                        SDValue &CC, bool &Invert,
7724                                        SDValue &OtherOp,
7725                                        SelectionDAG &DAG) {
7726   switch (N->getOpcode()) {
7727   default: return false;
7728   case ISD::SELECT: {
7729     CC = N->getOperand(0);
7730     SDValue N1 = N->getOperand(1);
7731     SDValue N2 = N->getOperand(2);
7732     if (isZeroOrAllOnes(N1, AllOnes)) {
7733       Invert = false;
7734       OtherOp = N2;
7735       return true;
7736     }
7737     if (isZeroOrAllOnes(N2, AllOnes)) {
7738       Invert = true;
7739       OtherOp = N1;
7740       return true;
7741     }
7742     return false;
7743   }
7744   case ISD::ZERO_EXTEND:
7745     // (zext cc) can never be the all ones value.
7746     if (AllOnes)
7747       return false;
7748     // Fall through.
7749   case ISD::SIGN_EXTEND: {
7750     SDLoc dl(N);
7751     EVT VT = N->getValueType(0);
7752     CC = N->getOperand(0);
7753     if (CC.getValueType() != MVT::i1)
7754       return false;
7755     Invert = !AllOnes;
7756     if (AllOnes)
7757       // When looking for an AllOnes constant, N is an sext, and the 'other'
7758       // value is 0.
7759       OtherOp = DAG.getConstant(0, dl, VT);
7760     else if (N->getOpcode() == ISD::ZERO_EXTEND)
7761       // When looking for a 0 constant, N can be zext or sext.
7762       OtherOp = DAG.getConstant(1, dl, VT);
7763     else
7764       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
7765                                 VT);
7766     return true;
7767   }
7768   }
7769 }
7770
7771 // Combine a constant select operand into its use:
7772 //
7773 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
7774 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
7775 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
7776 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
7777 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
7778 //
7779 // The transform is rejected if the select doesn't have a constant operand that
7780 // is null, or all ones when AllOnes is set.
7781 //
7782 // Also recognize sext/zext from i1:
7783 //
7784 //   (add (zext cc), x) -> (select cc (add x, 1), x)
7785 //   (add (sext cc), x) -> (select cc (add x, -1), x)
7786 //
7787 // These transformations eventually create predicated instructions.
7788 //
7789 // @param N       The node to transform.
7790 // @param Slct    The N operand that is a select.
7791 // @param OtherOp The other N operand (x above).
7792 // @param DCI     Context.
7793 // @param AllOnes Require the select constant to be all ones instead of null.
7794 // @returns The new node, or SDValue() on failure.
7795 static
7796 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7797                             TargetLowering::DAGCombinerInfo &DCI,
7798                             bool AllOnes = false) {
7799   SelectionDAG &DAG = DCI.DAG;
7800   EVT VT = N->getValueType(0);
7801   SDValue NonConstantVal;
7802   SDValue CCOp;
7803   bool SwapSelectOps;
7804   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7805                                   NonConstantVal, DAG))
7806     return SDValue();
7807
7808   // Slct is now know to be the desired identity constant when CC is true.
7809   SDValue TrueVal = OtherOp;
7810   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7811                                  OtherOp, NonConstantVal);
7812   // Unless SwapSelectOps says CC should be false.
7813   if (SwapSelectOps)
7814     std::swap(TrueVal, FalseVal);
7815
7816   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7817                      CCOp, TrueVal, FalseVal);
7818 }
7819
7820 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7821 static
7822 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7823                                        TargetLowering::DAGCombinerInfo &DCI) {
7824   SDValue N0 = N->getOperand(0);
7825   SDValue N1 = N->getOperand(1);
7826   if (N0.getNode()->hasOneUse()) {
7827     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7828     if (Result.getNode())
7829       return Result;
7830   }
7831   if (N1.getNode()->hasOneUse()) {
7832     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7833     if (Result.getNode())
7834       return Result;
7835   }
7836   return SDValue();
7837 }
7838
7839 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7840 // (only after legalization).
7841 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7842                                  TargetLowering::DAGCombinerInfo &DCI,
7843                                  const ARMSubtarget *Subtarget) {
7844
7845   // Only perform optimization if after legalize, and if NEON is available. We
7846   // also expected both operands to be BUILD_VECTORs.
7847   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7848       || N0.getOpcode() != ISD::BUILD_VECTOR
7849       || N1.getOpcode() != ISD::BUILD_VECTOR)
7850     return SDValue();
7851
7852   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7853   EVT VT = N->getValueType(0);
7854   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7855     return SDValue();
7856
7857   // Check that the vector operands are of the right form.
7858   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7859   // operands, where N is the size of the formed vector.
7860   // Each EXTRACT_VECTOR should have the same input vector and odd or even
7861   // index such that we have a pair wise add pattern.
7862
7863   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7864   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7865     return SDValue();
7866   SDValue Vec = N0->getOperand(0)->getOperand(0);
7867   SDNode *V = Vec.getNode();
7868   unsigned nextIndex = 0;
7869
7870   // For each operands to the ADD which are BUILD_VECTORs,
7871   // check to see if each of their operands are an EXTRACT_VECTOR with
7872   // the same vector and appropriate index.
7873   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7874     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7875         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7876
7877       SDValue ExtVec0 = N0->getOperand(i);
7878       SDValue ExtVec1 = N1->getOperand(i);
7879
7880       // First operand is the vector, verify its the same.
7881       if (V != ExtVec0->getOperand(0).getNode() ||
7882           V != ExtVec1->getOperand(0).getNode())
7883         return SDValue();
7884
7885       // Second is the constant, verify its correct.
7886       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7887       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7888
7889       // For the constant, we want to see all the even or all the odd.
7890       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7891           || C1->getZExtValue() != nextIndex+1)
7892         return SDValue();
7893
7894       // Increment index.
7895       nextIndex+=2;
7896     } else
7897       return SDValue();
7898   }
7899
7900   // Create VPADDL node.
7901   SelectionDAG &DAG = DCI.DAG;
7902   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7903
7904   SDLoc dl(N);
7905
7906   // Build operand list.
7907   SmallVector<SDValue, 8> Ops;
7908   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
7909                                 TLI.getPointerTy()));
7910
7911   // Input is the vector.
7912   Ops.push_back(Vec);
7913
7914   // Get widened type and narrowed type.
7915   MVT widenType;
7916   unsigned numElem = VT.getVectorNumElements();
7917   
7918   EVT inputLaneType = Vec.getValueType().getVectorElementType();
7919   switch (inputLaneType.getSimpleVT().SimpleTy) {
7920     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7921     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7922     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7923     default:
7924       llvm_unreachable("Invalid vector element type for padd optimization.");
7925   }
7926
7927   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
7928   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
7929   return DAG.getNode(ExtOp, dl, VT, tmp);
7930 }
7931
7932 static SDValue findMUL_LOHI(SDValue V) {
7933   if (V->getOpcode() == ISD::UMUL_LOHI ||
7934       V->getOpcode() == ISD::SMUL_LOHI)
7935     return V;
7936   return SDValue();
7937 }
7938
7939 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7940                                      TargetLowering::DAGCombinerInfo &DCI,
7941                                      const ARMSubtarget *Subtarget) {
7942
7943   if (Subtarget->isThumb1Only()) return SDValue();
7944
7945   // Only perform the checks after legalize when the pattern is available.
7946   if (DCI.isBeforeLegalize()) return SDValue();
7947
7948   // Look for multiply add opportunities.
7949   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7950   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7951   // a glue link from the first add to the second add.
7952   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7953   // a S/UMLAL instruction.
7954   //          loAdd   UMUL_LOHI
7955   //            \    / :lo    \ :hi
7956   //             \  /          \          [no multiline comment]
7957   //              ADDC         |  hiAdd
7958   //                 \ :glue  /  /
7959   //                  \      /  /
7960   //                    ADDE
7961   //
7962   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7963   SDValue AddcOp0 = AddcNode->getOperand(0);
7964   SDValue AddcOp1 = AddcNode->getOperand(1);
7965
7966   // Check if the two operands are from the same mul_lohi node.
7967   if (AddcOp0.getNode() == AddcOp1.getNode())
7968     return SDValue();
7969
7970   assert(AddcNode->getNumValues() == 2 &&
7971          AddcNode->getValueType(0) == MVT::i32 &&
7972          "Expect ADDC with two result values. First: i32");
7973
7974   // Check that we have a glued ADDC node.
7975   if (AddcNode->getValueType(1) != MVT::Glue)
7976     return SDValue();
7977
7978   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7979   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7980       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7981       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7982       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7983     return SDValue();
7984
7985   // Look for the glued ADDE.
7986   SDNode* AddeNode = AddcNode->getGluedUser();
7987   if (!AddeNode)
7988     return SDValue();
7989
7990   // Make sure it is really an ADDE.
7991   if (AddeNode->getOpcode() != ISD::ADDE)
7992     return SDValue();
7993
7994   assert(AddeNode->getNumOperands() == 3 &&
7995          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
7996          "ADDE node has the wrong inputs");
7997
7998   // Check for the triangle shape.
7999   SDValue AddeOp0 = AddeNode->getOperand(0);
8000   SDValue AddeOp1 = AddeNode->getOperand(1);
8001
8002   // Make sure that the ADDE operands are not coming from the same node.
8003   if (AddeOp0.getNode() == AddeOp1.getNode())
8004     return SDValue();
8005
8006   // Find the MUL_LOHI node walking up ADDE's operands.
8007   bool IsLeftOperandMUL = false;
8008   SDValue MULOp = findMUL_LOHI(AddeOp0);
8009   if (MULOp == SDValue())
8010    MULOp = findMUL_LOHI(AddeOp1);
8011   else
8012     IsLeftOperandMUL = true;
8013   if (MULOp == SDValue())
8014     return SDValue();
8015
8016   // Figure out the right opcode.
8017   unsigned Opc = MULOp->getOpcode();
8018   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8019
8020   // Figure out the high and low input values to the MLAL node.
8021   SDValue* HiAdd = nullptr;
8022   SDValue* LoMul = nullptr;
8023   SDValue* LowAdd = nullptr;
8024
8025   // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
8026   if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
8027     return SDValue();
8028
8029   if (IsLeftOperandMUL)
8030     HiAdd = &AddeOp1;
8031   else
8032     HiAdd = &AddeOp0;
8033
8034
8035   // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
8036   // whose low result is fed to the ADDC we are checking.
8037
8038   if (AddcOp0 == MULOp.getValue(0)) {
8039     LoMul = &AddcOp0;
8040     LowAdd = &AddcOp1;
8041   }
8042   if (AddcOp1 == MULOp.getValue(0)) {
8043     LoMul = &AddcOp1;
8044     LowAdd = &AddcOp0;
8045   }
8046
8047   if (!LoMul)
8048     return SDValue();
8049
8050   // Create the merged node.
8051   SelectionDAG &DAG = DCI.DAG;
8052
8053   // Build operand list.
8054   SmallVector<SDValue, 8> Ops;
8055   Ops.push_back(LoMul->getOperand(0));
8056   Ops.push_back(LoMul->getOperand(1));
8057   Ops.push_back(*LowAdd);
8058   Ops.push_back(*HiAdd);
8059
8060   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
8061                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
8062
8063   // Replace the ADDs' nodes uses by the MLA node's values.
8064   SDValue HiMLALResult(MLALNode.getNode(), 1);
8065   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8066
8067   SDValue LoMLALResult(MLALNode.getNode(), 0);
8068   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8069
8070   // Return original node to notify the driver to stop replacing.
8071   SDValue resNode(AddcNode, 0);
8072   return resNode;
8073 }
8074
8075 /// PerformADDCCombine - Target-specific dag combine transform from
8076 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8077 static SDValue PerformADDCCombine(SDNode *N,
8078                                  TargetLowering::DAGCombinerInfo &DCI,
8079                                  const ARMSubtarget *Subtarget) {
8080
8081   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8082
8083 }
8084
8085 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8086 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
8087 /// called with the default operands, and if that fails, with commuted
8088 /// operands.
8089 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8090                                           TargetLowering::DAGCombinerInfo &DCI,
8091                                           const ARMSubtarget *Subtarget){
8092
8093   // Attempt to create vpaddl for this add.
8094   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8095   if (Result.getNode())
8096     return Result;
8097
8098   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8099   if (N0.getNode()->hasOneUse()) {
8100     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8101     if (Result.getNode()) return Result;
8102   }
8103   return SDValue();
8104 }
8105
8106 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8107 ///
8108 static SDValue PerformADDCombine(SDNode *N,
8109                                  TargetLowering::DAGCombinerInfo &DCI,
8110                                  const ARMSubtarget *Subtarget) {
8111   SDValue N0 = N->getOperand(0);
8112   SDValue N1 = N->getOperand(1);
8113
8114   // First try with the default operand order.
8115   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8116   if (Result.getNode())
8117     return Result;
8118
8119   // If that didn't work, try again with the operands commuted.
8120   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8121 }
8122
8123 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8124 ///
8125 static SDValue PerformSUBCombine(SDNode *N,
8126                                  TargetLowering::DAGCombinerInfo &DCI) {
8127   SDValue N0 = N->getOperand(0);
8128   SDValue N1 = N->getOperand(1);
8129
8130   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8131   if (N1.getNode()->hasOneUse()) {
8132     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8133     if (Result.getNode()) return Result;
8134   }
8135
8136   return SDValue();
8137 }
8138
8139 /// PerformVMULCombine
8140 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8141 /// special multiplier accumulator forwarding.
8142 ///   vmul d3, d0, d2
8143 ///   vmla d3, d1, d2
8144 /// is faster than
8145 ///   vadd d3, d0, d1
8146 ///   vmul d3, d3, d2
8147 //  However, for (A + B) * (A + B),
8148 //    vadd d2, d0, d1
8149 //    vmul d3, d0, d2
8150 //    vmla d3, d1, d2
8151 //  is slower than
8152 //    vadd d2, d0, d1
8153 //    vmul d3, d2, d2
8154 static SDValue PerformVMULCombine(SDNode *N,
8155                                   TargetLowering::DAGCombinerInfo &DCI,
8156                                   const ARMSubtarget *Subtarget) {
8157   if (!Subtarget->hasVMLxForwarding())
8158     return SDValue();
8159
8160   SelectionDAG &DAG = DCI.DAG;
8161   SDValue N0 = N->getOperand(0);
8162   SDValue N1 = N->getOperand(1);
8163   unsigned Opcode = N0.getOpcode();
8164   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8165       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8166     Opcode = N1.getOpcode();
8167     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8168         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8169       return SDValue();
8170     std::swap(N0, N1);
8171   }
8172
8173   if (N0 == N1)
8174     return SDValue();
8175
8176   EVT VT = N->getValueType(0);
8177   SDLoc DL(N);
8178   SDValue N00 = N0->getOperand(0);
8179   SDValue N01 = N0->getOperand(1);
8180   return DAG.getNode(Opcode, DL, VT,
8181                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8182                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8183 }
8184
8185 static SDValue PerformMULCombine(SDNode *N,
8186                                  TargetLowering::DAGCombinerInfo &DCI,
8187                                  const ARMSubtarget *Subtarget) {
8188   SelectionDAG &DAG = DCI.DAG;
8189
8190   if (Subtarget->isThumb1Only())
8191     return SDValue();
8192
8193   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8194     return SDValue();
8195
8196   EVT VT = N->getValueType(0);
8197   if (VT.is64BitVector() || VT.is128BitVector())
8198     return PerformVMULCombine(N, DCI, Subtarget);
8199   if (VT != MVT::i32)
8200     return SDValue();
8201
8202   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8203   if (!C)
8204     return SDValue();
8205
8206   int64_t MulAmt = C->getSExtValue();
8207   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8208
8209   ShiftAmt = ShiftAmt & (32 - 1);
8210   SDValue V = N->getOperand(0);
8211   SDLoc DL(N);
8212
8213   SDValue Res;
8214   MulAmt >>= ShiftAmt;
8215
8216   if (MulAmt >= 0) {
8217     if (isPowerOf2_32(MulAmt - 1)) {
8218       // (mul x, 2^N + 1) => (add (shl x, N), x)
8219       Res = DAG.getNode(ISD::ADD, DL, VT,
8220                         V,
8221                         DAG.getNode(ISD::SHL, DL, VT,
8222                                     V,
8223                                     DAG.getConstant(Log2_32(MulAmt - 1), DL,
8224                                                     MVT::i32)));
8225     } else if (isPowerOf2_32(MulAmt + 1)) {
8226       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8227       Res = DAG.getNode(ISD::SUB, DL, VT,
8228                         DAG.getNode(ISD::SHL, DL, VT,
8229                                     V,
8230                                     DAG.getConstant(Log2_32(MulAmt + 1), DL,
8231                                                     MVT::i32)),
8232                         V);
8233     } else
8234       return SDValue();
8235   } else {
8236     uint64_t MulAmtAbs = -MulAmt;
8237     if (isPowerOf2_32(MulAmtAbs + 1)) {
8238       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8239       Res = DAG.getNode(ISD::SUB, DL, VT,
8240                         V,
8241                         DAG.getNode(ISD::SHL, DL, VT,
8242                                     V,
8243                                     DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
8244                                                     MVT::i32)));
8245     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8246       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8247       Res = DAG.getNode(ISD::ADD, DL, VT,
8248                         V,
8249                         DAG.getNode(ISD::SHL, DL, VT,
8250                                     V,
8251                                     DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
8252                                                     MVT::i32)));
8253       Res = DAG.getNode(ISD::SUB, DL, VT,
8254                         DAG.getConstant(0, DL, MVT::i32), Res);
8255
8256     } else
8257       return SDValue();
8258   }
8259
8260   if (ShiftAmt != 0)
8261     Res = DAG.getNode(ISD::SHL, DL, VT,
8262                       Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
8263
8264   // Do not add new nodes to DAG combiner worklist.
8265   DCI.CombineTo(N, Res, false);
8266   return SDValue();
8267 }
8268
8269 static SDValue PerformANDCombine(SDNode *N,
8270                                  TargetLowering::DAGCombinerInfo &DCI,
8271                                  const ARMSubtarget *Subtarget) {
8272
8273   // Attempt to use immediate-form VBIC
8274   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8275   SDLoc dl(N);
8276   EVT VT = N->getValueType(0);
8277   SelectionDAG &DAG = DCI.DAG;
8278
8279   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8280     return SDValue();
8281
8282   APInt SplatBits, SplatUndef;
8283   unsigned SplatBitSize;
8284   bool HasAnyUndefs;
8285   if (BVN &&
8286       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8287     if (SplatBitSize <= 64) {
8288       EVT VbicVT;
8289       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8290                                       SplatUndef.getZExtValue(), SplatBitSize,
8291                                       DAG, dl, VbicVT, VT.is128BitVector(),
8292                                       OtherModImm);
8293       if (Val.getNode()) {
8294         SDValue Input =
8295           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8296         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8297         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8298       }
8299     }
8300   }
8301
8302   if (!Subtarget->isThumb1Only()) {
8303     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8304     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8305     if (Result.getNode())
8306       return Result;
8307   }
8308
8309   return SDValue();
8310 }
8311
8312 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8313 static SDValue PerformORCombine(SDNode *N,
8314                                 TargetLowering::DAGCombinerInfo &DCI,
8315                                 const ARMSubtarget *Subtarget) {
8316   // Attempt to use immediate-form VORR
8317   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8318   SDLoc dl(N);
8319   EVT VT = N->getValueType(0);
8320   SelectionDAG &DAG = DCI.DAG;
8321
8322   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8323     return SDValue();
8324
8325   APInt SplatBits, SplatUndef;
8326   unsigned SplatBitSize;
8327   bool HasAnyUndefs;
8328   if (BVN && Subtarget->hasNEON() &&
8329       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8330     if (SplatBitSize <= 64) {
8331       EVT VorrVT;
8332       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8333                                       SplatUndef.getZExtValue(), SplatBitSize,
8334                                       DAG, dl, VorrVT, VT.is128BitVector(),
8335                                       OtherModImm);
8336       if (Val.getNode()) {
8337         SDValue Input =
8338           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8339         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8340         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8341       }
8342     }
8343   }
8344
8345   if (!Subtarget->isThumb1Only()) {
8346     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8347     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8348     if (Result.getNode())
8349       return Result;
8350   }
8351
8352   // The code below optimizes (or (and X, Y), Z).
8353   // The AND operand needs to have a single user to make these optimizations
8354   // profitable.
8355   SDValue N0 = N->getOperand(0);
8356   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8357     return SDValue();
8358   SDValue N1 = N->getOperand(1);
8359
8360   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8361   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8362       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8363     APInt SplatUndef;
8364     unsigned SplatBitSize;
8365     bool HasAnyUndefs;
8366
8367     APInt SplatBits0, SplatBits1;
8368     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8369     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8370     // Ensure that the second operand of both ands are constants
8371     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8372                                       HasAnyUndefs) && !HasAnyUndefs) {
8373         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8374                                           HasAnyUndefs) && !HasAnyUndefs) {
8375             // Ensure that the bit width of the constants are the same and that
8376             // the splat arguments are logical inverses as per the pattern we
8377             // are trying to simplify.
8378             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8379                 SplatBits0 == ~SplatBits1) {
8380                 // Canonicalize the vector type to make instruction selection
8381                 // simpler.
8382                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8383                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8384                                              N0->getOperand(1),
8385                                              N0->getOperand(0),
8386                                              N1->getOperand(0));
8387                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8388             }
8389         }
8390     }
8391   }
8392
8393   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8394   // reasonable.
8395
8396   // BFI is only available on V6T2+
8397   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8398     return SDValue();
8399
8400   SDLoc DL(N);
8401   // 1) or (and A, mask), val => ARMbfi A, val, mask
8402   //      iff (val & mask) == val
8403   //
8404   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8405   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8406   //          && mask == ~mask2
8407   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8408   //          && ~mask == mask2
8409   //  (i.e., copy a bitfield value into another bitfield of the same width)
8410
8411   if (VT != MVT::i32)
8412     return SDValue();
8413
8414   SDValue N00 = N0.getOperand(0);
8415
8416   // The value and the mask need to be constants so we can verify this is
8417   // actually a bitfield set. If the mask is 0xffff, we can do better
8418   // via a movt instruction, so don't use BFI in that case.
8419   SDValue MaskOp = N0.getOperand(1);
8420   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8421   if (!MaskC)
8422     return SDValue();
8423   unsigned Mask = MaskC->getZExtValue();
8424   if (Mask == 0xffff)
8425     return SDValue();
8426   SDValue Res;
8427   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8428   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8429   if (N1C) {
8430     unsigned Val = N1C->getZExtValue();
8431     if ((Val & ~Mask) != Val)
8432       return SDValue();
8433
8434     if (ARM::isBitFieldInvertedMask(Mask)) {
8435       Val >>= countTrailingZeros(~Mask);
8436
8437       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8438                         DAG.getConstant(Val, DL, MVT::i32),
8439                         DAG.getConstant(Mask, DL, MVT::i32));
8440
8441       // Do not add new nodes to DAG combiner worklist.
8442       DCI.CombineTo(N, Res, false);
8443       return SDValue();
8444     }
8445   } else if (N1.getOpcode() == ISD::AND) {
8446     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8447     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8448     if (!N11C)
8449       return SDValue();
8450     unsigned Mask2 = N11C->getZExtValue();
8451
8452     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8453     // as is to match.
8454     if (ARM::isBitFieldInvertedMask(Mask) &&
8455         (Mask == ~Mask2)) {
8456       // The pack halfword instruction works better for masks that fit it,
8457       // so use that when it's available.
8458       if (Subtarget->hasT2ExtractPack() &&
8459           (Mask == 0xffff || Mask == 0xffff0000))
8460         return SDValue();
8461       // 2a
8462       unsigned amt = countTrailingZeros(Mask2);
8463       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8464                         DAG.getConstant(amt, DL, MVT::i32));
8465       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8466                         DAG.getConstant(Mask, DL, MVT::i32));
8467       // Do not add new nodes to DAG combiner worklist.
8468       DCI.CombineTo(N, Res, false);
8469       return SDValue();
8470     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8471                (~Mask == Mask2)) {
8472       // The pack halfword instruction works better for masks that fit it,
8473       // so use that when it's available.
8474       if (Subtarget->hasT2ExtractPack() &&
8475           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8476         return SDValue();
8477       // 2b
8478       unsigned lsb = countTrailingZeros(Mask);
8479       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8480                         DAG.getConstant(lsb, DL, MVT::i32));
8481       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8482                         DAG.getConstant(Mask2, DL, MVT::i32));
8483       // Do not add new nodes to DAG combiner worklist.
8484       DCI.CombineTo(N, Res, false);
8485       return SDValue();
8486     }
8487   }
8488
8489   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8490       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8491       ARM::isBitFieldInvertedMask(~Mask)) {
8492     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8493     // where lsb(mask) == #shamt and masked bits of B are known zero.
8494     SDValue ShAmt = N00.getOperand(1);
8495     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8496     unsigned LSB = countTrailingZeros(Mask);
8497     if (ShAmtC != LSB)
8498       return SDValue();
8499
8500     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8501                       DAG.getConstant(~Mask, DL, MVT::i32));
8502
8503     // Do not add new nodes to DAG combiner worklist.
8504     DCI.CombineTo(N, Res, false);
8505   }
8506
8507   return SDValue();
8508 }
8509
8510 static SDValue PerformXORCombine(SDNode *N,
8511                                  TargetLowering::DAGCombinerInfo &DCI,
8512                                  const ARMSubtarget *Subtarget) {
8513   EVT VT = N->getValueType(0);
8514   SelectionDAG &DAG = DCI.DAG;
8515
8516   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8517     return SDValue();
8518
8519   if (!Subtarget->isThumb1Only()) {
8520     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8521     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8522     if (Result.getNode())
8523       return Result;
8524   }
8525
8526   return SDValue();
8527 }
8528
8529 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8530 /// the bits being cleared by the AND are not demanded by the BFI.
8531 static SDValue PerformBFICombine(SDNode *N,
8532                                  TargetLowering::DAGCombinerInfo &DCI) {
8533   SDValue N1 = N->getOperand(1);
8534   if (N1.getOpcode() == ISD::AND) {
8535     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8536     if (!N11C)
8537       return SDValue();
8538     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8539     unsigned LSB = countTrailingZeros(~InvMask);
8540     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8541     assert(Width <
8542                static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
8543            "undefined behavior");
8544     unsigned Mask = (1u << Width) - 1;
8545     unsigned Mask2 = N11C->getZExtValue();
8546     if ((Mask & (~Mask2)) == 0)
8547       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8548                              N->getOperand(0), N1.getOperand(0),
8549                              N->getOperand(2));
8550   }
8551   return SDValue();
8552 }
8553
8554 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8555 /// ARMISD::VMOVRRD.
8556 static SDValue PerformVMOVRRDCombine(SDNode *N,
8557                                      TargetLowering::DAGCombinerInfo &DCI,
8558                                      const ARMSubtarget *Subtarget) {
8559   // vmovrrd(vmovdrr x, y) -> x,y
8560   SDValue InDouble = N->getOperand(0);
8561   if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
8562     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8563
8564   // vmovrrd(load f64) -> (load i32), (load i32)
8565   SDNode *InNode = InDouble.getNode();
8566   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8567       InNode->getValueType(0) == MVT::f64 &&
8568       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8569       !cast<LoadSDNode>(InNode)->isVolatile()) {
8570     // TODO: Should this be done for non-FrameIndex operands?
8571     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8572
8573     SelectionDAG &DAG = DCI.DAG;
8574     SDLoc DL(LD);
8575     SDValue BasePtr = LD->getBasePtr();
8576     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8577                                  LD->getPointerInfo(), LD->isVolatile(),
8578                                  LD->isNonTemporal(), LD->isInvariant(),
8579                                  LD->getAlignment());
8580
8581     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8582                                     DAG.getConstant(4, DL, MVT::i32));
8583     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8584                                  LD->getPointerInfo(), LD->isVolatile(),
8585                                  LD->isNonTemporal(), LD->isInvariant(),
8586                                  std::min(4U, LD->getAlignment() / 2));
8587
8588     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8589     if (DCI.DAG.getTargetLoweringInfo().isBigEndian())
8590       std::swap (NewLD1, NewLD2);
8591     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8592     return Result;
8593   }
8594
8595   return SDValue();
8596 }
8597
8598 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8599 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8600 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8601   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8602   SDValue Op0 = N->getOperand(0);
8603   SDValue Op1 = N->getOperand(1);
8604   if (Op0.getOpcode() == ISD::BITCAST)
8605     Op0 = Op0.getOperand(0);
8606   if (Op1.getOpcode() == ISD::BITCAST)
8607     Op1 = Op1.getOperand(0);
8608   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8609       Op0.getNode() == Op1.getNode() &&
8610       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8611     return DAG.getNode(ISD::BITCAST, SDLoc(N),
8612                        N->getValueType(0), Op0.getOperand(0));
8613   return SDValue();
8614 }
8615
8616 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8617 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8618 /// i64 vector to have f64 elements, since the value can then be loaded
8619 /// directly into a VFP register.
8620 static bool hasNormalLoadOperand(SDNode *N) {
8621   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8622   for (unsigned i = 0; i < NumElts; ++i) {
8623     SDNode *Elt = N->getOperand(i).getNode();
8624     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8625       return true;
8626   }
8627   return false;
8628 }
8629
8630 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8631 /// ISD::BUILD_VECTOR.
8632 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8633                                           TargetLowering::DAGCombinerInfo &DCI,
8634                                           const ARMSubtarget *Subtarget) {
8635   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8636   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
8637   // into a pair of GPRs, which is fine when the value is used as a scalar,
8638   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8639   SelectionDAG &DAG = DCI.DAG;
8640   if (N->getNumOperands() == 2) {
8641     SDValue RV = PerformVMOVDRRCombine(N, DAG);
8642     if (RV.getNode())
8643       return RV;
8644   }
8645
8646   // Load i64 elements as f64 values so that type legalization does not split
8647   // them up into i32 values.
8648   EVT VT = N->getValueType(0);
8649   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8650     return SDValue();
8651   SDLoc dl(N);
8652   SmallVector<SDValue, 8> Ops;
8653   unsigned NumElts = VT.getVectorNumElements();
8654   for (unsigned i = 0; i < NumElts; ++i) {
8655     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8656     Ops.push_back(V);
8657     // Make the DAGCombiner fold the bitcast.
8658     DCI.AddToWorklist(V.getNode());
8659   }
8660   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8661   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8662   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8663 }
8664
8665 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8666 static SDValue
8667 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8668   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8669   // At that time, we may have inserted bitcasts from integer to float.
8670   // If these bitcasts have survived DAGCombine, change the lowering of this
8671   // BUILD_VECTOR in something more vector friendly, i.e., that does not
8672   // force to use floating point types.
8673
8674   // Make sure we can change the type of the vector.
8675   // This is possible iff:
8676   // 1. The vector is only used in a bitcast to a integer type. I.e.,
8677   //    1.1. Vector is used only once.
8678   //    1.2. Use is a bit convert to an integer type.
8679   // 2. The size of its operands are 32-bits (64-bits are not legal).
8680   EVT VT = N->getValueType(0);
8681   EVT EltVT = VT.getVectorElementType();
8682
8683   // Check 1.1. and 2.
8684   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8685     return SDValue();
8686
8687   // By construction, the input type must be float.
8688   assert(EltVT == MVT::f32 && "Unexpected type!");
8689
8690   // Check 1.2.
8691   SDNode *Use = *N->use_begin();
8692   if (Use->getOpcode() != ISD::BITCAST ||
8693       Use->getValueType(0).isFloatingPoint())
8694     return SDValue();
8695
8696   // Check profitability.
8697   // Model is, if more than half of the relevant operands are bitcast from
8698   // i32, turn the build_vector into a sequence of insert_vector_elt.
8699   // Relevant operands are everything that is not statically
8700   // (i.e., at compile time) bitcasted.
8701   unsigned NumOfBitCastedElts = 0;
8702   unsigned NumElts = VT.getVectorNumElements();
8703   unsigned NumOfRelevantElts = NumElts;
8704   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8705     SDValue Elt = N->getOperand(Idx);
8706     if (Elt->getOpcode() == ISD::BITCAST) {
8707       // Assume only bit cast to i32 will go away.
8708       if (Elt->getOperand(0).getValueType() == MVT::i32)
8709         ++NumOfBitCastedElts;
8710     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8711       // Constants are statically casted, thus do not count them as
8712       // relevant operands.
8713       --NumOfRelevantElts;
8714   }
8715
8716   // Check if more than half of the elements require a non-free bitcast.
8717   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8718     return SDValue();
8719
8720   SelectionDAG &DAG = DCI.DAG;
8721   // Create the new vector type.
8722   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8723   // Check if the type is legal.
8724   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8725   if (!TLI.isTypeLegal(VecVT))
8726     return SDValue();
8727
8728   // Combine:
8729   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8730   // => BITCAST INSERT_VECTOR_ELT
8731   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8732   //                      (BITCAST EN), N.
8733   SDValue Vec = DAG.getUNDEF(VecVT);
8734   SDLoc dl(N);
8735   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8736     SDValue V = N->getOperand(Idx);
8737     if (V.getOpcode() == ISD::UNDEF)
8738       continue;
8739     if (V.getOpcode() == ISD::BITCAST &&
8740         V->getOperand(0).getValueType() == MVT::i32)
8741       // Fold obvious case.
8742       V = V.getOperand(0);
8743     else {
8744       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
8745       // Make the DAGCombiner fold the bitcasts.
8746       DCI.AddToWorklist(V.getNode());
8747     }
8748     SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
8749     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8750   }
8751   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8752   // Make the DAGCombiner fold the bitcasts.
8753   DCI.AddToWorklist(Vec.getNode());
8754   return Vec;
8755 }
8756
8757 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8758 /// ISD::INSERT_VECTOR_ELT.
8759 static SDValue PerformInsertEltCombine(SDNode *N,
8760                                        TargetLowering::DAGCombinerInfo &DCI) {
8761   // Bitcast an i64 load inserted into a vector to f64.
8762   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8763   EVT VT = N->getValueType(0);
8764   SDNode *Elt = N->getOperand(1).getNode();
8765   if (VT.getVectorElementType() != MVT::i64 ||
8766       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8767     return SDValue();
8768
8769   SelectionDAG &DAG = DCI.DAG;
8770   SDLoc dl(N);
8771   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8772                                  VT.getVectorNumElements());
8773   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8774   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8775   // Make the DAGCombiner fold the bitcasts.
8776   DCI.AddToWorklist(Vec.getNode());
8777   DCI.AddToWorklist(V.getNode());
8778   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8779                                Vec, V, N->getOperand(2));
8780   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8781 }
8782
8783 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8784 /// ISD::VECTOR_SHUFFLE.
8785 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8786   // The LLVM shufflevector instruction does not require the shuffle mask
8787   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8788   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
8789   // operands do not match the mask length, they are extended by concatenating
8790   // them with undef vectors.  That is probably the right thing for other
8791   // targets, but for NEON it is better to concatenate two double-register
8792   // size vector operands into a single quad-register size vector.  Do that
8793   // transformation here:
8794   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
8795   //   shuffle(concat(v1, v2), undef)
8796   SDValue Op0 = N->getOperand(0);
8797   SDValue Op1 = N->getOperand(1);
8798   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8799       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8800       Op0.getNumOperands() != 2 ||
8801       Op1.getNumOperands() != 2)
8802     return SDValue();
8803   SDValue Concat0Op1 = Op0.getOperand(1);
8804   SDValue Concat1Op1 = Op1.getOperand(1);
8805   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8806       Concat1Op1.getOpcode() != ISD::UNDEF)
8807     return SDValue();
8808   // Skip the transformation if any of the types are illegal.
8809   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8810   EVT VT = N->getValueType(0);
8811   if (!TLI.isTypeLegal(VT) ||
8812       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8813       !TLI.isTypeLegal(Concat1Op1.getValueType()))
8814     return SDValue();
8815
8816   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
8817                                   Op0.getOperand(0), Op1.getOperand(0));
8818   // Translate the shuffle mask.
8819   SmallVector<int, 16> NewMask;
8820   unsigned NumElts = VT.getVectorNumElements();
8821   unsigned HalfElts = NumElts/2;
8822   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8823   for (unsigned n = 0; n < NumElts; ++n) {
8824     int MaskElt = SVN->getMaskElt(n);
8825     int NewElt = -1;
8826     if (MaskElt < (int)HalfElts)
8827       NewElt = MaskElt;
8828     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8829       NewElt = HalfElts + MaskElt - NumElts;
8830     NewMask.push_back(NewElt);
8831   }
8832   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
8833                               DAG.getUNDEF(VT), NewMask.data());
8834 }
8835
8836 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
8837 /// NEON load/store intrinsics, and generic vector load/stores, to merge
8838 /// base address updates.
8839 /// For generic load/stores, the memory type is assumed to be a vector.
8840 /// The caller is assumed to have checked legality.
8841 static SDValue CombineBaseUpdate(SDNode *N,
8842                                  TargetLowering::DAGCombinerInfo &DCI) {
8843   SelectionDAG &DAG = DCI.DAG;
8844   const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8845                             N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8846   const bool isStore = N->getOpcode() == ISD::STORE;
8847   const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
8848   SDValue Addr = N->getOperand(AddrOpIdx);
8849   MemSDNode *MemN = cast<MemSDNode>(N);
8850   SDLoc dl(N);
8851
8852   // Search for a use of the address operand that is an increment.
8853   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8854          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8855     SDNode *User = *UI;
8856     if (User->getOpcode() != ISD::ADD ||
8857         UI.getUse().getResNo() != Addr.getResNo())
8858       continue;
8859
8860     // Check that the add is independent of the load/store.  Otherwise, folding
8861     // it would create a cycle.
8862     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8863       continue;
8864
8865     // Find the new opcode for the updating load/store.
8866     bool isLoadOp = true;
8867     bool isLaneOp = false;
8868     unsigned NewOpc = 0;
8869     unsigned NumVecs = 0;
8870     if (isIntrinsic) {
8871       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8872       switch (IntNo) {
8873       default: llvm_unreachable("unexpected intrinsic for Neon base update");
8874       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
8875         NumVecs = 1; break;
8876       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
8877         NumVecs = 2; break;
8878       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
8879         NumVecs = 3; break;
8880       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
8881         NumVecs = 4; break;
8882       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8883         NumVecs = 2; isLaneOp = true; break;
8884       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8885         NumVecs = 3; isLaneOp = true; break;
8886       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8887         NumVecs = 4; isLaneOp = true; break;
8888       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
8889         NumVecs = 1; isLoadOp = false; break;
8890       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
8891         NumVecs = 2; isLoadOp = false; break;
8892       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
8893         NumVecs = 3; isLoadOp = false; break;
8894       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
8895         NumVecs = 4; isLoadOp = false; break;
8896       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8897         NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
8898       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8899         NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
8900       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8901         NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
8902       }
8903     } else {
8904       isLaneOp = true;
8905       switch (N->getOpcode()) {
8906       default: llvm_unreachable("unexpected opcode for Neon base update");
8907       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8908       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8909       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8910       case ISD::LOAD:       NewOpc = ARMISD::VLD1_UPD;
8911         NumVecs = 1; isLaneOp = false; break;
8912       case ISD::STORE:      NewOpc = ARMISD::VST1_UPD;
8913         NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
8914       }
8915     }
8916
8917     // Find the size of memory referenced by the load/store.
8918     EVT VecTy;
8919     if (isLoadOp) {
8920       VecTy = N->getValueType(0);
8921     } else if (isIntrinsic) {
8922       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8923     } else {
8924       assert(isStore && "Node has to be a load, a store, or an intrinsic!");
8925       VecTy = N->getOperand(1).getValueType();
8926     }
8927
8928     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8929     if (isLaneOp)
8930       NumBytes /= VecTy.getVectorNumElements();
8931
8932     // If the increment is a constant, it must match the memory ref size.
8933     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8934     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8935       uint64_t IncVal = CInc->getZExtValue();
8936       if (IncVal != NumBytes)
8937         continue;
8938     } else if (NumBytes >= 3 * 16) {
8939       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8940       // separate instructions that make it harder to use a non-constant update.
8941       continue;
8942     }
8943
8944     // OK, we found an ADD we can fold into the base update.
8945     // Now, create a _UPD node, taking care of not breaking alignment.
8946
8947     EVT AlignedVecTy = VecTy;
8948     unsigned Alignment = MemN->getAlignment();
8949
8950     // If this is a less-than-standard-aligned load/store, change the type to
8951     // match the standard alignment.
8952     // The alignment is overlooked when selecting _UPD variants; and it's
8953     // easier to introduce bitcasts here than fix that.
8954     // There are 3 ways to get to this base-update combine:
8955     // - intrinsics: they are assumed to be properly aligned (to the standard
8956     //   alignment of the memory type), so we don't need to do anything.
8957     // - ARMISD::VLDx nodes: they are only generated from the aforementioned
8958     //   intrinsics, so, likewise, there's nothing to do.
8959     // - generic load/store instructions: the alignment is specified as an
8960     //   explicit operand, rather than implicitly as the standard alignment
8961     //   of the memory type (like the intrisics).  We need to change the
8962     //   memory type to match the explicit alignment.  That way, we don't
8963     //   generate non-standard-aligned ARMISD::VLDx nodes.
8964     if (isa<LSBaseSDNode>(N)) {
8965       if (Alignment == 0)
8966         Alignment = 1;
8967       if (Alignment < VecTy.getScalarSizeInBits() / 8) {
8968         MVT EltTy = MVT::getIntegerVT(Alignment * 8);
8969         assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
8970         assert(!isLaneOp && "Unexpected generic load/store lane.");
8971         unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
8972         AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
8973       }
8974       // Don't set an explicit alignment on regular load/stores that we want
8975       // to transform to VLD/VST 1_UPD nodes.
8976       // This matches the behavior of regular load/stores, which only get an
8977       // explicit alignment if the MMO alignment is larger than the standard
8978       // alignment of the memory type.
8979       // Intrinsics, however, always get an explicit alignment, set to the
8980       // alignment of the MMO.
8981       Alignment = 1;
8982     }
8983
8984     // Create the new updating load/store node.
8985     // First, create an SDVTList for the new updating node's results.
8986     EVT Tys[6];
8987     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
8988     unsigned n;
8989     for (n = 0; n < NumResultVecs; ++n)
8990       Tys[n] = AlignedVecTy;
8991     Tys[n++] = MVT::i32;
8992     Tys[n] = MVT::Other;
8993     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
8994
8995     // Then, gather the new node's operands.
8996     SmallVector<SDValue, 8> Ops;
8997     Ops.push_back(N->getOperand(0)); // incoming chain
8998     Ops.push_back(N->getOperand(AddrOpIdx));
8999     Ops.push_back(Inc);
9000
9001     if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
9002       // Try to match the intrinsic's signature
9003       Ops.push_back(StN->getValue());
9004     } else {
9005       // Loads (and of course intrinsics) match the intrinsics' signature,
9006       // so just add all but the alignment operand.
9007       for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
9008         Ops.push_back(N->getOperand(i));
9009     }
9010
9011     // For all node types, the alignment operand is always the last one.
9012     Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
9013
9014     // If this is a non-standard-aligned STORE, the penultimate operand is the
9015     // stored value.  Bitcast it to the aligned type.
9016     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
9017       SDValue &StVal = Ops[Ops.size()-2];
9018       StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
9019     }
9020
9021     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys,
9022                                            Ops, AlignedVecTy,
9023                                            MemN->getMemOperand());
9024
9025     // Update the uses.
9026     SmallVector<SDValue, 5> NewResults;
9027     for (unsigned i = 0; i < NumResultVecs; ++i)
9028       NewResults.push_back(SDValue(UpdN.getNode(), i));
9029
9030     // If this is an non-standard-aligned LOAD, the first result is the loaded
9031     // value.  Bitcast it to the expected result type.
9032     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
9033       SDValue &LdVal = NewResults[0];
9034       LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
9035     }
9036
9037     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9038     DCI.CombineTo(N, NewResults);
9039     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9040
9041     break;
9042   }
9043   return SDValue();
9044 }
9045
9046 static SDValue PerformVLDCombine(SDNode *N,
9047                                  TargetLowering::DAGCombinerInfo &DCI) {
9048   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9049     return SDValue();
9050
9051   return CombineBaseUpdate(N, DCI);
9052 }
9053
9054 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9055 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9056 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
9057 /// return true.
9058 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9059   SelectionDAG &DAG = DCI.DAG;
9060   EVT VT = N->getValueType(0);
9061   // vldN-dup instructions only support 64-bit vectors for N > 1.
9062   if (!VT.is64BitVector())
9063     return false;
9064
9065   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9066   SDNode *VLD = N->getOperand(0).getNode();
9067   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9068     return false;
9069   unsigned NumVecs = 0;
9070   unsigned NewOpc = 0;
9071   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9072   if (IntNo == Intrinsic::arm_neon_vld2lane) {
9073     NumVecs = 2;
9074     NewOpc = ARMISD::VLD2DUP;
9075   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9076     NumVecs = 3;
9077     NewOpc = ARMISD::VLD3DUP;
9078   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9079     NumVecs = 4;
9080     NewOpc = ARMISD::VLD4DUP;
9081   } else {
9082     return false;
9083   }
9084
9085   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9086   // numbers match the load.
9087   unsigned VLDLaneNo =
9088     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9089   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9090        UI != UE; ++UI) {
9091     // Ignore uses of the chain result.
9092     if (UI.getUse().getResNo() == NumVecs)
9093       continue;
9094     SDNode *User = *UI;
9095     if (User->getOpcode() != ARMISD::VDUPLANE ||
9096         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9097       return false;
9098   }
9099
9100   // Create the vldN-dup node.
9101   EVT Tys[5];
9102   unsigned n;
9103   for (n = 0; n < NumVecs; ++n)
9104     Tys[n] = VT;
9105   Tys[n] = MVT::Other;
9106   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9107   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9108   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9109   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9110                                            Ops, VLDMemInt->getMemoryVT(),
9111                                            VLDMemInt->getMemOperand());
9112
9113   // Update the uses.
9114   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9115        UI != UE; ++UI) {
9116     unsigned ResNo = UI.getUse().getResNo();
9117     // Ignore uses of the chain result.
9118     if (ResNo == NumVecs)
9119       continue;
9120     SDNode *User = *UI;
9121     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9122   }
9123
9124   // Now the vldN-lane intrinsic is dead except for its chain result.
9125   // Update uses of the chain.
9126   std::vector<SDValue> VLDDupResults;
9127   for (unsigned n = 0; n < NumVecs; ++n)
9128     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9129   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9130   DCI.CombineTo(VLD, VLDDupResults);
9131
9132   return true;
9133 }
9134
9135 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9136 /// ARMISD::VDUPLANE.
9137 static SDValue PerformVDUPLANECombine(SDNode *N,
9138                                       TargetLowering::DAGCombinerInfo &DCI) {
9139   SDValue Op = N->getOperand(0);
9140
9141   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9142   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9143   if (CombineVLDDUP(N, DCI))
9144     return SDValue(N, 0);
9145
9146   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9147   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9148   while (Op.getOpcode() == ISD::BITCAST)
9149     Op = Op.getOperand(0);
9150   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9151     return SDValue();
9152
9153   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9154   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9155   // The canonical VMOV for a zero vector uses a 32-bit element size.
9156   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9157   unsigned EltBits;
9158   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9159     EltSize = 8;
9160   EVT VT = N->getValueType(0);
9161   if (EltSize > VT.getVectorElementType().getSizeInBits())
9162     return SDValue();
9163
9164   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9165 }
9166
9167 static SDValue PerformLOADCombine(SDNode *N,
9168                                   TargetLowering::DAGCombinerInfo &DCI) {
9169   EVT VT = N->getValueType(0);
9170
9171   // If this is a legal vector load, try to combine it into a VLD1_UPD.
9172   if (ISD::isNormalLoad(N) && VT.isVector() &&
9173       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9174     return CombineBaseUpdate(N, DCI);
9175
9176   return SDValue();
9177 }
9178
9179 /// PerformSTORECombine - Target-specific dag combine xforms for
9180 /// ISD::STORE.
9181 static SDValue PerformSTORECombine(SDNode *N,
9182                                    TargetLowering::DAGCombinerInfo &DCI) {
9183   StoreSDNode *St = cast<StoreSDNode>(N);
9184   if (St->isVolatile())
9185     return SDValue();
9186
9187   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
9188   // pack all of the elements in one place.  Next, store to memory in fewer
9189   // chunks.
9190   SDValue StVal = St->getValue();
9191   EVT VT = StVal.getValueType();
9192   if (St->isTruncatingStore() && VT.isVector()) {
9193     SelectionDAG &DAG = DCI.DAG;
9194     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9195     EVT StVT = St->getMemoryVT();
9196     unsigned NumElems = VT.getVectorNumElements();
9197     assert(StVT != VT && "Cannot truncate to the same type");
9198     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
9199     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
9200
9201     // From, To sizes and ElemCount must be pow of two
9202     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
9203
9204     // We are going to use the original vector elt for storing.
9205     // Accumulated smaller vector elements must be a multiple of the store size.
9206     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
9207
9208     unsigned SizeRatio  = FromEltSz / ToEltSz;
9209     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
9210
9211     // Create a type on which we perform the shuffle.
9212     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9213                                      NumElems*SizeRatio);
9214     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9215
9216     SDLoc DL(St);
9217     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9218     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9219     for (unsigned i = 0; i < NumElems; ++i)
9220       ShuffleVec[i] = TLI.isBigEndian() ? (i+1) * SizeRatio - 1 : i * SizeRatio;
9221
9222     // Can't shuffle using an illegal type.
9223     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9224
9225     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9226                                 DAG.getUNDEF(WideVec.getValueType()),
9227                                 ShuffleVec.data());
9228     // At this point all of the data is stored at the bottom of the
9229     // register. We now need to save it to mem.
9230
9231     // Find the largest store unit
9232     MVT StoreType = MVT::i8;
9233     for (MVT Tp : MVT::integer_valuetypes()) {
9234       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9235         StoreType = Tp;
9236     }
9237     // Didn't find a legal store type.
9238     if (!TLI.isTypeLegal(StoreType))
9239       return SDValue();
9240
9241     // Bitcast the original vector into a vector of store-size units
9242     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9243             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9244     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9245     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9246     SmallVector<SDValue, 8> Chains;
9247     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8, DL,
9248                                         TLI.getPointerTy());
9249     SDValue BasePtr = St->getBasePtr();
9250
9251     // Perform one or more big stores into memory.
9252     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9253     for (unsigned I = 0; I < E; I++) {
9254       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9255                                    StoreType, ShuffWide,
9256                                    DAG.getIntPtrConstant(I, DL));
9257       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9258                                 St->getPointerInfo(), St->isVolatile(),
9259                                 St->isNonTemporal(), St->getAlignment());
9260       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9261                             Increment);
9262       Chains.push_back(Ch);
9263     }
9264     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
9265   }
9266
9267   if (!ISD::isNormalStore(St))
9268     return SDValue();
9269
9270   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9271   // ARM stores of arguments in the same cache line.
9272   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9273       StVal.getNode()->hasOneUse()) {
9274     SelectionDAG  &DAG = DCI.DAG;
9275     bool isBigEndian = DAG.getTargetLoweringInfo().isBigEndian();
9276     SDLoc DL(St);
9277     SDValue BasePtr = St->getBasePtr();
9278     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9279                                   StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
9280                                   BasePtr, St->getPointerInfo(), St->isVolatile(),
9281                                   St->isNonTemporal(), St->getAlignment());
9282
9283     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9284                                     DAG.getConstant(4, DL, MVT::i32));
9285     return DAG.getStore(NewST1.getValue(0), DL,
9286                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
9287                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9288                         St->isNonTemporal(),
9289                         std::min(4U, St->getAlignment() / 2));
9290   }
9291
9292   if (StVal.getValueType() == MVT::i64 &&
9293       StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9294
9295     // Bitcast an i64 store extracted from a vector to f64.
9296     // Otherwise, the i64 value will be legalized to a pair of i32 values.
9297     SelectionDAG &DAG = DCI.DAG;
9298     SDLoc dl(StVal);
9299     SDValue IntVec = StVal.getOperand(0);
9300     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9301                                    IntVec.getValueType().getVectorNumElements());
9302     SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9303     SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9304                                  Vec, StVal.getOperand(1));
9305     dl = SDLoc(N);
9306     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9307     // Make the DAGCombiner fold the bitcasts.
9308     DCI.AddToWorklist(Vec.getNode());
9309     DCI.AddToWorklist(ExtElt.getNode());
9310     DCI.AddToWorklist(V.getNode());
9311     return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9312                         St->getPointerInfo(), St->isVolatile(),
9313                         St->isNonTemporal(), St->getAlignment(),
9314                         St->getAAInfo());
9315   }
9316
9317   // If this is a legal vector store, try to combine it into a VST1_UPD.
9318   if (ISD::isNormalStore(N) && VT.isVector() &&
9319       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9320     return CombineBaseUpdate(N, DCI);
9321
9322   return SDValue();
9323 }
9324
9325 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9326 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9327 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9328 {
9329   integerPart cN;
9330   integerPart c0 = 0;
9331   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9332        I != E; I++) {
9333     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9334     if (!C)
9335       return false;
9336
9337     bool isExact;
9338     APFloat APF = C->getValueAPF();
9339     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9340         != APFloat::opOK || !isExact)
9341       return false;
9342
9343     c0 = (I == 0) ? cN : c0;
9344     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9345       return false;
9346   }
9347   C = c0;
9348   return true;
9349 }
9350
9351 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9352 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9353 /// when the VMUL has a constant operand that is a power of 2.
9354 ///
9355 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9356 ///  vmul.f32        d16, d17, d16
9357 ///  vcvt.s32.f32    d16, d16
9358 /// becomes:
9359 ///  vcvt.s32.f32    d16, d16, #3
9360 static SDValue PerformVCVTCombine(SDNode *N,
9361                                   TargetLowering::DAGCombinerInfo &DCI,
9362                                   const ARMSubtarget *Subtarget) {
9363   SelectionDAG &DAG = DCI.DAG;
9364   SDValue Op = N->getOperand(0);
9365
9366   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9367       Op.getOpcode() != ISD::FMUL)
9368     return SDValue();
9369
9370   uint64_t C;
9371   SDValue N0 = Op->getOperand(0);
9372   SDValue ConstVec = Op->getOperand(1);
9373   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9374
9375   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9376       !isConstVecPow2(ConstVec, isSigned, C))
9377     return SDValue();
9378
9379   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9380   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9381   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9382   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32 ||
9383       NumLanes > 4) {
9384     // These instructions only exist converting from f32 to i32. We can handle
9385     // smaller integers by generating an extra truncate, but larger ones would
9386     // be lossy. We also can't handle more then 4 lanes, since these intructions
9387     // only support v2i32/v4i32 types.
9388     return SDValue();
9389   }
9390
9391   SDLoc dl(N);
9392   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9393     Intrinsic::arm_neon_vcvtfp2fxu;
9394   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9395                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9396                                  DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9397                                  N0,
9398                                  DAG.getConstant(Log2_64(C), dl, MVT::i32));
9399
9400   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9401     FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
9402
9403   return FixConv;
9404 }
9405
9406 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9407 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9408 /// when the VDIV has a constant operand that is a power of 2.
9409 ///
9410 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9411 ///  vcvt.f32.s32    d16, d16
9412 ///  vdiv.f32        d16, d17, d16
9413 /// becomes:
9414 ///  vcvt.f32.s32    d16, d16, #3
9415 static SDValue PerformVDIVCombine(SDNode *N,
9416                                   TargetLowering::DAGCombinerInfo &DCI,
9417                                   const ARMSubtarget *Subtarget) {
9418   SelectionDAG &DAG = DCI.DAG;
9419   SDValue Op = N->getOperand(0);
9420   unsigned OpOpcode = Op.getNode()->getOpcode();
9421
9422   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9423       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9424     return SDValue();
9425
9426   uint64_t C;
9427   SDValue ConstVec = N->getOperand(1);
9428   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9429
9430   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9431       !isConstVecPow2(ConstVec, isSigned, C))
9432     return SDValue();
9433
9434   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9435   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9436   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9437     // These instructions only exist converting from i32 to f32. We can handle
9438     // smaller integers by generating an extra extend, but larger ones would
9439     // be lossy.
9440     return SDValue();
9441   }
9442
9443   SDLoc dl(N);
9444   SDValue ConvInput = Op.getOperand(0);
9445   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9446   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9447     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9448                             dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9449                             ConvInput);
9450
9451   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9452     Intrinsic::arm_neon_vcvtfxu2fp;
9453   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9454                      Op.getValueType(),
9455                      DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9456                      ConvInput, DAG.getConstant(Log2_64(C), dl, MVT::i32));
9457 }
9458
9459 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9460 /// operand of a vector shift operation, where all the elements of the
9461 /// build_vector must have the same constant integer value.
9462 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9463   // Ignore bit_converts.
9464   while (Op.getOpcode() == ISD::BITCAST)
9465     Op = Op.getOperand(0);
9466   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9467   APInt SplatBits, SplatUndef;
9468   unsigned SplatBitSize;
9469   bool HasAnyUndefs;
9470   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9471                                       HasAnyUndefs, ElementBits) ||
9472       SplatBitSize > ElementBits)
9473     return false;
9474   Cnt = SplatBits.getSExtValue();
9475   return true;
9476 }
9477
9478 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9479 /// operand of a vector shift left operation.  That value must be in the range:
9480 ///   0 <= Value < ElementBits for a left shift; or
9481 ///   0 <= Value <= ElementBits for a long left shift.
9482 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9483   assert(VT.isVector() && "vector shift count is not a vector type");
9484   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9485   if (! getVShiftImm(Op, ElementBits, Cnt))
9486     return false;
9487   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9488 }
9489
9490 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9491 /// operand of a vector shift right operation.  For a shift opcode, the value
9492 /// is positive, but for an intrinsic the value count must be negative. The
9493 /// absolute value must be in the range:
9494 ///   1 <= |Value| <= ElementBits for a right shift; or
9495 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9496 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9497                          int64_t &Cnt) {
9498   assert(VT.isVector() && "vector shift count is not a vector type");
9499   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9500   if (! getVShiftImm(Op, ElementBits, Cnt))
9501     return false;
9502   if (isIntrinsic)
9503     Cnt = -Cnt;
9504   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9505 }
9506
9507 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9508 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9509   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9510   switch (IntNo) {
9511   default:
9512     // Don't do anything for most intrinsics.
9513     break;
9514
9515   // Vector shifts: check for immediate versions and lower them.
9516   // Note: This is done during DAG combining instead of DAG legalizing because
9517   // the build_vectors for 64-bit vector element shift counts are generally
9518   // not legal, and it is hard to see their values after they get legalized to
9519   // loads from a constant pool.
9520   case Intrinsic::arm_neon_vshifts:
9521   case Intrinsic::arm_neon_vshiftu:
9522   case Intrinsic::arm_neon_vrshifts:
9523   case Intrinsic::arm_neon_vrshiftu:
9524   case Intrinsic::arm_neon_vrshiftn:
9525   case Intrinsic::arm_neon_vqshifts:
9526   case Intrinsic::arm_neon_vqshiftu:
9527   case Intrinsic::arm_neon_vqshiftsu:
9528   case Intrinsic::arm_neon_vqshiftns:
9529   case Intrinsic::arm_neon_vqshiftnu:
9530   case Intrinsic::arm_neon_vqshiftnsu:
9531   case Intrinsic::arm_neon_vqrshiftns:
9532   case Intrinsic::arm_neon_vqrshiftnu:
9533   case Intrinsic::arm_neon_vqrshiftnsu: {
9534     EVT VT = N->getOperand(1).getValueType();
9535     int64_t Cnt;
9536     unsigned VShiftOpc = 0;
9537
9538     switch (IntNo) {
9539     case Intrinsic::arm_neon_vshifts:
9540     case Intrinsic::arm_neon_vshiftu:
9541       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9542         VShiftOpc = ARMISD::VSHL;
9543         break;
9544       }
9545       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9546         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9547                      ARMISD::VSHRs : ARMISD::VSHRu);
9548         break;
9549       }
9550       return SDValue();
9551
9552     case Intrinsic::arm_neon_vrshifts:
9553     case Intrinsic::arm_neon_vrshiftu:
9554       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9555         break;
9556       return SDValue();
9557
9558     case Intrinsic::arm_neon_vqshifts:
9559     case Intrinsic::arm_neon_vqshiftu:
9560       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9561         break;
9562       return SDValue();
9563
9564     case Intrinsic::arm_neon_vqshiftsu:
9565       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9566         break;
9567       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9568
9569     case Intrinsic::arm_neon_vrshiftn:
9570     case Intrinsic::arm_neon_vqshiftns:
9571     case Intrinsic::arm_neon_vqshiftnu:
9572     case Intrinsic::arm_neon_vqshiftnsu:
9573     case Intrinsic::arm_neon_vqrshiftns:
9574     case Intrinsic::arm_neon_vqrshiftnu:
9575     case Intrinsic::arm_neon_vqrshiftnsu:
9576       // Narrowing shifts require an immediate right shift.
9577       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9578         break;
9579       llvm_unreachable("invalid shift count for narrowing vector shift "
9580                        "intrinsic");
9581
9582     default:
9583       llvm_unreachable("unhandled vector shift");
9584     }
9585
9586     switch (IntNo) {
9587     case Intrinsic::arm_neon_vshifts:
9588     case Intrinsic::arm_neon_vshiftu:
9589       // Opcode already set above.
9590       break;
9591     case Intrinsic::arm_neon_vrshifts:
9592       VShiftOpc = ARMISD::VRSHRs; break;
9593     case Intrinsic::arm_neon_vrshiftu:
9594       VShiftOpc = ARMISD::VRSHRu; break;
9595     case Intrinsic::arm_neon_vrshiftn:
9596       VShiftOpc = ARMISD::VRSHRN; break;
9597     case Intrinsic::arm_neon_vqshifts:
9598       VShiftOpc = ARMISD::VQSHLs; break;
9599     case Intrinsic::arm_neon_vqshiftu:
9600       VShiftOpc = ARMISD::VQSHLu; break;
9601     case Intrinsic::arm_neon_vqshiftsu:
9602       VShiftOpc = ARMISD::VQSHLsu; break;
9603     case Intrinsic::arm_neon_vqshiftns:
9604       VShiftOpc = ARMISD::VQSHRNs; break;
9605     case Intrinsic::arm_neon_vqshiftnu:
9606       VShiftOpc = ARMISD::VQSHRNu; break;
9607     case Intrinsic::arm_neon_vqshiftnsu:
9608       VShiftOpc = ARMISD::VQSHRNsu; break;
9609     case Intrinsic::arm_neon_vqrshiftns:
9610       VShiftOpc = ARMISD::VQRSHRNs; break;
9611     case Intrinsic::arm_neon_vqrshiftnu:
9612       VShiftOpc = ARMISD::VQRSHRNu; break;
9613     case Intrinsic::arm_neon_vqrshiftnsu:
9614       VShiftOpc = ARMISD::VQRSHRNsu; break;
9615     }
9616
9617     SDLoc dl(N);
9618     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
9619                        N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
9620   }
9621
9622   case Intrinsic::arm_neon_vshiftins: {
9623     EVT VT = N->getOperand(1).getValueType();
9624     int64_t Cnt;
9625     unsigned VShiftOpc = 0;
9626
9627     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9628       VShiftOpc = ARMISD::VSLI;
9629     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9630       VShiftOpc = ARMISD::VSRI;
9631     else {
9632       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9633     }
9634
9635     SDLoc dl(N);
9636     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
9637                        N->getOperand(1), N->getOperand(2),
9638                        DAG.getConstant(Cnt, dl, MVT::i32));
9639   }
9640
9641   case Intrinsic::arm_neon_vqrshifts:
9642   case Intrinsic::arm_neon_vqrshiftu:
9643     // No immediate versions of these to check for.
9644     break;
9645   }
9646
9647   return SDValue();
9648 }
9649
9650 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9651 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9652 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9653 /// vector element shift counts are generally not legal, and it is hard to see
9654 /// their values after they get legalized to loads from a constant pool.
9655 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9656                                    const ARMSubtarget *ST) {
9657   EVT VT = N->getValueType(0);
9658   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9659     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9660     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9661     SDValue N1 = N->getOperand(1);
9662     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9663       SDValue N0 = N->getOperand(0);
9664       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9665           DAG.MaskedValueIsZero(N0.getOperand(0),
9666                                 APInt::getHighBitsSet(32, 16)))
9667         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9668     }
9669   }
9670
9671   // Nothing to be done for scalar shifts.
9672   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9673   if (!VT.isVector() || !TLI.isTypeLegal(VT))
9674     return SDValue();
9675
9676   assert(ST->hasNEON() && "unexpected vector shift");
9677   int64_t Cnt;
9678
9679   switch (N->getOpcode()) {
9680   default: llvm_unreachable("unexpected shift opcode");
9681
9682   case ISD::SHL:
9683     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
9684       SDLoc dl(N);
9685       return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
9686                          DAG.getConstant(Cnt, dl, MVT::i32));
9687     }
9688     break;
9689
9690   case ISD::SRA:
9691   case ISD::SRL:
9692     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9693       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9694                             ARMISD::VSHRs : ARMISD::VSHRu);
9695       SDLoc dl(N);
9696       return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
9697                          DAG.getConstant(Cnt, dl, MVT::i32));
9698     }
9699   }
9700   return SDValue();
9701 }
9702
9703 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9704 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9705 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9706                                     const ARMSubtarget *ST) {
9707   SDValue N0 = N->getOperand(0);
9708
9709   // Check for sign- and zero-extensions of vector extract operations of 8-
9710   // and 16-bit vector elements.  NEON supports these directly.  They are
9711   // handled during DAG combining because type legalization will promote them
9712   // to 32-bit types and it is messy to recognize the operations after that.
9713   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9714     SDValue Vec = N0.getOperand(0);
9715     SDValue Lane = N0.getOperand(1);
9716     EVT VT = N->getValueType(0);
9717     EVT EltVT = N0.getValueType();
9718     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9719
9720     if (VT == MVT::i32 &&
9721         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9722         TLI.isTypeLegal(Vec.getValueType()) &&
9723         isa<ConstantSDNode>(Lane)) {
9724
9725       unsigned Opc = 0;
9726       switch (N->getOpcode()) {
9727       default: llvm_unreachable("unexpected opcode");
9728       case ISD::SIGN_EXTEND:
9729         Opc = ARMISD::VGETLANEs;
9730         break;
9731       case ISD::ZERO_EXTEND:
9732       case ISD::ANY_EXTEND:
9733         Opc = ARMISD::VGETLANEu;
9734         break;
9735       }
9736       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9737     }
9738   }
9739
9740   return SDValue();
9741 }
9742
9743 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9744 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9745 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9746                                        const ARMSubtarget *ST) {
9747   // If the target supports NEON, try to use vmax/vmin instructions for f32
9748   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
9749   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
9750   // a NaN; only do the transformation when it matches that behavior.
9751
9752   // For now only do this when using NEON for FP operations; if using VFP, it
9753   // is not obvious that the benefit outweighs the cost of switching to the
9754   // NEON pipeline.
9755   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9756       N->getValueType(0) != MVT::f32)
9757     return SDValue();
9758
9759   SDValue CondLHS = N->getOperand(0);
9760   SDValue CondRHS = N->getOperand(1);
9761   SDValue LHS = N->getOperand(2);
9762   SDValue RHS = N->getOperand(3);
9763   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9764
9765   unsigned Opcode = 0;
9766   bool IsReversed;
9767   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9768     IsReversed = false; // x CC y ? x : y
9769   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9770     IsReversed = true ; // x CC y ? y : x
9771   } else {
9772     return SDValue();
9773   }
9774
9775   bool IsUnordered;
9776   switch (CC) {
9777   default: break;
9778   case ISD::SETOLT:
9779   case ISD::SETOLE:
9780   case ISD::SETLT:
9781   case ISD::SETLE:
9782   case ISD::SETULT:
9783   case ISD::SETULE:
9784     // If LHS is NaN, an ordered comparison will be false and the result will
9785     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
9786     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9787     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9788     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9789       break;
9790     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9791     // will return -0, so vmin can only be used for unsafe math or if one of
9792     // the operands is known to be nonzero.
9793     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9794         !DAG.getTarget().Options.UnsafeFPMath &&
9795         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9796       break;
9797     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9798     break;
9799
9800   case ISD::SETOGT:
9801   case ISD::SETOGE:
9802   case ISD::SETGT:
9803   case ISD::SETGE:
9804   case ISD::SETUGT:
9805   case ISD::SETUGE:
9806     // If LHS is NaN, an ordered comparison will be false and the result will
9807     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
9808     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9809     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9810     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9811       break;
9812     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9813     // will return +0, so vmax can only be used for unsafe math or if one of
9814     // the operands is known to be nonzero.
9815     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9816         !DAG.getTarget().Options.UnsafeFPMath &&
9817         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9818       break;
9819     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9820     break;
9821   }
9822
9823   if (!Opcode)
9824     return SDValue();
9825   return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9826 }
9827
9828 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9829 SDValue
9830 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9831   SDValue Cmp = N->getOperand(4);
9832   if (Cmp.getOpcode() != ARMISD::CMPZ)
9833     // Only looking at EQ and NE cases.
9834     return SDValue();
9835
9836   EVT VT = N->getValueType(0);
9837   SDLoc dl(N);
9838   SDValue LHS = Cmp.getOperand(0);
9839   SDValue RHS = Cmp.getOperand(1);
9840   SDValue FalseVal = N->getOperand(0);
9841   SDValue TrueVal = N->getOperand(1);
9842   SDValue ARMcc = N->getOperand(2);
9843   ARMCC::CondCodes CC =
9844     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9845
9846   // Simplify
9847   //   mov     r1, r0
9848   //   cmp     r1, x
9849   //   mov     r0, y
9850   //   moveq   r0, x
9851   // to
9852   //   cmp     r0, x
9853   //   movne   r0, y
9854   //
9855   //   mov     r1, r0
9856   //   cmp     r1, x
9857   //   mov     r0, x
9858   //   movne   r0, y
9859   // to
9860   //   cmp     r0, x
9861   //   movne   r0, y
9862   /// FIXME: Turn this into a target neutral optimization?
9863   SDValue Res;
9864   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9865     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9866                       N->getOperand(3), Cmp);
9867   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9868     SDValue ARMcc;
9869     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9870     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9871                       N->getOperand(3), NewCmp);
9872   }
9873
9874   if (Res.getNode()) {
9875     APInt KnownZero, KnownOne;
9876     DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
9877     // Capture demanded bits information that would be otherwise lost.
9878     if (KnownZero == 0xfffffffe)
9879       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9880                         DAG.getValueType(MVT::i1));
9881     else if (KnownZero == 0xffffff00)
9882       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9883                         DAG.getValueType(MVT::i8));
9884     else if (KnownZero == 0xffff0000)
9885       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9886                         DAG.getValueType(MVT::i16));
9887   }
9888
9889   return Res;
9890 }
9891
9892 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9893                                              DAGCombinerInfo &DCI) const {
9894   switch (N->getOpcode()) {
9895   default: break;
9896   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
9897   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
9898   case ISD::SUB:        return PerformSUBCombine(N, DCI);
9899   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
9900   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
9901   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
9902   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
9903   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
9904   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
9905   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9906   case ISD::STORE:      return PerformSTORECombine(N, DCI);
9907   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
9908   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9909   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9910   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9911   case ISD::FP_TO_SINT:
9912   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9913   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
9914   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9915   case ISD::SHL:
9916   case ISD::SRA:
9917   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
9918   case ISD::SIGN_EXTEND:
9919   case ISD::ZERO_EXTEND:
9920   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9921   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9922   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9923   case ISD::LOAD:       return PerformLOADCombine(N, DCI);
9924   case ARMISD::VLD2DUP:
9925   case ARMISD::VLD3DUP:
9926   case ARMISD::VLD4DUP:
9927     return PerformVLDCombine(N, DCI);
9928   case ARMISD::BUILD_VECTOR:
9929     return PerformARMBUILD_VECTORCombine(N, DCI);
9930   case ISD::INTRINSIC_VOID:
9931   case ISD::INTRINSIC_W_CHAIN:
9932     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9933     case Intrinsic::arm_neon_vld1:
9934     case Intrinsic::arm_neon_vld2:
9935     case Intrinsic::arm_neon_vld3:
9936     case Intrinsic::arm_neon_vld4:
9937     case Intrinsic::arm_neon_vld2lane:
9938     case Intrinsic::arm_neon_vld3lane:
9939     case Intrinsic::arm_neon_vld4lane:
9940     case Intrinsic::arm_neon_vst1:
9941     case Intrinsic::arm_neon_vst2:
9942     case Intrinsic::arm_neon_vst3:
9943     case Intrinsic::arm_neon_vst4:
9944     case Intrinsic::arm_neon_vst2lane:
9945     case Intrinsic::arm_neon_vst3lane:
9946     case Intrinsic::arm_neon_vst4lane:
9947       return PerformVLDCombine(N, DCI);
9948     default: break;
9949     }
9950     break;
9951   }
9952   return SDValue();
9953 }
9954
9955 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9956                                                           EVT VT) const {
9957   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9958 }
9959
9960 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
9961                                                        unsigned,
9962                                                        unsigned,
9963                                                        bool *Fast) const {
9964   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9965   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9966
9967   switch (VT.getSimpleVT().SimpleTy) {
9968   default:
9969     return false;
9970   case MVT::i8:
9971   case MVT::i16:
9972   case MVT::i32: {
9973     // Unaligned access can use (for example) LRDB, LRDH, LDR
9974     if (AllowsUnaligned) {
9975       if (Fast)
9976         *Fast = Subtarget->hasV7Ops();
9977       return true;
9978     }
9979     return false;
9980   }
9981   case MVT::f64:
9982   case MVT::v2f64: {
9983     // For any little-endian targets with neon, we can support unaligned ld/st
9984     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9985     // A big-endian target may also explicitly support unaligned accesses
9986     if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9987       if (Fast)
9988         *Fast = true;
9989       return true;
9990     }
9991     return false;
9992   }
9993   }
9994 }
9995
9996 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9997                        unsigned AlignCheck) {
9998   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9999           (DstAlign == 0 || DstAlign % AlignCheck == 0));
10000 }
10001
10002 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10003                                            unsigned DstAlign, unsigned SrcAlign,
10004                                            bool IsMemset, bool ZeroMemset,
10005                                            bool MemcpyStrSrc,
10006                                            MachineFunction &MF) const {
10007   const Function *F = MF.getFunction();
10008
10009   // See if we can use NEON instructions for this...
10010   if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
10011       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10012     bool Fast;
10013     if (Size >= 16 &&
10014         (memOpAlign(SrcAlign, DstAlign, 16) ||
10015          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
10016       return MVT::v2f64;
10017     } else if (Size >= 8 &&
10018                (memOpAlign(SrcAlign, DstAlign, 8) ||
10019                 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
10020                  Fast))) {
10021       return MVT::f64;
10022     }
10023   }
10024
10025   // Lowering to i32/i16 if the size permits.
10026   if (Size >= 4)
10027     return MVT::i32;
10028   else if (Size >= 2)
10029     return MVT::i16;
10030
10031   // Let the target-independent logic figure it out.
10032   return MVT::Other;
10033 }
10034
10035 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10036   if (Val.getOpcode() != ISD::LOAD)
10037     return false;
10038
10039   EVT VT1 = Val.getValueType();
10040   if (!VT1.isSimple() || !VT1.isInteger() ||
10041       !VT2.isSimple() || !VT2.isInteger())
10042     return false;
10043
10044   switch (VT1.getSimpleVT().SimpleTy) {
10045   default: break;
10046   case MVT::i1:
10047   case MVT::i8:
10048   case MVT::i16:
10049     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10050     return true;
10051   }
10052
10053   return false;
10054 }
10055
10056 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
10057   EVT VT = ExtVal.getValueType();
10058
10059   if (!isTypeLegal(VT))
10060     return false;
10061
10062   // Don't create a loadext if we can fold the extension into a wide/long
10063   // instruction.
10064   // If there's more than one user instruction, the loadext is desirable no
10065   // matter what.  There can be two uses by the same instruction.
10066   if (ExtVal->use_empty() ||
10067       !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
10068     return true;
10069
10070   SDNode *U = *ExtVal->use_begin();
10071   if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
10072        U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
10073     return false;
10074
10075   return true;
10076 }
10077
10078 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10079   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10080     return false;
10081
10082   if (!isTypeLegal(EVT::getEVT(Ty1)))
10083     return false;
10084
10085   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10086
10087   // Assuming the caller doesn't have a zeroext or signext return parameter,
10088   // truncation all the way down to i1 is valid.
10089   return true;
10090 }
10091
10092
10093 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10094   if (V < 0)
10095     return false;
10096
10097   unsigned Scale = 1;
10098   switch (VT.getSimpleVT().SimpleTy) {
10099   default: return false;
10100   case MVT::i1:
10101   case MVT::i8:
10102     // Scale == 1;
10103     break;
10104   case MVT::i16:
10105     // Scale == 2;
10106     Scale = 2;
10107     break;
10108   case MVT::i32:
10109     // Scale == 4;
10110     Scale = 4;
10111     break;
10112   }
10113
10114   if ((V & (Scale - 1)) != 0)
10115     return false;
10116   V /= Scale;
10117   return V == (V & ((1LL << 5) - 1));
10118 }
10119
10120 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10121                                       const ARMSubtarget *Subtarget) {
10122   bool isNeg = false;
10123   if (V < 0) {
10124     isNeg = true;
10125     V = - V;
10126   }
10127
10128   switch (VT.getSimpleVT().SimpleTy) {
10129   default: return false;
10130   case MVT::i1:
10131   case MVT::i8:
10132   case MVT::i16:
10133   case MVT::i32:
10134     // + imm12 or - imm8
10135     if (isNeg)
10136       return V == (V & ((1LL << 8) - 1));
10137     return V == (V & ((1LL << 12) - 1));
10138   case MVT::f32:
10139   case MVT::f64:
10140     // Same as ARM mode. FIXME: NEON?
10141     if (!Subtarget->hasVFP2())
10142       return false;
10143     if ((V & 3) != 0)
10144       return false;
10145     V >>= 2;
10146     return V == (V & ((1LL << 8) - 1));
10147   }
10148 }
10149
10150 /// isLegalAddressImmediate - Return true if the integer value can be used
10151 /// as the offset of the target addressing mode for load / store of the
10152 /// given type.
10153 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10154                                     const ARMSubtarget *Subtarget) {
10155   if (V == 0)
10156     return true;
10157
10158   if (!VT.isSimple())
10159     return false;
10160
10161   if (Subtarget->isThumb1Only())
10162     return isLegalT1AddressImmediate(V, VT);
10163   else if (Subtarget->isThumb2())
10164     return isLegalT2AddressImmediate(V, VT, Subtarget);
10165
10166   // ARM mode.
10167   if (V < 0)
10168     V = - V;
10169   switch (VT.getSimpleVT().SimpleTy) {
10170   default: return false;
10171   case MVT::i1:
10172   case MVT::i8:
10173   case MVT::i32:
10174     // +- imm12
10175     return V == (V & ((1LL << 12) - 1));
10176   case MVT::i16:
10177     // +- imm8
10178     return V == (V & ((1LL << 8) - 1));
10179   case MVT::f32:
10180   case MVT::f64:
10181     if (!Subtarget->hasVFP2()) // FIXME: NEON?
10182       return false;
10183     if ((V & 3) != 0)
10184       return false;
10185     V >>= 2;
10186     return V == (V & ((1LL << 8) - 1));
10187   }
10188 }
10189
10190 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10191                                                       EVT VT) const {
10192   int Scale = AM.Scale;
10193   if (Scale < 0)
10194     return false;
10195
10196   switch (VT.getSimpleVT().SimpleTy) {
10197   default: return false;
10198   case MVT::i1:
10199   case MVT::i8:
10200   case MVT::i16:
10201   case MVT::i32:
10202     if (Scale == 1)
10203       return true;
10204     // r + r << imm
10205     Scale = Scale & ~1;
10206     return Scale == 2 || Scale == 4 || Scale == 8;
10207   case MVT::i64:
10208     // r + r
10209     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10210       return true;
10211     return false;
10212   case MVT::isVoid:
10213     // Note, we allow "void" uses (basically, uses that aren't loads or
10214     // stores), because arm allows folding a scale into many arithmetic
10215     // operations.  This should be made more precise and revisited later.
10216
10217     // Allow r << imm, but the imm has to be a multiple of two.
10218     if (Scale & 1) return false;
10219     return isPowerOf2_32(Scale);
10220   }
10221 }
10222
10223 /// isLegalAddressingMode - Return true if the addressing mode represented
10224 /// by AM is legal for this target, for a load/store of the specified type.
10225 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10226                                               Type *Ty) const {
10227   EVT VT = getValueType(Ty, true);
10228   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10229     return false;
10230
10231   // Can never fold addr of global into load/store.
10232   if (AM.BaseGV)
10233     return false;
10234
10235   switch (AM.Scale) {
10236   case 0:  // no scale reg, must be "r+i" or "r", or "i".
10237     break;
10238   case 1:
10239     if (Subtarget->isThumb1Only())
10240       return false;
10241     // FALL THROUGH.
10242   default:
10243     // ARM doesn't support any R+R*scale+imm addr modes.
10244     if (AM.BaseOffs)
10245       return false;
10246
10247     if (!VT.isSimple())
10248       return false;
10249
10250     if (Subtarget->isThumb2())
10251       return isLegalT2ScaledAddressingMode(AM, VT);
10252
10253     int Scale = AM.Scale;
10254     switch (VT.getSimpleVT().SimpleTy) {
10255     default: return false;
10256     case MVT::i1:
10257     case MVT::i8:
10258     case MVT::i32:
10259       if (Scale < 0) Scale = -Scale;
10260       if (Scale == 1)
10261         return true;
10262       // r + r << imm
10263       return isPowerOf2_32(Scale & ~1);
10264     case MVT::i16:
10265     case MVT::i64:
10266       // r + r
10267       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10268         return true;
10269       return false;
10270
10271     case MVT::isVoid:
10272       // Note, we allow "void" uses (basically, uses that aren't loads or
10273       // stores), because arm allows folding a scale into many arithmetic
10274       // operations.  This should be made more precise and revisited later.
10275
10276       // Allow r << imm, but the imm has to be a multiple of two.
10277       if (Scale & 1) return false;
10278       return isPowerOf2_32(Scale);
10279     }
10280   }
10281   return true;
10282 }
10283
10284 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10285 /// icmp immediate, that is the target has icmp instructions which can compare
10286 /// a register against the immediate without having to materialize the
10287 /// immediate into a register.
10288 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10289   // Thumb2 and ARM modes can use cmn for negative immediates.
10290   if (!Subtarget->isThumb())
10291     return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
10292   if (Subtarget->isThumb2())
10293     return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
10294   // Thumb1 doesn't have cmn, and only 8-bit immediates.
10295   return Imm >= 0 && Imm <= 255;
10296 }
10297
10298 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10299 /// *or sub* immediate, that is the target has add or sub instructions which can
10300 /// add a register with the immediate without having to materialize the
10301 /// immediate into a register.
10302 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10303   // Same encoding for add/sub, just flip the sign.
10304   int64_t AbsImm = std::abs(Imm);
10305   if (!Subtarget->isThumb())
10306     return ARM_AM::getSOImmVal(AbsImm) != -1;
10307   if (Subtarget->isThumb2())
10308     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10309   // Thumb1 only has 8-bit unsigned immediate.
10310   return AbsImm >= 0 && AbsImm <= 255;
10311 }
10312
10313 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10314                                       bool isSEXTLoad, SDValue &Base,
10315                                       SDValue &Offset, bool &isInc,
10316                                       SelectionDAG &DAG) {
10317   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10318     return false;
10319
10320   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10321     // AddressingMode 3
10322     Base = Ptr->getOperand(0);
10323     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10324       int RHSC = (int)RHS->getZExtValue();
10325       if (RHSC < 0 && RHSC > -256) {
10326         assert(Ptr->getOpcode() == ISD::ADD);
10327         isInc = false;
10328         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10329         return true;
10330       }
10331     }
10332     isInc = (Ptr->getOpcode() == ISD::ADD);
10333     Offset = Ptr->getOperand(1);
10334     return true;
10335   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10336     // AddressingMode 2
10337     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10338       int RHSC = (int)RHS->getZExtValue();
10339       if (RHSC < 0 && RHSC > -0x1000) {
10340         assert(Ptr->getOpcode() == ISD::ADD);
10341         isInc = false;
10342         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10343         Base = Ptr->getOperand(0);
10344         return true;
10345       }
10346     }
10347
10348     if (Ptr->getOpcode() == ISD::ADD) {
10349       isInc = true;
10350       ARM_AM::ShiftOpc ShOpcVal=
10351         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10352       if (ShOpcVal != ARM_AM::no_shift) {
10353         Base = Ptr->getOperand(1);
10354         Offset = Ptr->getOperand(0);
10355       } else {
10356         Base = Ptr->getOperand(0);
10357         Offset = Ptr->getOperand(1);
10358       }
10359       return true;
10360     }
10361
10362     isInc = (Ptr->getOpcode() == ISD::ADD);
10363     Base = Ptr->getOperand(0);
10364     Offset = Ptr->getOperand(1);
10365     return true;
10366   }
10367
10368   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10369   return false;
10370 }
10371
10372 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10373                                      bool isSEXTLoad, SDValue &Base,
10374                                      SDValue &Offset, bool &isInc,
10375                                      SelectionDAG &DAG) {
10376   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10377     return false;
10378
10379   Base = Ptr->getOperand(0);
10380   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10381     int RHSC = (int)RHS->getZExtValue();
10382     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10383       assert(Ptr->getOpcode() == ISD::ADD);
10384       isInc = false;
10385       Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10386       return true;
10387     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10388       isInc = Ptr->getOpcode() == ISD::ADD;
10389       Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
10390       return true;
10391     }
10392   }
10393
10394   return false;
10395 }
10396
10397 /// getPreIndexedAddressParts - returns true by value, base pointer and
10398 /// offset pointer and addressing mode by reference if the node's address
10399 /// can be legally represented as pre-indexed load / store address.
10400 bool
10401 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10402                                              SDValue &Offset,
10403                                              ISD::MemIndexedMode &AM,
10404                                              SelectionDAG &DAG) const {
10405   if (Subtarget->isThumb1Only())
10406     return false;
10407
10408   EVT VT;
10409   SDValue Ptr;
10410   bool isSEXTLoad = false;
10411   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10412     Ptr = LD->getBasePtr();
10413     VT  = LD->getMemoryVT();
10414     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10415   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10416     Ptr = ST->getBasePtr();
10417     VT  = ST->getMemoryVT();
10418   } else
10419     return false;
10420
10421   bool isInc;
10422   bool isLegal = false;
10423   if (Subtarget->isThumb2())
10424     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10425                                        Offset, isInc, DAG);
10426   else
10427     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10428                                         Offset, isInc, DAG);
10429   if (!isLegal)
10430     return false;
10431
10432   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10433   return true;
10434 }
10435
10436 /// getPostIndexedAddressParts - returns true by value, base pointer and
10437 /// offset pointer and addressing mode by reference if this node can be
10438 /// combined with a load / store to form a post-indexed load / store.
10439 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10440                                                    SDValue &Base,
10441                                                    SDValue &Offset,
10442                                                    ISD::MemIndexedMode &AM,
10443                                                    SelectionDAG &DAG) const {
10444   if (Subtarget->isThumb1Only())
10445     return false;
10446
10447   EVT VT;
10448   SDValue Ptr;
10449   bool isSEXTLoad = false;
10450   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10451     VT  = LD->getMemoryVT();
10452     Ptr = LD->getBasePtr();
10453     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10454   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10455     VT  = ST->getMemoryVT();
10456     Ptr = ST->getBasePtr();
10457   } else
10458     return false;
10459
10460   bool isInc;
10461   bool isLegal = false;
10462   if (Subtarget->isThumb2())
10463     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10464                                        isInc, DAG);
10465   else
10466     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10467                                         isInc, DAG);
10468   if (!isLegal)
10469     return false;
10470
10471   if (Ptr != Base) {
10472     // Swap base ptr and offset to catch more post-index load / store when
10473     // it's legal. In Thumb2 mode, offset must be an immediate.
10474     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10475         !Subtarget->isThumb2())
10476       std::swap(Base, Offset);
10477
10478     // Post-indexed load / store update the base pointer.
10479     if (Ptr != Base)
10480       return false;
10481   }
10482
10483   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10484   return true;
10485 }
10486
10487 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10488                                                       APInt &KnownZero,
10489                                                       APInt &KnownOne,
10490                                                       const SelectionDAG &DAG,
10491                                                       unsigned Depth) const {
10492   unsigned BitWidth = KnownOne.getBitWidth();
10493   KnownZero = KnownOne = APInt(BitWidth, 0);
10494   switch (Op.getOpcode()) {
10495   default: break;
10496   case ARMISD::ADDC:
10497   case ARMISD::ADDE:
10498   case ARMISD::SUBC:
10499   case ARMISD::SUBE:
10500     // These nodes' second result is a boolean
10501     if (Op.getResNo() == 0)
10502       break;
10503     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10504     break;
10505   case ARMISD::CMOV: {
10506     // Bits are known zero/one if known on the LHS and RHS.
10507     DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10508     if (KnownZero == 0 && KnownOne == 0) return;
10509
10510     APInt KnownZeroRHS, KnownOneRHS;
10511     DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10512     KnownZero &= KnownZeroRHS;
10513     KnownOne  &= KnownOneRHS;
10514     return;
10515   }
10516   case ISD::INTRINSIC_W_CHAIN: {
10517     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10518     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10519     switch (IntID) {
10520     default: return;
10521     case Intrinsic::arm_ldaex:
10522     case Intrinsic::arm_ldrex: {
10523       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10524       unsigned MemBits = VT.getScalarType().getSizeInBits();
10525       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10526       return;
10527     }
10528     }
10529   }
10530   }
10531 }
10532
10533 //===----------------------------------------------------------------------===//
10534 //                           ARM Inline Assembly Support
10535 //===----------------------------------------------------------------------===//
10536
10537 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10538   // Looking for "rev" which is V6+.
10539   if (!Subtarget->hasV6Ops())
10540     return false;
10541
10542   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10543   std::string AsmStr = IA->getAsmString();
10544   SmallVector<StringRef, 4> AsmPieces;
10545   SplitString(AsmStr, AsmPieces, ";\n");
10546
10547   switch (AsmPieces.size()) {
10548   default: return false;
10549   case 1:
10550     AsmStr = AsmPieces[0];
10551     AsmPieces.clear();
10552     SplitString(AsmStr, AsmPieces, " \t,");
10553
10554     // rev $0, $1
10555     if (AsmPieces.size() == 3 &&
10556         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10557         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10558       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10559       if (Ty && Ty->getBitWidth() == 32)
10560         return IntrinsicLowering::LowerToByteSwap(CI);
10561     }
10562     break;
10563   }
10564
10565   return false;
10566 }
10567
10568 /// getConstraintType - Given a constraint letter, return the type of
10569 /// constraint it is for this target.
10570 ARMTargetLowering::ConstraintType
10571 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10572   if (Constraint.size() == 1) {
10573     switch (Constraint[0]) {
10574     default:  break;
10575     case 'l': return C_RegisterClass;
10576     case 'w': return C_RegisterClass;
10577     case 'h': return C_RegisterClass;
10578     case 'x': return C_RegisterClass;
10579     case 't': return C_RegisterClass;
10580     case 'j': return C_Other; // Constant for movw.
10581       // An address with a single base register. Due to the way we
10582       // currently handle addresses it is the same as an 'r' memory constraint.
10583     case 'Q': return C_Memory;
10584     }
10585   } else if (Constraint.size() == 2) {
10586     switch (Constraint[0]) {
10587     default: break;
10588     // All 'U+' constraints are addresses.
10589     case 'U': return C_Memory;
10590     }
10591   }
10592   return TargetLowering::getConstraintType(Constraint);
10593 }
10594
10595 /// Examine constraint type and operand type and determine a weight value.
10596 /// This object must already have been set up with the operand type
10597 /// and the current alternative constraint selected.
10598 TargetLowering::ConstraintWeight
10599 ARMTargetLowering::getSingleConstraintMatchWeight(
10600     AsmOperandInfo &info, const char *constraint) const {
10601   ConstraintWeight weight = CW_Invalid;
10602   Value *CallOperandVal = info.CallOperandVal;
10603     // If we don't have a value, we can't do a match,
10604     // but allow it at the lowest weight.
10605   if (!CallOperandVal)
10606     return CW_Default;
10607   Type *type = CallOperandVal->getType();
10608   // Look at the constraint type.
10609   switch (*constraint) {
10610   default:
10611     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10612     break;
10613   case 'l':
10614     if (type->isIntegerTy()) {
10615       if (Subtarget->isThumb())
10616         weight = CW_SpecificReg;
10617       else
10618         weight = CW_Register;
10619     }
10620     break;
10621   case 'w':
10622     if (type->isFloatingPointTy())
10623       weight = CW_Register;
10624     break;
10625   }
10626   return weight;
10627 }
10628
10629 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10630 RCPair
10631 ARMTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
10632                                                 const std::string &Constraint,
10633                                                 MVT VT) const {
10634   if (Constraint.size() == 1) {
10635     // GCC ARM Constraint Letters
10636     switch (Constraint[0]) {
10637     case 'l': // Low regs or general regs.
10638       if (Subtarget->isThumb())
10639         return RCPair(0U, &ARM::tGPRRegClass);
10640       return RCPair(0U, &ARM::GPRRegClass);
10641     case 'h': // High regs or no regs.
10642       if (Subtarget->isThumb())
10643         return RCPair(0U, &ARM::hGPRRegClass);
10644       break;
10645     case 'r':
10646       if (Subtarget->isThumb1Only())
10647         return RCPair(0U, &ARM::tGPRRegClass);
10648       return RCPair(0U, &ARM::GPRRegClass);
10649     case 'w':
10650       if (VT == MVT::Other)
10651         break;
10652       if (VT == MVT::f32)
10653         return RCPair(0U, &ARM::SPRRegClass);
10654       if (VT.getSizeInBits() == 64)
10655         return RCPair(0U, &ARM::DPRRegClass);
10656       if (VT.getSizeInBits() == 128)
10657         return RCPair(0U, &ARM::QPRRegClass);
10658       break;
10659     case 'x':
10660       if (VT == MVT::Other)
10661         break;
10662       if (VT == MVT::f32)
10663         return RCPair(0U, &ARM::SPR_8RegClass);
10664       if (VT.getSizeInBits() == 64)
10665         return RCPair(0U, &ARM::DPR_8RegClass);
10666       if (VT.getSizeInBits() == 128)
10667         return RCPair(0U, &ARM::QPR_8RegClass);
10668       break;
10669     case 't':
10670       if (VT == MVT::f32)
10671         return RCPair(0U, &ARM::SPRRegClass);
10672       break;
10673     }
10674   }
10675   if (StringRef("{cc}").equals_lower(Constraint))
10676     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10677
10678   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10679 }
10680
10681 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10682 /// vector.  If it is invalid, don't add anything to Ops.
10683 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10684                                                      std::string &Constraint,
10685                                                      std::vector<SDValue>&Ops,
10686                                                      SelectionDAG &DAG) const {
10687   SDValue Result;
10688
10689   // Currently only support length 1 constraints.
10690   if (Constraint.length() != 1) return;
10691
10692   char ConstraintLetter = Constraint[0];
10693   switch (ConstraintLetter) {
10694   default: break;
10695   case 'j':
10696   case 'I': case 'J': case 'K': case 'L':
10697   case 'M': case 'N': case 'O':
10698     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10699     if (!C)
10700       return;
10701
10702     int64_t CVal64 = C->getSExtValue();
10703     int CVal = (int) CVal64;
10704     // None of these constraints allow values larger than 32 bits.  Check
10705     // that the value fits in an int.
10706     if (CVal != CVal64)
10707       return;
10708
10709     switch (ConstraintLetter) {
10710       case 'j':
10711         // Constant suitable for movw, must be between 0 and
10712         // 65535.
10713         if (Subtarget->hasV6T2Ops())
10714           if (CVal >= 0 && CVal <= 65535)
10715             break;
10716         return;
10717       case 'I':
10718         if (Subtarget->isThumb1Only()) {
10719           // This must be a constant between 0 and 255, for ADD
10720           // immediates.
10721           if (CVal >= 0 && CVal <= 255)
10722             break;
10723         } else if (Subtarget->isThumb2()) {
10724           // A constant that can be used as an immediate value in a
10725           // data-processing instruction.
10726           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10727             break;
10728         } else {
10729           // A constant that can be used as an immediate value in a
10730           // data-processing instruction.
10731           if (ARM_AM::getSOImmVal(CVal) != -1)
10732             break;
10733         }
10734         return;
10735
10736       case 'J':
10737         if (Subtarget->isThumb()) {  // FIXME thumb2
10738           // This must be a constant between -255 and -1, for negated ADD
10739           // immediates. This can be used in GCC with an "n" modifier that
10740           // prints the negated value, for use with SUB instructions. It is
10741           // not useful otherwise but is implemented for compatibility.
10742           if (CVal >= -255 && CVal <= -1)
10743             break;
10744         } else {
10745           // This must be a constant between -4095 and 4095. It is not clear
10746           // what this constraint is intended for. Implemented for
10747           // compatibility with GCC.
10748           if (CVal >= -4095 && CVal <= 4095)
10749             break;
10750         }
10751         return;
10752
10753       case 'K':
10754         if (Subtarget->isThumb1Only()) {
10755           // A 32-bit value where only one byte has a nonzero value. Exclude
10756           // zero to match GCC. This constraint is used by GCC internally for
10757           // constants that can be loaded with a move/shift combination.
10758           // It is not useful otherwise but is implemented for compatibility.
10759           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10760             break;
10761         } else if (Subtarget->isThumb2()) {
10762           // A constant whose bitwise inverse can be used as an immediate
10763           // value in a data-processing instruction. This can be used in GCC
10764           // with a "B" modifier that prints the inverted value, for use with
10765           // BIC and MVN instructions. It is not useful otherwise but is
10766           // implemented for compatibility.
10767           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10768             break;
10769         } else {
10770           // A constant whose bitwise inverse can be used as an immediate
10771           // value in a data-processing instruction. This can be used in GCC
10772           // with a "B" modifier that prints the inverted value, for use with
10773           // BIC and MVN instructions. It is not useful otherwise but is
10774           // implemented for compatibility.
10775           if (ARM_AM::getSOImmVal(~CVal) != -1)
10776             break;
10777         }
10778         return;
10779
10780       case 'L':
10781         if (Subtarget->isThumb1Only()) {
10782           // This must be a constant between -7 and 7,
10783           // for 3-operand ADD/SUB immediate instructions.
10784           if (CVal >= -7 && CVal < 7)
10785             break;
10786         } else if (Subtarget->isThumb2()) {
10787           // A constant whose negation can be used as an immediate value in a
10788           // data-processing instruction. This can be used in GCC with an "n"
10789           // modifier that prints the negated value, for use with SUB
10790           // instructions. It is not useful otherwise but is implemented for
10791           // compatibility.
10792           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10793             break;
10794         } else {
10795           // A constant whose negation can be used as an immediate value in a
10796           // data-processing instruction. This can be used in GCC with an "n"
10797           // modifier that prints the negated value, for use with SUB
10798           // instructions. It is not useful otherwise but is implemented for
10799           // compatibility.
10800           if (ARM_AM::getSOImmVal(-CVal) != -1)
10801             break;
10802         }
10803         return;
10804
10805       case 'M':
10806         if (Subtarget->isThumb()) { // FIXME thumb2
10807           // This must be a multiple of 4 between 0 and 1020, for
10808           // ADD sp + immediate.
10809           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10810             break;
10811         } else {
10812           // A power of two or a constant between 0 and 32.  This is used in
10813           // GCC for the shift amount on shifted register operands, but it is
10814           // useful in general for any shift amounts.
10815           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10816             break;
10817         }
10818         return;
10819
10820       case 'N':
10821         if (Subtarget->isThumb()) {  // FIXME thumb2
10822           // This must be a constant between 0 and 31, for shift amounts.
10823           if (CVal >= 0 && CVal <= 31)
10824             break;
10825         }
10826         return;
10827
10828       case 'O':
10829         if (Subtarget->isThumb()) {  // FIXME thumb2
10830           // This must be a multiple of 4 between -508 and 508, for
10831           // ADD/SUB sp = sp + immediate.
10832           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10833             break;
10834         }
10835         return;
10836     }
10837     Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
10838     break;
10839   }
10840
10841   if (Result.getNode()) {
10842     Ops.push_back(Result);
10843     return;
10844   }
10845   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10846 }
10847
10848 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10849   assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10850   unsigned Opcode = Op->getOpcode();
10851   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10852          "Invalid opcode for Div/Rem lowering");
10853   bool isSigned = (Opcode == ISD::SDIVREM);
10854   EVT VT = Op->getValueType(0);
10855   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10856
10857   RTLIB::Libcall LC;
10858   switch (VT.getSimpleVT().SimpleTy) {
10859   default: llvm_unreachable("Unexpected request for libcall!");
10860   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
10861   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10862   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10863   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10864   }
10865
10866   SDValue InChain = DAG.getEntryNode();
10867
10868   TargetLowering::ArgListTy Args;
10869   TargetLowering::ArgListEntry Entry;
10870   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
10871     EVT ArgVT = Op->getOperand(i).getValueType();
10872     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10873     Entry.Node = Op->getOperand(i);
10874     Entry.Ty = ArgTy;
10875     Entry.isSExt = isSigned;
10876     Entry.isZExt = !isSigned;
10877     Args.push_back(Entry);
10878   }
10879
10880   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
10881                                          getPointerTy());
10882
10883   Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
10884
10885   SDLoc dl(Op);
10886   TargetLowering::CallLoweringInfo CLI(DAG);
10887   CLI.setDebugLoc(dl).setChain(InChain)
10888     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
10889     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
10890
10891   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
10892   return CallInfo.first;
10893 }
10894
10895 SDValue
10896 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
10897   assert(Subtarget->isTargetWindows() && "unsupported target platform");
10898   SDLoc DL(Op);
10899
10900   // Get the inputs.
10901   SDValue Chain = Op.getOperand(0);
10902   SDValue Size  = Op.getOperand(1);
10903
10904   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
10905                               DAG.getConstant(2, DL, MVT::i32));
10906
10907   SDValue Flag;
10908   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
10909   Flag = Chain.getValue(1);
10910
10911   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10912   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
10913
10914   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
10915   Chain = NewSP.getValue(1);
10916
10917   SDValue Ops[2] = { NewSP, Chain };
10918   return DAG.getMergeValues(Ops, DL);
10919 }
10920
10921 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
10922   assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
10923          "Unexpected type for custom-lowering FP_EXTEND");
10924
10925   RTLIB::Libcall LC;
10926   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
10927
10928   SDValue SrcVal = Op.getOperand(0);
10929   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
10930                      /*isSigned*/ false, SDLoc(Op)).first;
10931 }
10932
10933 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
10934   assert(Op.getOperand(0).getValueType() == MVT::f64 &&
10935          Subtarget->isFPOnlySP() &&
10936          "Unexpected type for custom-lowering FP_ROUND");
10937
10938   RTLIB::Libcall LC;
10939   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
10940
10941   SDValue SrcVal = Op.getOperand(0);
10942   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
10943                      /*isSigned*/ false, SDLoc(Op)).first;
10944 }
10945
10946 bool
10947 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10948   // The ARM target isn't yet aware of offsets.
10949   return false;
10950 }
10951
10952 bool ARM::isBitFieldInvertedMask(unsigned v) {
10953   if (v == 0xffffffff)
10954     return false;
10955
10956   // there can be 1's on either or both "outsides", all the "inside"
10957   // bits must be 0's
10958   return isShiftedMask_32(~v);
10959 }
10960
10961 /// isFPImmLegal - Returns true if the target can instruction select the
10962 /// specified FP immediate natively. If false, the legalizer will
10963 /// materialize the FP immediate as a load from a constant pool.
10964 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10965   if (!Subtarget->hasVFP3())
10966     return false;
10967   if (VT == MVT::f32)
10968     return ARM_AM::getFP32Imm(Imm) != -1;
10969   if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
10970     return ARM_AM::getFP64Imm(Imm) != -1;
10971   return false;
10972 }
10973
10974 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10975 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
10976 /// specified in the intrinsic calls.
10977 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10978                                            const CallInst &I,
10979                                            unsigned Intrinsic) const {
10980   switch (Intrinsic) {
10981   case Intrinsic::arm_neon_vld1:
10982   case Intrinsic::arm_neon_vld2:
10983   case Intrinsic::arm_neon_vld3:
10984   case Intrinsic::arm_neon_vld4:
10985   case Intrinsic::arm_neon_vld2lane:
10986   case Intrinsic::arm_neon_vld3lane:
10987   case Intrinsic::arm_neon_vld4lane: {
10988     Info.opc = ISD::INTRINSIC_W_CHAIN;
10989     // Conservatively set memVT to the entire set of vectors loaded.
10990     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10991     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10992     Info.ptrVal = I.getArgOperand(0);
10993     Info.offset = 0;
10994     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10995     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10996     Info.vol = false; // volatile loads with NEON intrinsics not supported
10997     Info.readMem = true;
10998     Info.writeMem = false;
10999     return true;
11000   }
11001   case Intrinsic::arm_neon_vst1:
11002   case Intrinsic::arm_neon_vst2:
11003   case Intrinsic::arm_neon_vst3:
11004   case Intrinsic::arm_neon_vst4:
11005   case Intrinsic::arm_neon_vst2lane:
11006   case Intrinsic::arm_neon_vst3lane:
11007   case Intrinsic::arm_neon_vst4lane: {
11008     Info.opc = ISD::INTRINSIC_VOID;
11009     // Conservatively set memVT to the entire set of vectors stored.
11010     unsigned NumElts = 0;
11011     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11012       Type *ArgTy = I.getArgOperand(ArgI)->getType();
11013       if (!ArgTy->isVectorTy())
11014         break;
11015       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
11016     }
11017     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11018     Info.ptrVal = I.getArgOperand(0);
11019     Info.offset = 0;
11020     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11021     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11022     Info.vol = false; // volatile stores with NEON intrinsics not supported
11023     Info.readMem = false;
11024     Info.writeMem = true;
11025     return true;
11026   }
11027   case Intrinsic::arm_ldaex:
11028   case Intrinsic::arm_ldrex: {
11029     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11030     Info.opc = ISD::INTRINSIC_W_CHAIN;
11031     Info.memVT = MVT::getVT(PtrTy->getElementType());
11032     Info.ptrVal = I.getArgOperand(0);
11033     Info.offset = 0;
11034     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11035     Info.vol = true;
11036     Info.readMem = true;
11037     Info.writeMem = false;
11038     return true;
11039   }
11040   case Intrinsic::arm_stlex:
11041   case Intrinsic::arm_strex: {
11042     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11043     Info.opc = ISD::INTRINSIC_W_CHAIN;
11044     Info.memVT = MVT::getVT(PtrTy->getElementType());
11045     Info.ptrVal = I.getArgOperand(1);
11046     Info.offset = 0;
11047     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11048     Info.vol = true;
11049     Info.readMem = false;
11050     Info.writeMem = true;
11051     return true;
11052   }
11053   case Intrinsic::arm_stlexd:
11054   case Intrinsic::arm_strexd: {
11055     Info.opc = ISD::INTRINSIC_W_CHAIN;
11056     Info.memVT = MVT::i64;
11057     Info.ptrVal = I.getArgOperand(2);
11058     Info.offset = 0;
11059     Info.align = 8;
11060     Info.vol = true;
11061     Info.readMem = false;
11062     Info.writeMem = true;
11063     return true;
11064   }
11065   case Intrinsic::arm_ldaexd:
11066   case Intrinsic::arm_ldrexd: {
11067     Info.opc = ISD::INTRINSIC_W_CHAIN;
11068     Info.memVT = MVT::i64;
11069     Info.ptrVal = I.getArgOperand(0);
11070     Info.offset = 0;
11071     Info.align = 8;
11072     Info.vol = true;
11073     Info.readMem = true;
11074     Info.writeMem = false;
11075     return true;
11076   }
11077   default:
11078     break;
11079   }
11080
11081   return false;
11082 }
11083
11084 /// \brief Returns true if it is beneficial to convert a load of a constant
11085 /// to just the constant itself.
11086 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11087                                                           Type *Ty) const {
11088   assert(Ty->isIntegerTy());
11089
11090   unsigned Bits = Ty->getPrimitiveSizeInBits();
11091   if (Bits == 0 || Bits > 32)
11092     return false;
11093   return true;
11094 }
11095
11096 bool ARMTargetLowering::hasLoadLinkedStoreConditional() const { return true; }
11097
11098 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
11099                                         ARM_MB::MemBOpt Domain) const {
11100   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11101
11102   // First, if the target has no DMB, see what fallback we can use.
11103   if (!Subtarget->hasDataBarrier()) {
11104     // Some ARMv6 cpus can support data barriers with an mcr instruction.
11105     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
11106     // here.
11107     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
11108       Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
11109       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
11110                         Builder.getInt32(0), Builder.getInt32(7),
11111                         Builder.getInt32(10), Builder.getInt32(5)};
11112       return Builder.CreateCall(MCR, args);
11113     } else {
11114       // Instead of using barriers, atomic accesses on these subtargets use
11115       // libcalls.
11116       llvm_unreachable("makeDMB on a target so old that it has no barriers");
11117     }
11118   } else {
11119     Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
11120     // Only a full system barrier exists in the M-class architectures.
11121     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
11122     Constant *CDomain = Builder.getInt32(Domain);
11123     return Builder.CreateCall(DMB, CDomain);
11124   }
11125 }
11126
11127 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11128 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11129                                          AtomicOrdering Ord, bool IsStore,
11130                                          bool IsLoad) const {
11131   if (!getInsertFencesForAtomic())
11132     return nullptr;
11133
11134   switch (Ord) {
11135   case NotAtomic:
11136   case Unordered:
11137     llvm_unreachable("Invalid fence: unordered/non-atomic");
11138   case Monotonic:
11139   case Acquire:
11140     return nullptr; // Nothing to do
11141   case SequentiallyConsistent:
11142     if (!IsStore)
11143       return nullptr; // Nothing to do
11144     /*FALLTHROUGH*/
11145   case Release:
11146   case AcquireRelease:
11147     if (Subtarget->isSwift())
11148       return makeDMB(Builder, ARM_MB::ISHST);
11149     // FIXME: add a comment with a link to documentation justifying this.
11150     else
11151       return makeDMB(Builder, ARM_MB::ISH);
11152   }
11153   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
11154 }
11155
11156 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11157                                           AtomicOrdering Ord, bool IsStore,
11158                                           bool IsLoad) const {
11159   if (!getInsertFencesForAtomic())
11160     return nullptr;
11161
11162   switch (Ord) {
11163   case NotAtomic:
11164   case Unordered:
11165     llvm_unreachable("Invalid fence: unordered/not-atomic");
11166   case Monotonic:
11167   case Release:
11168     return nullptr; // Nothing to do
11169   case Acquire:
11170   case AcquireRelease:
11171   case SequentiallyConsistent:
11172     return makeDMB(Builder, ARM_MB::ISH);
11173   }
11174   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
11175 }
11176
11177 // Loads and stores less than 64-bits are already atomic; ones above that
11178 // are doomed anyway, so defer to the default libcall and blame the OS when
11179 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11180 // anything for those.
11181 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11182   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11183   return (Size == 64) && !Subtarget->isMClass();
11184 }
11185
11186 // Loads and stores less than 64-bits are already atomic; ones above that
11187 // are doomed anyway, so defer to the default libcall and blame the OS when
11188 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11189 // anything for those.
11190 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
11191 // guarantee, see DDI0406C ARM architecture reference manual,
11192 // sections A8.8.72-74 LDRD)
11193 bool ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11194   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11195   return (Size == 64) && !Subtarget->isMClass();
11196 }
11197
11198 // For the real atomic operations, we have ldrex/strex up to 32 bits,
11199 // and up to 64 bits on the non-M profiles
11200 TargetLoweringBase::AtomicRMWExpansionKind
11201 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11202   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11203   return (Size <= (Subtarget->isMClass() ? 32U : 64U))
11204              ? AtomicRMWExpansionKind::LLSC
11205              : AtomicRMWExpansionKind::None;
11206 }
11207
11208 // This has so far only been implemented for MachO.
11209 bool ARMTargetLowering::useLoadStackGuardNode() const {
11210   return Subtarget->isTargetMachO();
11211 }
11212
11213 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
11214                                                   unsigned &Cost) const {
11215   // If we do not have NEON, vector types are not natively supported.
11216   if (!Subtarget->hasNEON())
11217     return false;
11218
11219   // Floating point values and vector values map to the same register file.
11220   // Therefore, althought we could do a store extract of a vector type, this is
11221   // better to leave at float as we have more freedom in the addressing mode for
11222   // those.
11223   if (VectorTy->isFPOrFPVectorTy())
11224     return false;
11225
11226   // If the index is unknown at compile time, this is very expensive to lower
11227   // and it is not possible to combine the store with the extract.
11228   if (!isa<ConstantInt>(Idx))
11229     return false;
11230
11231   assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
11232   unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
11233   // We can do a store + vector extract on any vector that fits perfectly in a D
11234   // or Q register.
11235   if (BitWidth == 64 || BitWidth == 128) {
11236     Cost = 0;
11237     return true;
11238   }
11239   return false;
11240 }
11241
11242 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11243                                          AtomicOrdering Ord) const {
11244   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11245   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11246   bool IsAcquire = isAtLeastAcquire(Ord);
11247
11248   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
11249   // intrinsic must return {i32, i32} and we have to recombine them into a
11250   // single i64 here.
11251   if (ValTy->getPrimitiveSizeInBits() == 64) {
11252     Intrinsic::ID Int =
11253         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
11254     Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
11255
11256     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11257     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
11258
11259     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11260     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11261     if (!Subtarget->isLittle())
11262       std::swap (Lo, Hi);
11263     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11264     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11265     return Builder.CreateOr(
11266         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
11267   }
11268
11269   Type *Tys[] = { Addr->getType() };
11270   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
11271   Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
11272
11273   return Builder.CreateTruncOrBitCast(
11274       Builder.CreateCall(Ldrex, Addr),
11275       cast<PointerType>(Addr->getType())->getElementType());
11276 }
11277
11278 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
11279                                                Value *Addr,
11280                                                AtomicOrdering Ord) const {
11281   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11282   bool IsRelease = isAtLeastRelease(Ord);
11283
11284   // Since the intrinsics must have legal type, the i64 intrinsics take two
11285   // parameters: "i32, i32". We must marshal Val into the appropriate form
11286   // before the call.
11287   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
11288     Intrinsic::ID Int =
11289         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
11290     Function *Strex = Intrinsic::getDeclaration(M, Int);
11291     Type *Int32Ty = Type::getInt32Ty(M->getContext());
11292
11293     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
11294     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
11295     if (!Subtarget->isLittle())
11296       std::swap (Lo, Hi);
11297     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11298     return Builder.CreateCall(Strex, {Lo, Hi, Addr});
11299   }
11300
11301   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
11302   Type *Tys[] = { Addr->getType() };
11303   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
11304
11305   return Builder.CreateCall(
11306       Strex, {Builder.CreateZExtOrBitCast(
11307                   Val, Strex->getFunctionType()->getParamType(0)),
11308               Addr});
11309 }
11310
11311 enum HABaseType {
11312   HA_UNKNOWN = 0,
11313   HA_FLOAT,
11314   HA_DOUBLE,
11315   HA_VECT64,
11316   HA_VECT128
11317 };
11318
11319 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
11320                                    uint64_t &Members) {
11321   if (const StructType *ST = dyn_cast<StructType>(Ty)) {
11322     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
11323       uint64_t SubMembers = 0;
11324       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
11325         return false;
11326       Members += SubMembers;
11327     }
11328   } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
11329     uint64_t SubMembers = 0;
11330     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
11331       return false;
11332     Members += SubMembers * AT->getNumElements();
11333   } else if (Ty->isFloatTy()) {
11334     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
11335       return false;
11336     Members = 1;
11337     Base = HA_FLOAT;
11338   } else if (Ty->isDoubleTy()) {
11339     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
11340       return false;
11341     Members = 1;
11342     Base = HA_DOUBLE;
11343   } else if (const VectorType *VT = dyn_cast<VectorType>(Ty)) {
11344     Members = 1;
11345     switch (Base) {
11346     case HA_FLOAT:
11347     case HA_DOUBLE:
11348       return false;
11349     case HA_VECT64:
11350       return VT->getBitWidth() == 64;
11351     case HA_VECT128:
11352       return VT->getBitWidth() == 128;
11353     case HA_UNKNOWN:
11354       switch (VT->getBitWidth()) {
11355       case 64:
11356         Base = HA_VECT64;
11357         return true;
11358       case 128:
11359         Base = HA_VECT128;
11360         return true;
11361       default:
11362         return false;
11363       }
11364     }
11365   }
11366
11367   return (Members > 0 && Members <= 4);
11368 }
11369
11370 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
11371 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
11372 /// passing according to AAPCS rules.
11373 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
11374     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11375   if (getEffectiveCallingConv(CallConv, isVarArg) !=
11376       CallingConv::ARM_AAPCS_VFP)
11377     return false;
11378
11379   HABaseType Base = HA_UNKNOWN;
11380   uint64_t Members = 0;
11381   bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
11382   DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
11383
11384   bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
11385   return IsHA || IsIntArray;
11386 }