Revert "Re-commit changes in r237579 with fix for bug breaking windows builds."
[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 /// MatchingStackOffset - Return true if the given stack call argument is
1934 /// already available in the same position (relatively) of the caller's
1935 /// incoming argument stack.
1936 static
1937 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1938                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1939                          const TargetInstrInfo *TII) {
1940   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1941   int FI = INT_MAX;
1942   if (Arg.getOpcode() == ISD::CopyFromReg) {
1943     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1944     if (!TargetRegisterInfo::isVirtualRegister(VR))
1945       return false;
1946     MachineInstr *Def = MRI->getVRegDef(VR);
1947     if (!Def)
1948       return false;
1949     if (!Flags.isByVal()) {
1950       if (!TII->isLoadFromStackSlot(Def, FI))
1951         return false;
1952     } else {
1953       return false;
1954     }
1955   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1956     if (Flags.isByVal())
1957       // ByVal argument is passed in as a pointer but it's now being
1958       // dereferenced. e.g.
1959       // define @foo(%struct.X* %A) {
1960       //   tail call @bar(%struct.X* byval %A)
1961       // }
1962       return false;
1963     SDValue Ptr = Ld->getBasePtr();
1964     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1965     if (!FINode)
1966       return false;
1967     FI = FINode->getIndex();
1968   } else
1969     return false;
1970
1971   assert(FI != INT_MAX);
1972   if (!MFI->isFixedObjectIndex(FI))
1973     return false;
1974   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1975 }
1976
1977 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1978 /// for tail call optimization. Targets which want to do tail call
1979 /// optimization should implement this function.
1980 bool
1981 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1982                                                      CallingConv::ID CalleeCC,
1983                                                      bool isVarArg,
1984                                                      bool isCalleeStructRet,
1985                                                      bool isCallerStructRet,
1986                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1987                                     const SmallVectorImpl<SDValue> &OutVals,
1988                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1989                                                      SelectionDAG& DAG) const {
1990   const Function *CallerF = DAG.getMachineFunction().getFunction();
1991   CallingConv::ID CallerCC = CallerF->getCallingConv();
1992   bool CCMatch = CallerCC == CalleeCC;
1993
1994   // Look for obvious safe cases to perform tail call optimization that do not
1995   // require ABI changes. This is what gcc calls sibcall.
1996
1997   // Do not sibcall optimize vararg calls unless the call site is not passing
1998   // any arguments.
1999   if (isVarArg && !Outs.empty())
2000     return false;
2001
2002   // Exception-handling functions need a special set of instructions to indicate
2003   // a return to the hardware. Tail-calling another function would probably
2004   // break this.
2005   if (CallerF->hasFnAttribute("interrupt"))
2006     return false;
2007
2008   // Also avoid sibcall optimization if either caller or callee uses struct
2009   // return semantics.
2010   if (isCalleeStructRet || isCallerStructRet)
2011     return false;
2012
2013   // FIXME: Completely disable sibcall for Thumb1 since ThumbRegisterInfo::
2014   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
2015   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
2016   // support in the assembler and linker to be used. This would need to be
2017   // fixed to fully support tail calls in Thumb1.
2018   //
2019   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
2020   // LR.  This means if we need to reload LR, it takes an extra instructions,
2021   // which outweighs the value of the tail call; but here we don't know yet
2022   // whether LR is going to be used.  Probably the right approach is to
2023   // generate the tail call here and turn it back into CALL/RET in
2024   // emitEpilogue if LR is used.
2025
2026   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
2027   // but we need to make sure there are enough registers; the only valid
2028   // registers are the 4 used for parameters.  We don't currently do this
2029   // case.
2030   if (Subtarget->isThumb1Only())
2031     return false;
2032
2033   // Externally-defined functions with weak linkage should not be
2034   // tail-called on ARM when the OS does not support dynamic
2035   // pre-emption of symbols, as the AAELF spec requires normal calls
2036   // to undefined weak functions to be replaced with a NOP or jump to the
2037   // next instruction. The behaviour of branch instructions in this
2038   // situation (as used for tail calls) is implementation-defined, so we
2039   // cannot rely on the linker replacing the tail call with a return.
2040   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2041     const GlobalValue *GV = G->getGlobal();
2042     const Triple TT(getTargetMachine().getTargetTriple());
2043     if (GV->hasExternalWeakLinkage() &&
2044         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2045       return false;
2046   }
2047
2048   // If the calling conventions do not match, then we'd better make sure the
2049   // results are returned in the same way as what the caller expects.
2050   if (!CCMatch) {
2051     SmallVector<CCValAssign, 16> RVLocs1;
2052     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2053                        *DAG.getContext(), Call);
2054     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2055
2056     SmallVector<CCValAssign, 16> RVLocs2;
2057     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2058                        *DAG.getContext(), Call);
2059     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2060
2061     if (RVLocs1.size() != RVLocs2.size())
2062       return false;
2063     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2064       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2065         return false;
2066       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2067         return false;
2068       if (RVLocs1[i].isRegLoc()) {
2069         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2070           return false;
2071       } else {
2072         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2073           return false;
2074       }
2075     }
2076   }
2077
2078   // If Caller's vararg or byval argument has been split between registers and
2079   // stack, do not perform tail call, since part of the argument is in caller's
2080   // local frame.
2081   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2082                                       getInfo<ARMFunctionInfo>();
2083   if (AFI_Caller->getArgRegsSaveSize())
2084     return false;
2085
2086   // If the callee takes no arguments then go on to check the results of the
2087   // call.
2088   if (!Outs.empty()) {
2089     // Check if stack adjustment is needed. For now, do not do this if any
2090     // argument is passed on the stack.
2091     SmallVector<CCValAssign, 16> ArgLocs;
2092     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2093                       *DAG.getContext(), Call);
2094     CCInfo.AnalyzeCallOperands(Outs,
2095                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2096     if (CCInfo.getNextStackOffset()) {
2097       MachineFunction &MF = DAG.getMachineFunction();
2098
2099       // Check if the arguments are already laid out in the right way as
2100       // the caller's fixed stack objects.
2101       MachineFrameInfo *MFI = MF.getFrameInfo();
2102       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2103       const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2104       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2105            i != e;
2106            ++i, ++realArgIdx) {
2107         CCValAssign &VA = ArgLocs[i];
2108         EVT RegVT = VA.getLocVT();
2109         SDValue Arg = OutVals[realArgIdx];
2110         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2111         if (VA.getLocInfo() == CCValAssign::Indirect)
2112           return false;
2113         if (VA.needsCustom()) {
2114           // f64 and vector types are split into multiple registers or
2115           // register/stack-slot combinations.  The types will not match
2116           // the registers; give up on memory f64 refs until we figure
2117           // out what to do about this.
2118           if (!VA.isRegLoc())
2119             return false;
2120           if (!ArgLocs[++i].isRegLoc())
2121             return false;
2122           if (RegVT == MVT::v2f64) {
2123             if (!ArgLocs[++i].isRegLoc())
2124               return false;
2125             if (!ArgLocs[++i].isRegLoc())
2126               return false;
2127           }
2128         } else if (!VA.isRegLoc()) {
2129           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2130                                    MFI, MRI, TII))
2131             return false;
2132         }
2133       }
2134     }
2135   }
2136
2137   return true;
2138 }
2139
2140 bool
2141 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2142                                   MachineFunction &MF, bool isVarArg,
2143                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2144                                   LLVMContext &Context) const {
2145   SmallVector<CCValAssign, 16> RVLocs;
2146   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2147   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2148                                                     isVarArg));
2149 }
2150
2151 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2152                                     SDLoc DL, SelectionDAG &DAG) {
2153   const MachineFunction &MF = DAG.getMachineFunction();
2154   const Function *F = MF.getFunction();
2155
2156   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2157
2158   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2159   // version of the "preferred return address". These offsets affect the return
2160   // instruction if this is a return from PL1 without hypervisor extensions.
2161   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2162   //    SWI:     0      "subs pc, lr, #0"
2163   //    ABORT:   +4     "subs pc, lr, #4"
2164   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2165   // UNDEF varies depending on where the exception came from ARM or Thumb
2166   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2167
2168   int64_t LROffset;
2169   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2170       IntKind == "ABORT")
2171     LROffset = 4;
2172   else if (IntKind == "SWI" || IntKind == "UNDEF")
2173     LROffset = 0;
2174   else
2175     report_fatal_error("Unsupported interrupt attribute. If present, value "
2176                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2177
2178   RetOps.insert(RetOps.begin() + 1,
2179                 DAG.getConstant(LROffset, DL, MVT::i32, false));
2180
2181   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2182 }
2183
2184 SDValue
2185 ARMTargetLowering::LowerReturn(SDValue Chain,
2186                                CallingConv::ID CallConv, bool isVarArg,
2187                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2188                                const SmallVectorImpl<SDValue> &OutVals,
2189                                SDLoc dl, SelectionDAG &DAG) const {
2190
2191   // CCValAssign - represent the assignment of the return value to a location.
2192   SmallVector<CCValAssign, 16> RVLocs;
2193
2194   // CCState - Info about the registers and stack slots.
2195   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2196                     *DAG.getContext(), Call);
2197
2198   // Analyze outgoing return values.
2199   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2200                                                isVarArg));
2201
2202   SDValue Flag;
2203   SmallVector<SDValue, 4> RetOps;
2204   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2205   bool isLittleEndian = Subtarget->isLittle();
2206
2207   MachineFunction &MF = DAG.getMachineFunction();
2208   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2209   AFI->setReturnRegsCount(RVLocs.size());
2210
2211   // Copy the result values into the output registers.
2212   for (unsigned i = 0, realRVLocIdx = 0;
2213        i != RVLocs.size();
2214        ++i, ++realRVLocIdx) {
2215     CCValAssign &VA = RVLocs[i];
2216     assert(VA.isRegLoc() && "Can only return in registers!");
2217
2218     SDValue Arg = OutVals[realRVLocIdx];
2219
2220     switch (VA.getLocInfo()) {
2221     default: llvm_unreachable("Unknown loc info!");
2222     case CCValAssign::Full: break;
2223     case CCValAssign::BCvt:
2224       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2225       break;
2226     }
2227
2228     if (VA.needsCustom()) {
2229       if (VA.getLocVT() == MVT::v2f64) {
2230         // Extract the first half and return it in two registers.
2231         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2232                                    DAG.getConstant(0, dl, MVT::i32));
2233         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2234                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2235
2236         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2237                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2238                                  Flag);
2239         Flag = Chain.getValue(1);
2240         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2241         VA = RVLocs[++i]; // skip ahead to next loc
2242         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2243                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2244                                  Flag);
2245         Flag = Chain.getValue(1);
2246         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2247         VA = RVLocs[++i]; // skip ahead to next loc
2248
2249         // Extract the 2nd half and fall through to handle it as an f64 value.
2250         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2251                           DAG.getConstant(1, dl, MVT::i32));
2252       }
2253       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2254       // available.
2255       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2256                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2257       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2258                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2259                                Flag);
2260       Flag = Chain.getValue(1);
2261       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2262       VA = RVLocs[++i]; // skip ahead to next loc
2263       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2264                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2265                                Flag);
2266     } else
2267       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2268
2269     // Guarantee that all emitted copies are
2270     // stuck together, avoiding something bad.
2271     Flag = Chain.getValue(1);
2272     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2273   }
2274
2275   // Update chain and glue.
2276   RetOps[0] = Chain;
2277   if (Flag.getNode())
2278     RetOps.push_back(Flag);
2279
2280   // CPUs which aren't M-class use a special sequence to return from
2281   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2282   // though we use "subs pc, lr, #N").
2283   //
2284   // M-class CPUs actually use a normal return sequence with a special
2285   // (hardware-provided) value in LR, so the normal code path works.
2286   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2287       !Subtarget->isMClass()) {
2288     if (Subtarget->isThumb1Only())
2289       report_fatal_error("interrupt attribute is not supported in Thumb1");
2290     return LowerInterruptReturn(RetOps, dl, DAG);
2291   }
2292
2293   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2294 }
2295
2296 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2297   if (N->getNumValues() != 1)
2298     return false;
2299   if (!N->hasNUsesOfValue(1, 0))
2300     return false;
2301
2302   SDValue TCChain = Chain;
2303   SDNode *Copy = *N->use_begin();
2304   if (Copy->getOpcode() == ISD::CopyToReg) {
2305     // If the copy has a glue operand, we conservatively assume it isn't safe to
2306     // perform a tail call.
2307     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2308       return false;
2309     TCChain = Copy->getOperand(0);
2310   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2311     SDNode *VMov = Copy;
2312     // f64 returned in a pair of GPRs.
2313     SmallPtrSet<SDNode*, 2> Copies;
2314     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2315          UI != UE; ++UI) {
2316       if (UI->getOpcode() != ISD::CopyToReg)
2317         return false;
2318       Copies.insert(*UI);
2319     }
2320     if (Copies.size() > 2)
2321       return false;
2322
2323     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2324          UI != UE; ++UI) {
2325       SDValue UseChain = UI->getOperand(0);
2326       if (Copies.count(UseChain.getNode()))
2327         // Second CopyToReg
2328         Copy = *UI;
2329       else {
2330         // We are at the top of this chain.
2331         // If the copy has a glue operand, we conservatively assume it
2332         // isn't safe to perform a tail call.
2333         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2334           return false;
2335         // First CopyToReg
2336         TCChain = UseChain;
2337       }
2338     }
2339   } else if (Copy->getOpcode() == ISD::BITCAST) {
2340     // f32 returned in a single GPR.
2341     if (!Copy->hasOneUse())
2342       return false;
2343     Copy = *Copy->use_begin();
2344     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2345       return false;
2346     // If the copy has a glue operand, we conservatively assume it isn't safe to
2347     // perform a tail call.
2348     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2349       return false;
2350     TCChain = Copy->getOperand(0);
2351   } else {
2352     return false;
2353   }
2354
2355   bool HasRet = false;
2356   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2357        UI != UE; ++UI) {
2358     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2359         UI->getOpcode() != ARMISD::INTRET_FLAG)
2360       return false;
2361     HasRet = true;
2362   }
2363
2364   if (!HasRet)
2365     return false;
2366
2367   Chain = TCChain;
2368   return true;
2369 }
2370
2371 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2372   if (!Subtarget->supportsTailCall())
2373     return false;
2374
2375   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2376     return false;
2377
2378   return !Subtarget->isThumb1Only();
2379 }
2380
2381 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2382 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2383 // one of the above mentioned nodes. It has to be wrapped because otherwise
2384 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2385 // be used to form addressing mode. These wrapped nodes will be selected
2386 // into MOVi.
2387 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2388   EVT PtrVT = Op.getValueType();
2389   // FIXME there is no actual debug info here
2390   SDLoc dl(Op);
2391   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2392   SDValue Res;
2393   if (CP->isMachineConstantPoolEntry())
2394     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2395                                     CP->getAlignment());
2396   else
2397     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2398                                     CP->getAlignment());
2399   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2400 }
2401
2402 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2403   return MachineJumpTableInfo::EK_Inline;
2404 }
2405
2406 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2407                                              SelectionDAG &DAG) const {
2408   MachineFunction &MF = DAG.getMachineFunction();
2409   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2410   unsigned ARMPCLabelIndex = 0;
2411   SDLoc DL(Op);
2412   EVT PtrVT = getPointerTy();
2413   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2414   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2415   SDValue CPAddr;
2416   if (RelocM == Reloc::Static) {
2417     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2418   } else {
2419     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2420     ARMPCLabelIndex = AFI->createPICLabelUId();
2421     ARMConstantPoolValue *CPV =
2422       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2423                                       ARMCP::CPBlockAddress, PCAdj);
2424     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2425   }
2426   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2427   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2428                                MachinePointerInfo::getConstantPool(),
2429                                false, false, false, 0);
2430   if (RelocM == Reloc::Static)
2431     return Result;
2432   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2433   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2434 }
2435
2436 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2437 SDValue
2438 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2439                                                  SelectionDAG &DAG) const {
2440   SDLoc dl(GA);
2441   EVT PtrVT = getPointerTy();
2442   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2443   MachineFunction &MF = DAG.getMachineFunction();
2444   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2445   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2446   ARMConstantPoolValue *CPV =
2447     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2448                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2449   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2450   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2451   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2452                          MachinePointerInfo::getConstantPool(),
2453                          false, false, false, 0);
2454   SDValue Chain = Argument.getValue(1);
2455
2456   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2457   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2458
2459   // call __tls_get_addr.
2460   ArgListTy Args;
2461   ArgListEntry Entry;
2462   Entry.Node = Argument;
2463   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2464   Args.push_back(Entry);
2465
2466   // FIXME: is there useful debug info available here?
2467   TargetLowering::CallLoweringInfo CLI(DAG);
2468   CLI.setDebugLoc(dl).setChain(Chain)
2469     .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2470                DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2471                0);
2472
2473   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2474   return CallResult.first;
2475 }
2476
2477 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2478 // "local exec" model.
2479 SDValue
2480 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2481                                         SelectionDAG &DAG,
2482                                         TLSModel::Model model) const {
2483   const GlobalValue *GV = GA->getGlobal();
2484   SDLoc dl(GA);
2485   SDValue Offset;
2486   SDValue Chain = DAG.getEntryNode();
2487   EVT PtrVT = getPointerTy();
2488   // Get the Thread Pointer
2489   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2490
2491   if (model == TLSModel::InitialExec) {
2492     MachineFunction &MF = DAG.getMachineFunction();
2493     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2494     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2495     // Initial exec model.
2496     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2497     ARMConstantPoolValue *CPV =
2498       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2499                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2500                                       true);
2501     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2502     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2503     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2504                          MachinePointerInfo::getConstantPool(),
2505                          false, false, false, 0);
2506     Chain = Offset.getValue(1);
2507
2508     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2509     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2510
2511     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2512                          MachinePointerInfo::getConstantPool(),
2513                          false, false, false, 0);
2514   } else {
2515     // local exec model
2516     assert(model == TLSModel::LocalExec);
2517     ARMConstantPoolValue *CPV =
2518       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2519     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2520     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2521     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2522                          MachinePointerInfo::getConstantPool(),
2523                          false, false, false, 0);
2524   }
2525
2526   // The address of the thread local variable is the add of the thread
2527   // pointer with the offset of the variable.
2528   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2529 }
2530
2531 SDValue
2532 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2533   // TODO: implement the "local dynamic" model
2534   assert(Subtarget->isTargetELF() &&
2535          "TLS not implemented for non-ELF targets");
2536   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2537
2538   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2539
2540   switch (model) {
2541     case TLSModel::GeneralDynamic:
2542     case TLSModel::LocalDynamic:
2543       return LowerToTLSGeneralDynamicModel(GA, DAG);
2544     case TLSModel::InitialExec:
2545     case TLSModel::LocalExec:
2546       return LowerToTLSExecModels(GA, DAG, model);
2547   }
2548   llvm_unreachable("bogus TLS model");
2549 }
2550
2551 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2552                                                  SelectionDAG &DAG) const {
2553   EVT PtrVT = getPointerTy();
2554   SDLoc dl(Op);
2555   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2556   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2557     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2558     ARMConstantPoolValue *CPV =
2559       ARMConstantPoolConstant::Create(GV,
2560                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2561     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2562     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2563     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2564                                  CPAddr,
2565                                  MachinePointerInfo::getConstantPool(),
2566                                  false, false, false, 0);
2567     SDValue Chain = Result.getValue(1);
2568     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2569     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2570     if (!UseGOTOFF)
2571       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2572                            MachinePointerInfo::getGOT(),
2573                            false, false, false, 0);
2574     return Result;
2575   }
2576
2577   // If we have T2 ops, we can materialize the address directly via movt/movw
2578   // pair. This is always cheaper.
2579   if (Subtarget->useMovt(DAG.getMachineFunction())) {
2580     ++NumMovwMovt;
2581     // FIXME: Once remat is capable of dealing with instructions with register
2582     // operands, expand this into two nodes.
2583     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2584                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2585   } else {
2586     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2587     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2588     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2589                        MachinePointerInfo::getConstantPool(),
2590                        false, false, false, 0);
2591   }
2592 }
2593
2594 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2595                                                     SelectionDAG &DAG) const {
2596   EVT PtrVT = getPointerTy();
2597   SDLoc dl(Op);
2598   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2599   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2600
2601   if (Subtarget->useMovt(DAG.getMachineFunction()))
2602     ++NumMovwMovt;
2603
2604   // FIXME: Once remat is capable of dealing with instructions with register
2605   // operands, expand this into multiple nodes
2606   unsigned Wrapper =
2607       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2608
2609   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2610   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2611
2612   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2613     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2614                          MachinePointerInfo::getGOT(), false, false, false, 0);
2615   return Result;
2616 }
2617
2618 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2619                                                      SelectionDAG &DAG) const {
2620   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2621   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2622          "Windows on ARM expects to use movw/movt");
2623
2624   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2625   const ARMII::TOF TargetFlags =
2626     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2627   EVT PtrVT = getPointerTy();
2628   SDValue Result;
2629   SDLoc DL(Op);
2630
2631   ++NumMovwMovt;
2632
2633   // FIXME: Once remat is capable of dealing with instructions with register
2634   // operands, expand this into two nodes.
2635   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2636                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2637                                                   TargetFlags));
2638   if (GV->hasDLLImportStorageClass())
2639     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2640                          MachinePointerInfo::getGOT(), false, false, false, 0);
2641   return Result;
2642 }
2643
2644 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2645                                                     SelectionDAG &DAG) const {
2646   assert(Subtarget->isTargetELF() &&
2647          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2648   MachineFunction &MF = DAG.getMachineFunction();
2649   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2650   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2651   EVT PtrVT = getPointerTy();
2652   SDLoc dl(Op);
2653   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2654   ARMConstantPoolValue *CPV =
2655     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2656                                   ARMPCLabelIndex, PCAdj);
2657   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2658   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2659   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2660                                MachinePointerInfo::getConstantPool(),
2661                                false, false, false, 0);
2662   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2663   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2664 }
2665
2666 SDValue
2667 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2668   SDLoc dl(Op);
2669   SDValue Val = DAG.getConstant(0, dl, MVT::i32);
2670   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2671                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2672                      Op.getOperand(1), Val);
2673 }
2674
2675 SDValue
2676 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2677   SDLoc dl(Op);
2678   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2679                      Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
2680 }
2681
2682 SDValue
2683 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2684                                           const ARMSubtarget *Subtarget) const {
2685   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2686   SDLoc dl(Op);
2687   switch (IntNo) {
2688   default: return SDValue();    // Don't custom lower most intrinsics.
2689   case Intrinsic::arm_rbit: {
2690     assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2691            "RBIT intrinsic must have i32 type!");
2692     return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1));
2693   }
2694   case Intrinsic::arm_thread_pointer: {
2695     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2696     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2697   }
2698   case Intrinsic::eh_sjlj_lsda: {
2699     MachineFunction &MF = DAG.getMachineFunction();
2700     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2701     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2702     EVT PtrVT = getPointerTy();
2703     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2704     SDValue CPAddr;
2705     unsigned PCAdj = (RelocM != Reloc::PIC_)
2706       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2707     ARMConstantPoolValue *CPV =
2708       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2709                                       ARMCP::CPLSDA, PCAdj);
2710     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2711     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2712     SDValue Result =
2713       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2714                   MachinePointerInfo::getConstantPool(),
2715                   false, false, false, 0);
2716
2717     if (RelocM == Reloc::PIC_) {
2718       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2719       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2720     }
2721     return Result;
2722   }
2723   case Intrinsic::arm_neon_vmulls:
2724   case Intrinsic::arm_neon_vmullu: {
2725     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2726       ? ARMISD::VMULLs : ARMISD::VMULLu;
2727     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2728                        Op.getOperand(1), Op.getOperand(2));
2729   }
2730   }
2731 }
2732
2733 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2734                                  const ARMSubtarget *Subtarget) {
2735   // FIXME: handle "fence singlethread" more efficiently.
2736   SDLoc dl(Op);
2737   if (!Subtarget->hasDataBarrier()) {
2738     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2739     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2740     // here.
2741     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2742            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2743     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2744                        DAG.getConstant(0, dl, MVT::i32));
2745   }
2746
2747   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2748   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2749   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
2750   if (Subtarget->isMClass()) {
2751     // Only a full system barrier exists in the M-class architectures.
2752     Domain = ARM_MB::SY;
2753   } else if (Subtarget->isSwift() && Ord == Release) {
2754     // Swift happens to implement ISHST barriers in a way that's compatible with
2755     // Release semantics but weaker than ISH so we'd be fools not to use
2756     // it. Beware: other processors probably don't!
2757     Domain = ARM_MB::ISHST;
2758   }
2759
2760   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2761                      DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
2762                      DAG.getConstant(Domain, dl, MVT::i32));
2763 }
2764
2765 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2766                              const ARMSubtarget *Subtarget) {
2767   // ARM pre v5TE and Thumb1 does not have preload instructions.
2768   if (!(Subtarget->isThumb2() ||
2769         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2770     // Just preserve the chain.
2771     return Op.getOperand(0);
2772
2773   SDLoc dl(Op);
2774   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2775   if (!isRead &&
2776       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2777     // ARMv7 with MP extension has PLDW.
2778     return Op.getOperand(0);
2779
2780   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2781   if (Subtarget->isThumb()) {
2782     // Invert the bits.
2783     isRead = ~isRead & 1;
2784     isData = ~isData & 1;
2785   }
2786
2787   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2788                      Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
2789                      DAG.getConstant(isData, dl, MVT::i32));
2790 }
2791
2792 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2793   MachineFunction &MF = DAG.getMachineFunction();
2794   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2795
2796   // vastart just stores the address of the VarArgsFrameIndex slot into the
2797   // memory location argument.
2798   SDLoc dl(Op);
2799   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2800   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2801   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2802   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2803                       MachinePointerInfo(SV), false, false, 0);
2804 }
2805
2806 SDValue
2807 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2808                                         SDValue &Root, SelectionDAG &DAG,
2809                                         SDLoc dl) const {
2810   MachineFunction &MF = DAG.getMachineFunction();
2811   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2812
2813   const TargetRegisterClass *RC;
2814   if (AFI->isThumb1OnlyFunction())
2815     RC = &ARM::tGPRRegClass;
2816   else
2817     RC = &ARM::GPRRegClass;
2818
2819   // Transform the arguments stored in physical registers into virtual ones.
2820   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2821   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2822
2823   SDValue ArgValue2;
2824   if (NextVA.isMemLoc()) {
2825     MachineFrameInfo *MFI = MF.getFrameInfo();
2826     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2827
2828     // Create load node to retrieve arguments from the stack.
2829     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2830     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2831                             MachinePointerInfo::getFixedStack(FI),
2832                             false, false, false, 0);
2833   } else {
2834     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2835     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2836   }
2837   if (!Subtarget->isLittle())
2838     std::swap (ArgValue, ArgValue2);
2839   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2840 }
2841
2842 // The remaining GPRs hold either the beginning of variable-argument
2843 // data, or the beginning of an aggregate passed by value (usually
2844 // byval).  Either way, we allocate stack slots adjacent to the data
2845 // provided by our caller, and store the unallocated registers there.
2846 // If this is a variadic function, the va_list pointer will begin with
2847 // these values; otherwise, this reassembles a (byval) structure that
2848 // was split between registers and memory.
2849 // Return: The frame index registers were stored into.
2850 int
2851 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2852                                   SDLoc dl, SDValue &Chain,
2853                                   const Value *OrigArg,
2854                                   unsigned InRegsParamRecordIdx,
2855                                   int ArgOffset,
2856                                   unsigned ArgSize) const {
2857   // Currently, two use-cases possible:
2858   // Case #1. Non-var-args function, and we meet first byval parameter.
2859   //          Setup first unallocated register as first byval register;
2860   //          eat all remained registers
2861   //          (these two actions are performed by HandleByVal method).
2862   //          Then, here, we initialize stack frame with
2863   //          "store-reg" instructions.
2864   // Case #2. Var-args function, that doesn't contain byval parameters.
2865   //          The same: eat all remained unallocated registers,
2866   //          initialize stack frame.
2867
2868   MachineFunction &MF = DAG.getMachineFunction();
2869   MachineFrameInfo *MFI = MF.getFrameInfo();
2870   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2871   unsigned RBegin, REnd;
2872   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2873     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2874   } else {
2875     unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
2876     RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
2877     REnd = ARM::R4;
2878   }
2879
2880   if (REnd != RBegin)
2881     ArgOffset = -4 * (ARM::R4 - RBegin);
2882
2883   int FrameIndex = MFI->CreateFixedObject(ArgSize, ArgOffset, false);
2884   SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2885
2886   SmallVector<SDValue, 4> MemOps;
2887   const TargetRegisterClass *RC =
2888       AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
2889
2890   for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
2891     unsigned VReg = MF.addLiveIn(Reg, RC);
2892     SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2893     SDValue Store =
2894         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2895                      MachinePointerInfo(OrigArg, 4 * i), false, false, 0);
2896     MemOps.push_back(Store);
2897     FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2898                       DAG.getConstant(4, dl, getPointerTy()));
2899   }
2900
2901   if (!MemOps.empty())
2902     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2903   return FrameIndex;
2904 }
2905
2906 // Setup stack frame, the va_list pointer will start from.
2907 void
2908 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2909                                         SDLoc dl, SDValue &Chain,
2910                                         unsigned ArgOffset,
2911                                         unsigned TotalArgRegsSaveSize,
2912                                         bool ForceMutable) const {
2913   MachineFunction &MF = DAG.getMachineFunction();
2914   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2915
2916   // Try to store any remaining integer argument regs
2917   // to their spots on the stack so that they may be loaded by deferencing
2918   // the result of va_next.
2919   // If there is no regs to be stored, just point address after last
2920   // argument passed via stack.
2921   int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
2922                                   CCInfo.getInRegsParamsCount(),
2923                                   CCInfo.getNextStackOffset(), 4);
2924   AFI->setVarArgsFrameIndex(FrameIndex);
2925 }
2926
2927 SDValue
2928 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2929                                         CallingConv::ID CallConv, bool isVarArg,
2930                                         const SmallVectorImpl<ISD::InputArg>
2931                                           &Ins,
2932                                         SDLoc dl, SelectionDAG &DAG,
2933                                         SmallVectorImpl<SDValue> &InVals)
2934                                           const {
2935   MachineFunction &MF = DAG.getMachineFunction();
2936   MachineFrameInfo *MFI = MF.getFrameInfo();
2937
2938   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2939
2940   // Assign locations to all of the incoming arguments.
2941   SmallVector<CCValAssign, 16> ArgLocs;
2942   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2943                     *DAG.getContext(), Prologue);
2944   CCInfo.AnalyzeFormalArguments(Ins,
2945                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2946                                                   isVarArg));
2947
2948   SmallVector<SDValue, 16> ArgValues;
2949   SDValue ArgValue;
2950   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2951   unsigned CurArgIdx = 0;
2952
2953   // Initially ArgRegsSaveSize is zero.
2954   // Then we increase this value each time we meet byval parameter.
2955   // We also increase this value in case of varargs function.
2956   AFI->setArgRegsSaveSize(0);
2957
2958   // Calculate the amount of stack space that we need to allocate to store
2959   // byval and variadic arguments that are passed in registers.
2960   // We need to know this before we allocate the first byval or variadic
2961   // argument, as they will be allocated a stack slot below the CFA (Canonical
2962   // Frame Address, the stack pointer at entry to the function).
2963   unsigned ArgRegBegin = ARM::R4;
2964   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2965     if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
2966       break;
2967
2968     CCValAssign &VA = ArgLocs[i];
2969     unsigned Index = VA.getValNo();
2970     ISD::ArgFlagsTy Flags = Ins[Index].Flags;
2971     if (!Flags.isByVal())
2972       continue;
2973
2974     assert(VA.isMemLoc() && "unexpected byval pointer in reg");
2975     unsigned RBegin, REnd;
2976     CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
2977     ArgRegBegin = std::min(ArgRegBegin, RBegin);
2978
2979     CCInfo.nextInRegsParam();
2980   }
2981   CCInfo.rewindByValRegsInfo();
2982
2983   int lastInsIndex = -1;
2984   if (isVarArg && MFI->hasVAStart()) {
2985     unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
2986     if (RegIdx != array_lengthof(GPRArgRegs))
2987       ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
2988   }
2989
2990   unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
2991   AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
2992
2993   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2994     CCValAssign &VA = ArgLocs[i];
2995     if (Ins[VA.getValNo()].isOrigArg()) {
2996       std::advance(CurOrigArg,
2997                    Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
2998       CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
2999     }
3000     // Arguments stored in registers.
3001     if (VA.isRegLoc()) {
3002       EVT RegVT = VA.getLocVT();
3003
3004       if (VA.needsCustom()) {
3005         // f64 and vector types are split up into multiple registers or
3006         // combinations of registers and stack slots.
3007         if (VA.getLocVT() == MVT::v2f64) {
3008           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3009                                                    Chain, DAG, dl);
3010           VA = ArgLocs[++i]; // skip ahead to next loc
3011           SDValue ArgValue2;
3012           if (VA.isMemLoc()) {
3013             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3014             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3015             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3016                                     MachinePointerInfo::getFixedStack(FI),
3017                                     false, false, false, 0);
3018           } else {
3019             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3020                                              Chain, DAG, dl);
3021           }
3022           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3023           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3024                                  ArgValue, ArgValue1,
3025                                  DAG.getIntPtrConstant(0, dl));
3026           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3027                                  ArgValue, ArgValue2,
3028                                  DAG.getIntPtrConstant(1, dl));
3029         } else
3030           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3031
3032       } else {
3033         const TargetRegisterClass *RC;
3034
3035         if (RegVT == MVT::f32)
3036           RC = &ARM::SPRRegClass;
3037         else if (RegVT == MVT::f64)
3038           RC = &ARM::DPRRegClass;
3039         else if (RegVT == MVT::v2f64)
3040           RC = &ARM::QPRRegClass;
3041         else if (RegVT == MVT::i32)
3042           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3043                                            : &ARM::GPRRegClass;
3044         else
3045           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3046
3047         // Transform the arguments in physical registers into virtual ones.
3048         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3049         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3050       }
3051
3052       // If this is an 8 or 16-bit value, it is really passed promoted
3053       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3054       // truncate to the right size.
3055       switch (VA.getLocInfo()) {
3056       default: llvm_unreachable("Unknown loc info!");
3057       case CCValAssign::Full: break;
3058       case CCValAssign::BCvt:
3059         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3060         break;
3061       case CCValAssign::SExt:
3062         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3063                                DAG.getValueType(VA.getValVT()));
3064         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3065         break;
3066       case CCValAssign::ZExt:
3067         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3068                                DAG.getValueType(VA.getValVT()));
3069         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3070         break;
3071       }
3072
3073       InVals.push_back(ArgValue);
3074
3075     } else { // VA.isRegLoc()
3076
3077       // sanity check
3078       assert(VA.isMemLoc());
3079       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3080
3081       int index = VA.getValNo();
3082
3083       // Some Ins[] entries become multiple ArgLoc[] entries.
3084       // Process them only once.
3085       if (index != lastInsIndex)
3086         {
3087           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3088           // FIXME: For now, all byval parameter objects are marked mutable.
3089           // This can be changed with more analysis.
3090           // In case of tail call optimization mark all arguments mutable.
3091           // Since they could be overwritten by lowering of arguments in case of
3092           // a tail call.
3093           if (Flags.isByVal()) {
3094             assert(Ins[index].isOrigArg() &&
3095                    "Byval arguments cannot be implicit");
3096             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3097
3098             int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, CurOrigArg,
3099                                             CurByValIndex, VA.getLocMemOffset(),
3100                                             Flags.getByValSize());
3101             InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3102             CCInfo.nextInRegsParam();
3103           } else {
3104             unsigned FIOffset = VA.getLocMemOffset();
3105             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3106                                             FIOffset, true);
3107
3108             // Create load nodes to retrieve arguments from the stack.
3109             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3110             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3111                                          MachinePointerInfo::getFixedStack(FI),
3112                                          false, false, false, 0));
3113           }
3114           lastInsIndex = index;
3115         }
3116     }
3117   }
3118
3119   // varargs
3120   if (isVarArg && MFI->hasVAStart())
3121     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3122                          CCInfo.getNextStackOffset(),
3123                          TotalArgRegsSaveSize);
3124
3125   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3126
3127   return Chain;
3128 }
3129
3130 /// isFloatingPointZero - Return true if this is +0.0.
3131 static bool isFloatingPointZero(SDValue Op) {
3132   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3133     return CFP->getValueAPF().isPosZero();
3134   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3135     // Maybe this has already been legalized into the constant pool?
3136     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3137       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3138       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3139         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3140           return CFP->getValueAPF().isPosZero();
3141     }
3142   } else if (Op->getOpcode() == ISD::BITCAST &&
3143              Op->getValueType(0) == MVT::f64) {
3144     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3145     // created by LowerConstantFP().
3146     SDValue BitcastOp = Op->getOperand(0);
3147     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM) {
3148       SDValue MoveOp = BitcastOp->getOperand(0);
3149       if (MoveOp->getOpcode() == ISD::TargetConstant &&
3150           cast<ConstantSDNode>(MoveOp)->getZExtValue() == 0) {
3151         return true;
3152       }
3153     }
3154   }
3155   return false;
3156 }
3157
3158 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3159 /// the given operands.
3160 SDValue
3161 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3162                              SDValue &ARMcc, SelectionDAG &DAG,
3163                              SDLoc dl) const {
3164   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3165     unsigned C = RHSC->getZExtValue();
3166     if (!isLegalICmpImmediate(C)) {
3167       // Constant does not fit, try adjusting it by one?
3168       switch (CC) {
3169       default: break;
3170       case ISD::SETLT:
3171       case ISD::SETGE:
3172         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3173           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3174           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3175         }
3176         break;
3177       case ISD::SETULT:
3178       case ISD::SETUGE:
3179         if (C != 0 && isLegalICmpImmediate(C-1)) {
3180           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3181           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3182         }
3183         break;
3184       case ISD::SETLE:
3185       case ISD::SETGT:
3186         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3187           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3188           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3189         }
3190         break;
3191       case ISD::SETULE:
3192       case ISD::SETUGT:
3193         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3194           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3195           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3196         }
3197         break;
3198       }
3199     }
3200   }
3201
3202   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3203   ARMISD::NodeType CompareType;
3204   switch (CondCode) {
3205   default:
3206     CompareType = ARMISD::CMP;
3207     break;
3208   case ARMCC::EQ:
3209   case ARMCC::NE:
3210     // Uses only Z Flag
3211     CompareType = ARMISD::CMPZ;
3212     break;
3213   }
3214   ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3215   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3216 }
3217
3218 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3219 SDValue
3220 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3221                              SDLoc dl) const {
3222   assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3223   SDValue Cmp;
3224   if (!isFloatingPointZero(RHS))
3225     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3226   else
3227     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3228   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3229 }
3230
3231 /// duplicateCmp - Glue values can have only one use, so this function
3232 /// duplicates a comparison node.
3233 SDValue
3234 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3235   unsigned Opc = Cmp.getOpcode();
3236   SDLoc DL(Cmp);
3237   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3238     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3239
3240   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3241   Cmp = Cmp.getOperand(0);
3242   Opc = Cmp.getOpcode();
3243   if (Opc == ARMISD::CMPFP)
3244     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3245   else {
3246     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3247     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3248   }
3249   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3250 }
3251
3252 std::pair<SDValue, SDValue>
3253 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3254                                  SDValue &ARMcc) const {
3255   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3256
3257   SDValue Value, OverflowCmp;
3258   SDValue LHS = Op.getOperand(0);
3259   SDValue RHS = Op.getOperand(1);
3260   SDLoc dl(Op);
3261
3262   // FIXME: We are currently always generating CMPs because we don't support
3263   // generating CMN through the backend. This is not as good as the natural
3264   // CMP case because it causes a register dependency and cannot be folded
3265   // later.
3266
3267   switch (Op.getOpcode()) {
3268   default:
3269     llvm_unreachable("Unknown overflow instruction!");
3270   case ISD::SADDO:
3271     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3272     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3273     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3274     break;
3275   case ISD::UADDO:
3276     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3277     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3278     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3279     break;
3280   case ISD::SSUBO:
3281     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3282     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3283     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3284     break;
3285   case ISD::USUBO:
3286     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3287     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3288     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3289     break;
3290   } // switch (...)
3291
3292   return std::make_pair(Value, OverflowCmp);
3293 }
3294
3295
3296 SDValue
3297 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3298   // Let legalize expand this if it isn't a legal type yet.
3299   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3300     return SDValue();
3301
3302   SDValue Value, OverflowCmp;
3303   SDValue ARMcc;
3304   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3305   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3306   SDLoc dl(Op);
3307   // We use 0 and 1 as false and true values.
3308   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3309   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3310   EVT VT = Op.getValueType();
3311
3312   SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
3313                                  ARMcc, CCR, OverflowCmp);
3314
3315   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3316   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
3317 }
3318
3319
3320 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3321   SDValue Cond = Op.getOperand(0);
3322   SDValue SelectTrue = Op.getOperand(1);
3323   SDValue SelectFalse = Op.getOperand(2);
3324   SDLoc dl(Op);
3325   unsigned Opc = Cond.getOpcode();
3326
3327   if (Cond.getResNo() == 1 &&
3328       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3329        Opc == ISD::USUBO)) {
3330     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3331       return SDValue();
3332
3333     SDValue Value, OverflowCmp;
3334     SDValue ARMcc;
3335     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3336     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3337     EVT VT = Op.getValueType();
3338
3339     return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
3340                    OverflowCmp, DAG);
3341   }
3342
3343   // Convert:
3344   //
3345   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3346   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3347   //
3348   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3349     const ConstantSDNode *CMOVTrue =
3350       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3351     const ConstantSDNode *CMOVFalse =
3352       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3353
3354     if (CMOVTrue && CMOVFalse) {
3355       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3356       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3357
3358       SDValue True;
3359       SDValue False;
3360       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3361         True = SelectTrue;
3362         False = SelectFalse;
3363       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3364         True = SelectFalse;
3365         False = SelectTrue;
3366       }
3367
3368       if (True.getNode() && False.getNode()) {
3369         EVT VT = Op.getValueType();
3370         SDValue ARMcc = Cond.getOperand(2);
3371         SDValue CCR = Cond.getOperand(3);
3372         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3373         assert(True.getValueType() == VT);
3374         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3375       }
3376     }
3377   }
3378
3379   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3380   // undefined bits before doing a full-word comparison with zero.
3381   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3382                      DAG.getConstant(1, dl, Cond.getValueType()));
3383
3384   return DAG.getSelectCC(dl, Cond,
3385                          DAG.getConstant(0, dl, Cond.getValueType()),
3386                          SelectTrue, SelectFalse, ISD::SETNE);
3387 }
3388
3389 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3390                                  bool &swpCmpOps, bool &swpVselOps) {
3391   // Start by selecting the GE condition code for opcodes that return true for
3392   // 'equality'
3393   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3394       CC == ISD::SETULE)
3395     CondCode = ARMCC::GE;
3396
3397   // and GT for opcodes that return false for 'equality'.
3398   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3399            CC == ISD::SETULT)
3400     CondCode = ARMCC::GT;
3401
3402   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3403   // to swap the compare operands.
3404   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3405       CC == ISD::SETULT)
3406     swpCmpOps = true;
3407
3408   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3409   // If we have an unordered opcode, we need to swap the operands to the VSEL
3410   // instruction (effectively negating the condition).
3411   //
3412   // This also has the effect of swapping which one of 'less' or 'greater'
3413   // returns true, so we also swap the compare operands. It also switches
3414   // whether we return true for 'equality', so we compensate by picking the
3415   // opposite condition code to our original choice.
3416   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3417       CC == ISD::SETUGT) {
3418     swpCmpOps = !swpCmpOps;
3419     swpVselOps = !swpVselOps;
3420     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3421   }
3422
3423   // 'ordered' is 'anything but unordered', so use the VS condition code and
3424   // swap the VSEL operands.
3425   if (CC == ISD::SETO) {
3426     CondCode = ARMCC::VS;
3427     swpVselOps = true;
3428   }
3429
3430   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3431   // code and swap the VSEL operands.
3432   if (CC == ISD::SETUNE) {
3433     CondCode = ARMCC::EQ;
3434     swpVselOps = true;
3435   }
3436 }
3437
3438 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3439                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3440                                    SDValue Cmp, SelectionDAG &DAG) const {
3441   if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3442     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3443                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3444     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3445                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3446
3447     SDValue TrueLow = TrueVal.getValue(0);
3448     SDValue TrueHigh = TrueVal.getValue(1);
3449     SDValue FalseLow = FalseVal.getValue(0);
3450     SDValue FalseHigh = FalseVal.getValue(1);
3451
3452     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3453                               ARMcc, CCR, Cmp);
3454     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3455                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
3456
3457     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3458   } else {
3459     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3460                        Cmp);
3461   }
3462 }
3463
3464 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3465   EVT VT = Op.getValueType();
3466   SDValue LHS = Op.getOperand(0);
3467   SDValue RHS = Op.getOperand(1);
3468   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3469   SDValue TrueVal = Op.getOperand(2);
3470   SDValue FalseVal = Op.getOperand(3);
3471   SDLoc dl(Op);
3472
3473   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3474     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3475                                                     dl);
3476
3477     // If softenSetCCOperands only returned one value, we should compare it to
3478     // zero.
3479     if (!RHS.getNode()) {
3480       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3481       CC = ISD::SETNE;
3482     }
3483   }
3484
3485   if (LHS.getValueType() == MVT::i32) {
3486     // Try to generate VSEL on ARMv8.
3487     // The VSEL instruction can't use all the usual ARM condition
3488     // codes: it only has two bits to select the condition code, so it's
3489     // constrained to use only GE, GT, VS and EQ.
3490     //
3491     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3492     // swap the operands of the previous compare instruction (effectively
3493     // inverting the compare condition, swapping 'less' and 'greater') and
3494     // sometimes need to swap the operands to the VSEL (which inverts the
3495     // condition in the sense of firing whenever the previous condition didn't)
3496     if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3497                                     TrueVal.getValueType() == MVT::f64)) {
3498       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3499       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3500           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3501         CC = ISD::getSetCCInverse(CC, true);
3502         std::swap(TrueVal, FalseVal);
3503       }
3504     }
3505
3506     SDValue ARMcc;
3507     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3508     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3509     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3510   }
3511
3512   ARMCC::CondCodes CondCode, CondCode2;
3513   FPCCToARMCC(CC, CondCode, CondCode2);
3514
3515   // Try to generate VMAXNM/VMINNM on ARMv8.
3516   if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3517                                   TrueVal.getValueType() == MVT::f64)) {
3518     // We can use VMAXNM/VMINNM for a compare followed by a select with the
3519     // same operands, as follows:
3520     //   c = fcmp [?gt, ?ge, ?lt, ?le] a, b
3521     //   select c, a, b
3522     // In NoNaNsFPMath the CC will have been changed from, e.g., 'ogt' to 'gt'.
3523     bool swapSides = false;
3524     if (!getTargetMachine().Options.NoNaNsFPMath) {
3525       // transformability may depend on which way around we compare
3526       switch (CC) {
3527       default:
3528         break;
3529       case ISD::SETOGT:
3530       case ISD::SETOGE:
3531       case ISD::SETOLT:
3532       case ISD::SETOLE:
3533         // the non-NaN should be RHS
3534         swapSides = DAG.isKnownNeverNaN(LHS) && !DAG.isKnownNeverNaN(RHS);
3535         break;
3536       case ISD::SETUGT:
3537       case ISD::SETUGE:
3538       case ISD::SETULT:
3539       case ISD::SETULE:
3540         // the non-NaN should be LHS
3541         swapSides = DAG.isKnownNeverNaN(RHS) && !DAG.isKnownNeverNaN(LHS);
3542         break;
3543       }
3544     }
3545     swapSides = swapSides || (LHS == FalseVal && RHS == TrueVal);
3546     if (swapSides) {
3547       CC = ISD::getSetCCSwappedOperands(CC);
3548       std::swap(LHS, RHS);
3549     }
3550     if (LHS == TrueVal && RHS == FalseVal) {
3551       bool canTransform = true;
3552       // FIXME: FastMathFlags::noSignedZeros() doesn't appear reachable from here
3553       if (!getTargetMachine().Options.UnsafeFPMath &&
3554           !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
3555         const ConstantFPSDNode *Zero;
3556         switch (CC) {
3557         default:
3558           break;
3559         case ISD::SETOGT:
3560         case ISD::SETUGT:
3561         case ISD::SETGT:
3562           // RHS must not be -0
3563           canTransform = (Zero = dyn_cast<ConstantFPSDNode>(RHS)) &&
3564                          !Zero->isNegative();
3565           break;
3566         case ISD::SETOGE:
3567         case ISD::SETUGE:
3568         case ISD::SETGE:
3569           // LHS must not be -0
3570           canTransform = (Zero = dyn_cast<ConstantFPSDNode>(LHS)) &&
3571                          !Zero->isNegative();
3572           break;
3573         case ISD::SETOLT:
3574         case ISD::SETULT:
3575         case ISD::SETLT:
3576           // RHS must not be +0
3577           canTransform = (Zero = dyn_cast<ConstantFPSDNode>(RHS)) &&
3578                           Zero->isNegative();
3579           break;
3580         case ISD::SETOLE:
3581         case ISD::SETULE:
3582         case ISD::SETLE:
3583           // LHS must not be +0
3584           canTransform = (Zero = dyn_cast<ConstantFPSDNode>(LHS)) &&
3585                           Zero->isNegative();
3586           break;
3587         }
3588       }
3589       if (canTransform) {
3590         // Note: If one of the elements in a pair is a number and the other
3591         // element is NaN, the corresponding result element is the number.
3592         // This is consistent with the IEEE 754-2008 standard.
3593         // Therefore, a > b ? a : b <=> vmax(a,b), if b is constant and a is NaN
3594         switch (CC) {
3595         default:
3596           break;
3597         case ISD::SETOGT:
3598         case ISD::SETOGE:
3599           if (!DAG.isKnownNeverNaN(RHS))
3600             break;
3601           return DAG.getNode(ARMISD::VMAXNM, dl, VT, LHS, RHS);
3602         case ISD::SETUGT:
3603         case ISD::SETUGE:
3604           if (!DAG.isKnownNeverNaN(LHS))
3605             break;
3606         case ISD::SETGT:
3607         case ISD::SETGE:
3608           return DAG.getNode(ARMISD::VMAXNM, dl, VT, LHS, RHS);
3609         case ISD::SETOLT:
3610         case ISD::SETOLE:
3611           if (!DAG.isKnownNeverNaN(RHS))
3612             break;
3613           return DAG.getNode(ARMISD::VMINNM, dl, VT, LHS, RHS);
3614         case ISD::SETULT:
3615         case ISD::SETULE:
3616           if (!DAG.isKnownNeverNaN(LHS))
3617             break;
3618         case ISD::SETLT:
3619         case ISD::SETLE:
3620           return DAG.getNode(ARMISD::VMINNM, dl, VT, LHS, RHS);
3621         }
3622       }
3623     }
3624
3625     bool swpCmpOps = false;
3626     bool swpVselOps = false;
3627     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3628
3629     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3630         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3631       if (swpCmpOps)
3632         std::swap(LHS, RHS);
3633       if (swpVselOps)
3634         std::swap(TrueVal, FalseVal);
3635     }
3636   }
3637
3638   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3639   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3640   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3641   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3642   if (CondCode2 != ARMCC::AL) {
3643     SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
3644     // FIXME: Needs another CMP because flag can have but one use.
3645     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3646     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3647   }
3648   return Result;
3649 }
3650
3651 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3652 /// to morph to an integer compare sequence.
3653 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3654                            const ARMSubtarget *Subtarget) {
3655   SDNode *N = Op.getNode();
3656   if (!N->hasOneUse())
3657     // Otherwise it requires moving the value from fp to integer registers.
3658     return false;
3659   if (!N->getNumValues())
3660     return false;
3661   EVT VT = Op.getValueType();
3662   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3663     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3664     // vmrs are very slow, e.g. cortex-a8.
3665     return false;
3666
3667   if (isFloatingPointZero(Op)) {
3668     SeenZero = true;
3669     return true;
3670   }
3671   return ISD::isNormalLoad(N);
3672 }
3673
3674 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3675   if (isFloatingPointZero(Op))
3676     return DAG.getConstant(0, SDLoc(Op), MVT::i32);
3677
3678   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3679     return DAG.getLoad(MVT::i32, SDLoc(Op),
3680                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3681                        Ld->isVolatile(), Ld->isNonTemporal(),
3682                        Ld->isInvariant(), Ld->getAlignment());
3683
3684   llvm_unreachable("Unknown VFP cmp argument!");
3685 }
3686
3687 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3688                            SDValue &RetVal1, SDValue &RetVal2) {
3689   SDLoc dl(Op);
3690
3691   if (isFloatingPointZero(Op)) {
3692     RetVal1 = DAG.getConstant(0, dl, MVT::i32);
3693     RetVal2 = DAG.getConstant(0, dl, MVT::i32);
3694     return;
3695   }
3696
3697   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3698     SDValue Ptr = Ld->getBasePtr();
3699     RetVal1 = DAG.getLoad(MVT::i32, dl,
3700                           Ld->getChain(), Ptr,
3701                           Ld->getPointerInfo(),
3702                           Ld->isVolatile(), Ld->isNonTemporal(),
3703                           Ld->isInvariant(), Ld->getAlignment());
3704
3705     EVT PtrType = Ptr.getValueType();
3706     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3707     SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
3708                                  PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
3709     RetVal2 = DAG.getLoad(MVT::i32, dl,
3710                           Ld->getChain(), NewPtr,
3711                           Ld->getPointerInfo().getWithOffset(4),
3712                           Ld->isVolatile(), Ld->isNonTemporal(),
3713                           Ld->isInvariant(), NewAlign);
3714     return;
3715   }
3716
3717   llvm_unreachable("Unknown VFP cmp argument!");
3718 }
3719
3720 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3721 /// f32 and even f64 comparisons to integer ones.
3722 SDValue
3723 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3724   SDValue Chain = Op.getOperand(0);
3725   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3726   SDValue LHS = Op.getOperand(2);
3727   SDValue RHS = Op.getOperand(3);
3728   SDValue Dest = Op.getOperand(4);
3729   SDLoc dl(Op);
3730
3731   bool LHSSeenZero = false;
3732   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3733   bool RHSSeenZero = false;
3734   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3735   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3736     // If unsafe fp math optimization is enabled and there are no other uses of
3737     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3738     // to an integer comparison.
3739     if (CC == ISD::SETOEQ)
3740       CC = ISD::SETEQ;
3741     else if (CC == ISD::SETUNE)
3742       CC = ISD::SETNE;
3743
3744     SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
3745     SDValue ARMcc;
3746     if (LHS.getValueType() == MVT::f32) {
3747       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3748                         bitcastf32Toi32(LHS, DAG), Mask);
3749       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3750                         bitcastf32Toi32(RHS, DAG), Mask);
3751       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3752       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3753       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3754                          Chain, Dest, ARMcc, CCR, Cmp);
3755     }
3756
3757     SDValue LHS1, LHS2;
3758     SDValue RHS1, RHS2;
3759     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3760     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3761     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3762     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3763     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3764     ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3765     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3766     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3767     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3768   }
3769
3770   return SDValue();
3771 }
3772
3773 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3774   SDValue Chain = Op.getOperand(0);
3775   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3776   SDValue LHS = Op.getOperand(2);
3777   SDValue RHS = Op.getOperand(3);
3778   SDValue Dest = Op.getOperand(4);
3779   SDLoc dl(Op);
3780
3781   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3782     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3783                                                     dl);
3784
3785     // If softenSetCCOperands only returned one value, we should compare it to
3786     // zero.
3787     if (!RHS.getNode()) {
3788       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3789       CC = ISD::SETNE;
3790     }
3791   }
3792
3793   if (LHS.getValueType() == MVT::i32) {
3794     SDValue ARMcc;
3795     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3796     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3797     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3798                        Chain, Dest, ARMcc, CCR, Cmp);
3799   }
3800
3801   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3802
3803   if (getTargetMachine().Options.UnsafeFPMath &&
3804       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3805        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3806     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3807     if (Result.getNode())
3808       return Result;
3809   }
3810
3811   ARMCC::CondCodes CondCode, CondCode2;
3812   FPCCToARMCC(CC, CondCode, CondCode2);
3813
3814   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3815   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3816   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3817   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3818   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3819   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3820   if (CondCode2 != ARMCC::AL) {
3821     ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
3822     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3823     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3824   }
3825   return Res;
3826 }
3827
3828 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3829   SDValue Chain = Op.getOperand(0);
3830   SDValue Table = Op.getOperand(1);
3831   SDValue Index = Op.getOperand(2);
3832   SDLoc dl(Op);
3833
3834   EVT PTy = getPointerTy();
3835   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3836   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3837   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
3838   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
3839   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3840   if (Subtarget->isThumb2()) {
3841     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3842     // which does another jump to the destination. This also makes it easier
3843     // to translate it to TBB / TBH later.
3844     // FIXME: This might not work if the function is extremely large.
3845     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3846                        Addr, Op.getOperand(2), JTI);
3847   }
3848   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3849     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3850                        MachinePointerInfo::getJumpTable(),
3851                        false, false, false, 0);
3852     Chain = Addr.getValue(1);
3853     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3854     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3855   } else {
3856     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3857                        MachinePointerInfo::getJumpTable(),
3858                        false, false, false, 0);
3859     Chain = Addr.getValue(1);
3860     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3861   }
3862 }
3863
3864 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3865   EVT VT = Op.getValueType();
3866   SDLoc dl(Op);
3867
3868   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3869     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3870       return Op;
3871     return DAG.UnrollVectorOp(Op.getNode());
3872   }
3873
3874   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3875          "Invalid type for custom lowering!");
3876   if (VT != MVT::v4i16)
3877     return DAG.UnrollVectorOp(Op.getNode());
3878
3879   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3880   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3881 }
3882
3883 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3884   EVT VT = Op.getValueType();
3885   if (VT.isVector())
3886     return LowerVectorFP_TO_INT(Op, DAG);
3887   if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3888     RTLIB::Libcall LC;
3889     if (Op.getOpcode() == ISD::FP_TO_SINT)
3890       LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
3891                               Op.getValueType());
3892     else
3893       LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
3894                               Op.getValueType());
3895     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3896                        /*isSigned*/ false, SDLoc(Op)).first;
3897   }
3898
3899   return Op;
3900 }
3901
3902 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3903   EVT VT = Op.getValueType();
3904   SDLoc dl(Op);
3905
3906   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3907     if (VT.getVectorElementType() == MVT::f32)
3908       return Op;
3909     return DAG.UnrollVectorOp(Op.getNode());
3910   }
3911
3912   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3913          "Invalid type for custom lowering!");
3914   if (VT != MVT::v4f32)
3915     return DAG.UnrollVectorOp(Op.getNode());
3916
3917   unsigned CastOpc;
3918   unsigned Opc;
3919   switch (Op.getOpcode()) {
3920   default: llvm_unreachable("Invalid opcode!");
3921   case ISD::SINT_TO_FP:
3922     CastOpc = ISD::SIGN_EXTEND;
3923     Opc = ISD::SINT_TO_FP;
3924     break;
3925   case ISD::UINT_TO_FP:
3926     CastOpc = ISD::ZERO_EXTEND;
3927     Opc = ISD::UINT_TO_FP;
3928     break;
3929   }
3930
3931   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3932   return DAG.getNode(Opc, dl, VT, Op);
3933 }
3934
3935 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
3936   EVT VT = Op.getValueType();
3937   if (VT.isVector())
3938     return LowerVectorINT_TO_FP(Op, DAG);
3939   if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
3940     RTLIB::Libcall LC;
3941     if (Op.getOpcode() == ISD::SINT_TO_FP)
3942       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
3943                               Op.getValueType());
3944     else
3945       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
3946                               Op.getValueType());
3947     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3948                        /*isSigned*/ false, SDLoc(Op)).first;
3949   }
3950
3951   return Op;
3952 }
3953
3954 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3955   // Implement fcopysign with a fabs and a conditional fneg.
3956   SDValue Tmp0 = Op.getOperand(0);
3957   SDValue Tmp1 = Op.getOperand(1);
3958   SDLoc dl(Op);
3959   EVT VT = Op.getValueType();
3960   EVT SrcVT = Tmp1.getValueType();
3961   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3962     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3963   bool UseNEON = !InGPR && Subtarget->hasNEON();
3964
3965   if (UseNEON) {
3966     // Use VBSL to copy the sign bit.
3967     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3968     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3969                                DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
3970     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3971     if (VT == MVT::f64)
3972       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3973                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3974                          DAG.getConstant(32, dl, MVT::i32));
3975     else /*if (VT == MVT::f32)*/
3976       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3977     if (SrcVT == MVT::f32) {
3978       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3979       if (VT == MVT::f64)
3980         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3981                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3982                            DAG.getConstant(32, dl, MVT::i32));
3983     } else if (VT == MVT::f32)
3984       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3985                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3986                          DAG.getConstant(32, dl, MVT::i32));
3987     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3988     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3989
3990     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3991                                             dl, MVT::i32);
3992     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3993     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3994                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3995
3996     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3997                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3998                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3999     if (VT == MVT::f32) {
4000       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4001       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4002                         DAG.getConstant(0, dl, MVT::i32));
4003     } else {
4004       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4005     }
4006
4007     return Res;
4008   }
4009
4010   // Bitcast operand 1 to i32.
4011   if (SrcVT == MVT::f64)
4012     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4013                        Tmp1).getValue(1);
4014   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4015
4016   // Or in the signbit with integer operations.
4017   SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
4018   SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4019   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4020   if (VT == MVT::f32) {
4021     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4022                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4023     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4024                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4025   }
4026
4027   // f64: Or the high part with signbit and then combine two parts.
4028   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4029                      Tmp0);
4030   SDValue Lo = Tmp0.getValue(0);
4031   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4032   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4033   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4034 }
4035
4036 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4037   MachineFunction &MF = DAG.getMachineFunction();
4038   MachineFrameInfo *MFI = MF.getFrameInfo();
4039   MFI->setReturnAddressIsTaken(true);
4040
4041   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4042     return SDValue();
4043
4044   EVT VT = Op.getValueType();
4045   SDLoc dl(Op);
4046   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4047   if (Depth) {
4048     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4049     SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
4050     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4051                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4052                        MachinePointerInfo(), false, false, false, 0);
4053   }
4054
4055   // Return LR, which contains the return address. Mark it an implicit live-in.
4056   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4057   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4058 }
4059
4060 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4061   const ARMBaseRegisterInfo &ARI =
4062     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4063   MachineFunction &MF = DAG.getMachineFunction();
4064   MachineFrameInfo *MFI = MF.getFrameInfo();
4065   MFI->setFrameAddressIsTaken(true);
4066
4067   EVT VT = Op.getValueType();
4068   SDLoc dl(Op);  // FIXME probably not meaningful
4069   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4070   unsigned FrameReg = ARI.getFrameRegister(MF);
4071   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4072   while (Depth--)
4073     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4074                             MachinePointerInfo(),
4075                             false, false, false, 0);
4076   return FrameAddr;
4077 }
4078
4079 // FIXME? Maybe this could be a TableGen attribute on some registers and
4080 // this table could be generated automatically from RegInfo.
4081 unsigned ARMTargetLowering::getRegisterByName(const char* RegName,
4082                                               EVT VT) const {
4083   unsigned Reg = StringSwitch<unsigned>(RegName)
4084                        .Case("sp", ARM::SP)
4085                        .Default(0);
4086   if (Reg)
4087     return Reg;
4088   report_fatal_error("Invalid register name global variable");
4089 }
4090
4091 /// ExpandBITCAST - If the target supports VFP, this function is called to
4092 /// expand a bit convert where either the source or destination type is i64 to
4093 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
4094 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4095 /// vectors), since the legalizer won't know what to do with that.
4096 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4097   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4098   SDLoc dl(N);
4099   SDValue Op = N->getOperand(0);
4100
4101   // This function is only supposed to be called for i64 types, either as the
4102   // source or destination of the bit convert.
4103   EVT SrcVT = Op.getValueType();
4104   EVT DstVT = N->getValueType(0);
4105   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4106          "ExpandBITCAST called for non-i64 type");
4107
4108   // Turn i64->f64 into VMOVDRR.
4109   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4110     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4111                              DAG.getConstant(0, dl, MVT::i32));
4112     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4113                              DAG.getConstant(1, dl, MVT::i32));
4114     return DAG.getNode(ISD::BITCAST, dl, DstVT,
4115                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4116   }
4117
4118   // Turn f64->i64 into VMOVRRD.
4119   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4120     SDValue Cvt;
4121     if (TLI.isBigEndian() && SrcVT.isVector() &&
4122         SrcVT.getVectorNumElements() > 1)
4123       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4124                         DAG.getVTList(MVT::i32, MVT::i32),
4125                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4126     else
4127       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4128                         DAG.getVTList(MVT::i32, MVT::i32), Op);
4129     // Merge the pieces into a single i64 value.
4130     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4131   }
4132
4133   return SDValue();
4134 }
4135
4136 /// getZeroVector - Returns a vector of specified type with all zero elements.
4137 /// Zero vectors are used to represent vector negation and in those cases
4138 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
4139 /// not support i64 elements, so sometimes the zero vectors will need to be
4140 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
4141 /// zero vector.
4142 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4143   assert(VT.isVector() && "Expected a vector type");
4144   // The canonical modified immediate encoding of a zero vector is....0!
4145   SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
4146   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4147   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4148   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4149 }
4150
4151 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4152 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4153 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4154                                                 SelectionDAG &DAG) const {
4155   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4156   EVT VT = Op.getValueType();
4157   unsigned VTBits = VT.getSizeInBits();
4158   SDLoc dl(Op);
4159   SDValue ShOpLo = Op.getOperand(0);
4160   SDValue ShOpHi = Op.getOperand(1);
4161   SDValue ShAmt  = Op.getOperand(2);
4162   SDValue ARMcc;
4163   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4164
4165   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4166
4167   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4168                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4169   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4170   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4171                                    DAG.getConstant(VTBits, dl, MVT::i32));
4172   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4173   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4174   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4175
4176   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4177   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4178                           ISD::SETGE, ARMcc, DAG, dl);
4179   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4180   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4181                            CCR, Cmp);
4182
4183   SDValue Ops[2] = { Lo, Hi };
4184   return DAG.getMergeValues(Ops, dl);
4185 }
4186
4187 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4188 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4189 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4190                                                SelectionDAG &DAG) const {
4191   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4192   EVT VT = Op.getValueType();
4193   unsigned VTBits = VT.getSizeInBits();
4194   SDLoc dl(Op);
4195   SDValue ShOpLo = Op.getOperand(0);
4196   SDValue ShOpHi = Op.getOperand(1);
4197   SDValue ShAmt  = Op.getOperand(2);
4198   SDValue ARMcc;
4199
4200   assert(Op.getOpcode() == ISD::SHL_PARTS);
4201   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4202                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4203   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4204   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4205                                    DAG.getConstant(VTBits, dl, MVT::i32));
4206   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4207   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4208
4209   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4210   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4211   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4212                           ISD::SETGE, ARMcc, DAG, dl);
4213   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4214   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4215                            CCR, Cmp);
4216
4217   SDValue Ops[2] = { Lo, Hi };
4218   return DAG.getMergeValues(Ops, dl);
4219 }
4220
4221 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4222                                             SelectionDAG &DAG) const {
4223   // The rounding mode is in bits 23:22 of the FPSCR.
4224   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4225   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4226   // so that the shift + and get folded into a bitfield extract.
4227   SDLoc dl(Op);
4228   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4229                               DAG.getConstant(Intrinsic::arm_get_fpscr, dl,
4230                                               MVT::i32));
4231   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4232                                   DAG.getConstant(1U << 22, dl, MVT::i32));
4233   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4234                               DAG.getConstant(22, dl, MVT::i32));
4235   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4236                      DAG.getConstant(3, dl, MVT::i32));
4237 }
4238
4239 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4240                          const ARMSubtarget *ST) {
4241   EVT VT = N->getValueType(0);
4242   SDLoc dl(N);
4243
4244   if (!ST->hasV6T2Ops())
4245     return SDValue();
4246
4247   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4248   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4249 }
4250
4251 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4252 /// for each 16-bit element from operand, repeated.  The basic idea is to
4253 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4254 ///
4255 /// Trace for v4i16:
4256 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
4257 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4258 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4259 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4260 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
4261 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
4262 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4263 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
4264 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4265   EVT VT = N->getValueType(0);
4266   SDLoc DL(N);
4267
4268   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4269   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4270   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4271   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4272   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4273   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4274 }
4275
4276 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4277 /// bit-count for each 16-bit element from the operand.  We need slightly
4278 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4279 /// 64/128-bit registers.
4280 ///
4281 /// Trace for v4i16:
4282 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
4283 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4284 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
4285 /// v4i16:Extracted = [k0    k1    k2    k3    ]
4286 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4287   EVT VT = N->getValueType(0);
4288   SDLoc DL(N);
4289
4290   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4291   if (VT.is64BitVector()) {
4292     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4293     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4294                        DAG.getIntPtrConstant(0, DL));
4295   } else {
4296     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4297                                     BitCounts, DAG.getIntPtrConstant(0, DL));
4298     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4299   }
4300 }
4301
4302 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4303 /// bit-count for each 32-bit element from the operand.  The idea here is
4304 /// to split the vector into 16-bit elements, leverage the 16-bit count
4305 /// routine, and then combine the results.
4306 ///
4307 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4308 /// input    = [v0    v1    ] (vi: 32-bit elements)
4309 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4310 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4311 /// vrev: N0 = [k1 k0 k3 k2 ]
4312 ///            [k0 k1 k2 k3 ]
4313 ///       N1 =+[k1 k0 k3 k2 ]
4314 ///            [k0 k2 k1 k3 ]
4315 ///       N2 =+[k1 k3 k0 k2 ]
4316 ///            [k0    k2    k1    k3    ]
4317 /// Extended =+[k1    k3    k0    k2    ]
4318 ///            [k0    k2    ]
4319 /// Extracted=+[k1    k3    ]
4320 ///
4321 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4322   EVT VT = N->getValueType(0);
4323   SDLoc DL(N);
4324
4325   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4326
4327   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4328   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4329   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4330   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4331   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4332
4333   if (VT.is64BitVector()) {
4334     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4335     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4336                        DAG.getIntPtrConstant(0, DL));
4337   } else {
4338     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4339                                     DAG.getIntPtrConstant(0, DL));
4340     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4341   }
4342 }
4343
4344 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4345                           const ARMSubtarget *ST) {
4346   EVT VT = N->getValueType(0);
4347
4348   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4349   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4350           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4351          "Unexpected type for custom ctpop lowering");
4352
4353   if (VT.getVectorElementType() == MVT::i32)
4354     return lowerCTPOP32BitElements(N, DAG);
4355   else
4356     return lowerCTPOP16BitElements(N, DAG);
4357 }
4358
4359 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4360                           const ARMSubtarget *ST) {
4361   EVT VT = N->getValueType(0);
4362   SDLoc dl(N);
4363
4364   if (!VT.isVector())
4365     return SDValue();
4366
4367   // Lower vector shifts on NEON to use VSHL.
4368   assert(ST->hasNEON() && "unexpected vector shift");
4369
4370   // Left shifts translate directly to the vshiftu intrinsic.
4371   if (N->getOpcode() == ISD::SHL)
4372     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4373                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
4374                                        MVT::i32),
4375                        N->getOperand(0), N->getOperand(1));
4376
4377   assert((N->getOpcode() == ISD::SRA ||
4378           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4379
4380   // NEON uses the same intrinsics for both left and right shifts.  For
4381   // right shifts, the shift amounts are negative, so negate the vector of
4382   // shift amounts.
4383   EVT ShiftVT = N->getOperand(1).getValueType();
4384   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4385                                      getZeroVector(ShiftVT, DAG, dl),
4386                                      N->getOperand(1));
4387   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4388                              Intrinsic::arm_neon_vshifts :
4389                              Intrinsic::arm_neon_vshiftu);
4390   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4391                      DAG.getConstant(vshiftInt, dl, MVT::i32),
4392                      N->getOperand(0), NegatedCount);
4393 }
4394
4395 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4396                                 const ARMSubtarget *ST) {
4397   EVT VT = N->getValueType(0);
4398   SDLoc dl(N);
4399
4400   // We can get here for a node like i32 = ISD::SHL i32, i64
4401   if (VT != MVT::i64)
4402     return SDValue();
4403
4404   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4405          "Unknown shift to lower!");
4406
4407   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4408   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4409       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4410     return SDValue();
4411
4412   // If we are in thumb mode, we don't have RRX.
4413   if (ST->isThumb1Only()) return SDValue();
4414
4415   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4416   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4417                            DAG.getConstant(0, dl, MVT::i32));
4418   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4419                            DAG.getConstant(1, dl, MVT::i32));
4420
4421   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4422   // captures the result into a carry flag.
4423   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4424   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4425
4426   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4427   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4428
4429   // Merge the pieces into a single i64 value.
4430  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4431 }
4432
4433 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4434   SDValue TmpOp0, TmpOp1;
4435   bool Invert = false;
4436   bool Swap = false;
4437   unsigned Opc = 0;
4438
4439   SDValue Op0 = Op.getOperand(0);
4440   SDValue Op1 = Op.getOperand(1);
4441   SDValue CC = Op.getOperand(2);
4442   EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
4443   EVT VT = Op.getValueType();
4444   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4445   SDLoc dl(Op);
4446
4447   if (Op1.getValueType().isFloatingPoint()) {
4448     switch (SetCCOpcode) {
4449     default: llvm_unreachable("Illegal FP comparison");
4450     case ISD::SETUNE:
4451     case ISD::SETNE:  Invert = true; // Fallthrough
4452     case ISD::SETOEQ:
4453     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4454     case ISD::SETOLT:
4455     case ISD::SETLT: Swap = true; // Fallthrough
4456     case ISD::SETOGT:
4457     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4458     case ISD::SETOLE:
4459     case ISD::SETLE:  Swap = true; // Fallthrough
4460     case ISD::SETOGE:
4461     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4462     case ISD::SETUGE: Swap = true; // Fallthrough
4463     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4464     case ISD::SETUGT: Swap = true; // Fallthrough
4465     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4466     case ISD::SETUEQ: Invert = true; // Fallthrough
4467     case ISD::SETONE:
4468       // Expand this to (OLT | OGT).
4469       TmpOp0 = Op0;
4470       TmpOp1 = Op1;
4471       Opc = ISD::OR;
4472       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4473       Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
4474       break;
4475     case ISD::SETUO: Invert = true; // Fallthrough
4476     case ISD::SETO:
4477       // Expand this to (OLT | OGE).
4478       TmpOp0 = Op0;
4479       TmpOp1 = Op1;
4480       Opc = ISD::OR;
4481       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4482       Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
4483       break;
4484     }
4485   } else {
4486     // Integer comparisons.
4487     switch (SetCCOpcode) {
4488     default: llvm_unreachable("Illegal integer comparison");
4489     case ISD::SETNE:  Invert = true;
4490     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4491     case ISD::SETLT:  Swap = true;
4492     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4493     case ISD::SETLE:  Swap = true;
4494     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4495     case ISD::SETULT: Swap = true;
4496     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4497     case ISD::SETULE: Swap = true;
4498     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4499     }
4500
4501     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4502     if (Opc == ARMISD::VCEQ) {
4503
4504       SDValue AndOp;
4505       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4506         AndOp = Op0;
4507       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4508         AndOp = Op1;
4509
4510       // Ignore bitconvert.
4511       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4512         AndOp = AndOp.getOperand(0);
4513
4514       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4515         Opc = ARMISD::VTST;
4516         Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
4517         Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
4518         Invert = !Invert;
4519       }
4520     }
4521   }
4522
4523   if (Swap)
4524     std::swap(Op0, Op1);
4525
4526   // If one of the operands is a constant vector zero, attempt to fold the
4527   // comparison to a specialized compare-against-zero form.
4528   SDValue SingleOp;
4529   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4530     SingleOp = Op0;
4531   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4532     if (Opc == ARMISD::VCGE)
4533       Opc = ARMISD::VCLEZ;
4534     else if (Opc == ARMISD::VCGT)
4535       Opc = ARMISD::VCLTZ;
4536     SingleOp = Op1;
4537   }
4538
4539   SDValue Result;
4540   if (SingleOp.getNode()) {
4541     switch (Opc) {
4542     case ARMISD::VCEQ:
4543       Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
4544     case ARMISD::VCGE:
4545       Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
4546     case ARMISD::VCLEZ:
4547       Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
4548     case ARMISD::VCGT:
4549       Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
4550     case ARMISD::VCLTZ:
4551       Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
4552     default:
4553       Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4554     }
4555   } else {
4556      Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4557   }
4558
4559   Result = DAG.getSExtOrTrunc(Result, dl, VT);
4560
4561   if (Invert)
4562     Result = DAG.getNOT(dl, Result, VT);
4563
4564   return Result;
4565 }
4566
4567 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4568 /// valid vector constant for a NEON instruction with a "modified immediate"
4569 /// operand (e.g., VMOV).  If so, return the encoded value.
4570 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4571                                  unsigned SplatBitSize, SelectionDAG &DAG,
4572                                  SDLoc dl, EVT &VT, bool is128Bits,
4573                                  NEONModImmType type) {
4574   unsigned OpCmode, Imm;
4575
4576   // SplatBitSize is set to the smallest size that splats the vector, so a
4577   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4578   // immediate instructions others than VMOV do not support the 8-bit encoding
4579   // of a zero vector, and the default encoding of zero is supposed to be the
4580   // 32-bit version.
4581   if (SplatBits == 0)
4582     SplatBitSize = 32;
4583
4584   switch (SplatBitSize) {
4585   case 8:
4586     if (type != VMOVModImm)
4587       return SDValue();
4588     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4589     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4590     OpCmode = 0xe;
4591     Imm = SplatBits;
4592     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4593     break;
4594
4595   case 16:
4596     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4597     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4598     if ((SplatBits & ~0xff) == 0) {
4599       // Value = 0x00nn: Op=x, Cmode=100x.
4600       OpCmode = 0x8;
4601       Imm = SplatBits;
4602       break;
4603     }
4604     if ((SplatBits & ~0xff00) == 0) {
4605       // Value = 0xnn00: Op=x, Cmode=101x.
4606       OpCmode = 0xa;
4607       Imm = SplatBits >> 8;
4608       break;
4609     }
4610     return SDValue();
4611
4612   case 32:
4613     // NEON's 32-bit VMOV supports splat values where:
4614     // * only one byte is nonzero, or
4615     // * the least significant byte is 0xff and the second byte is nonzero, or
4616     // * the least significant 2 bytes are 0xff and the third is nonzero.
4617     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4618     if ((SplatBits & ~0xff) == 0) {
4619       // Value = 0x000000nn: Op=x, Cmode=000x.
4620       OpCmode = 0;
4621       Imm = SplatBits;
4622       break;
4623     }
4624     if ((SplatBits & ~0xff00) == 0) {
4625       // Value = 0x0000nn00: Op=x, Cmode=001x.
4626       OpCmode = 0x2;
4627       Imm = SplatBits >> 8;
4628       break;
4629     }
4630     if ((SplatBits & ~0xff0000) == 0) {
4631       // Value = 0x00nn0000: Op=x, Cmode=010x.
4632       OpCmode = 0x4;
4633       Imm = SplatBits >> 16;
4634       break;
4635     }
4636     if ((SplatBits & ~0xff000000) == 0) {
4637       // Value = 0xnn000000: Op=x, Cmode=011x.
4638       OpCmode = 0x6;
4639       Imm = SplatBits >> 24;
4640       break;
4641     }
4642
4643     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4644     if (type == OtherModImm) return SDValue();
4645
4646     if ((SplatBits & ~0xffff) == 0 &&
4647         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4648       // Value = 0x0000nnff: Op=x, Cmode=1100.
4649       OpCmode = 0xc;
4650       Imm = SplatBits >> 8;
4651       break;
4652     }
4653
4654     if ((SplatBits & ~0xffffff) == 0 &&
4655         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4656       // Value = 0x00nnffff: Op=x, Cmode=1101.
4657       OpCmode = 0xd;
4658       Imm = SplatBits >> 16;
4659       break;
4660     }
4661
4662     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4663     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4664     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4665     // and fall through here to test for a valid 64-bit splat.  But, then the
4666     // caller would also need to check and handle the change in size.
4667     return SDValue();
4668
4669   case 64: {
4670     if (type != VMOVModImm)
4671       return SDValue();
4672     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4673     uint64_t BitMask = 0xff;
4674     uint64_t Val = 0;
4675     unsigned ImmMask = 1;
4676     Imm = 0;
4677     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4678       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4679         Val |= BitMask;
4680         Imm |= ImmMask;
4681       } else if ((SplatBits & BitMask) != 0) {
4682         return SDValue();
4683       }
4684       BitMask <<= 8;
4685       ImmMask <<= 1;
4686     }
4687
4688     if (DAG.getTargetLoweringInfo().isBigEndian())
4689       // swap higher and lower 32 bit word
4690       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4691
4692     // Op=1, Cmode=1110.
4693     OpCmode = 0x1e;
4694     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4695     break;
4696   }
4697
4698   default:
4699     llvm_unreachable("unexpected size for isNEONModifiedImm");
4700   }
4701
4702   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4703   return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
4704 }
4705
4706 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4707                                            const ARMSubtarget *ST) const {
4708   if (!ST->hasVFP3())
4709     return SDValue();
4710
4711   bool IsDouble = Op.getValueType() == MVT::f64;
4712   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4713
4714   // Use the default (constant pool) lowering for double constants when we have
4715   // an SP-only FPU
4716   if (IsDouble && Subtarget->isFPOnlySP())
4717     return SDValue();
4718
4719   // Try splatting with a VMOV.f32...
4720   APFloat FPVal = CFP->getValueAPF();
4721   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4722
4723   if (ImmVal != -1) {
4724     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4725       // We have code in place to select a valid ConstantFP already, no need to
4726       // do any mangling.
4727       return Op;
4728     }
4729
4730     // It's a float and we are trying to use NEON operations where
4731     // possible. Lower it to a splat followed by an extract.
4732     SDLoc DL(Op);
4733     SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
4734     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4735                                       NewVal);
4736     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4737                        DAG.getConstant(0, DL, MVT::i32));
4738   }
4739
4740   // The rest of our options are NEON only, make sure that's allowed before
4741   // proceeding..
4742   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4743     return SDValue();
4744
4745   EVT VMovVT;
4746   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4747
4748   // It wouldn't really be worth bothering for doubles except for one very
4749   // important value, which does happen to match: 0.0. So make sure we don't do
4750   // anything stupid.
4751   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4752     return SDValue();
4753
4754   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4755   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
4756                                      VMovVT, false, VMOVModImm);
4757   if (NewVal != SDValue()) {
4758     SDLoc DL(Op);
4759     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4760                                       NewVal);
4761     if (IsDouble)
4762       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4763
4764     // It's a float: cast and extract a vector element.
4765     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4766                                        VecConstant);
4767     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4768                        DAG.getConstant(0, DL, MVT::i32));
4769   }
4770
4771   // Finally, try a VMVN.i32
4772   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
4773                              false, VMVNModImm);
4774   if (NewVal != SDValue()) {
4775     SDLoc DL(Op);
4776     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4777
4778     if (IsDouble)
4779       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4780
4781     // It's a float: cast and extract a vector element.
4782     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4783                                        VecConstant);
4784     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4785                        DAG.getConstant(0, DL, MVT::i32));
4786   }
4787
4788   return SDValue();
4789 }
4790
4791 // check if an VEXT instruction can handle the shuffle mask when the
4792 // vector sources of the shuffle are the same.
4793 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4794   unsigned NumElts = VT.getVectorNumElements();
4795
4796   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4797   if (M[0] < 0)
4798     return false;
4799
4800   Imm = M[0];
4801
4802   // If this is a VEXT shuffle, the immediate value is the index of the first
4803   // element.  The other shuffle indices must be the successive elements after
4804   // the first one.
4805   unsigned ExpectedElt = Imm;
4806   for (unsigned i = 1; i < NumElts; ++i) {
4807     // Increment the expected index.  If it wraps around, just follow it
4808     // back to index zero and keep going.
4809     ++ExpectedElt;
4810     if (ExpectedElt == NumElts)
4811       ExpectedElt = 0;
4812
4813     if (M[i] < 0) continue; // ignore UNDEF indices
4814     if (ExpectedElt != static_cast<unsigned>(M[i]))
4815       return false;
4816   }
4817
4818   return true;
4819 }
4820
4821
4822 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4823                        bool &ReverseVEXT, unsigned &Imm) {
4824   unsigned NumElts = VT.getVectorNumElements();
4825   ReverseVEXT = false;
4826
4827   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4828   if (M[0] < 0)
4829     return false;
4830
4831   Imm = M[0];
4832
4833   // If this is a VEXT shuffle, the immediate value is the index of the first
4834   // element.  The other shuffle indices must be the successive elements after
4835   // the first one.
4836   unsigned ExpectedElt = Imm;
4837   for (unsigned i = 1; i < NumElts; ++i) {
4838     // Increment the expected index.  If it wraps around, it may still be
4839     // a VEXT but the source vectors must be swapped.
4840     ExpectedElt += 1;
4841     if (ExpectedElt == NumElts * 2) {
4842       ExpectedElt = 0;
4843       ReverseVEXT = true;
4844     }
4845
4846     if (M[i] < 0) continue; // ignore UNDEF indices
4847     if (ExpectedElt != static_cast<unsigned>(M[i]))
4848       return false;
4849   }
4850
4851   // Adjust the index value if the source operands will be swapped.
4852   if (ReverseVEXT)
4853     Imm -= NumElts;
4854
4855   return true;
4856 }
4857
4858 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4859 /// instruction with the specified blocksize.  (The order of the elements
4860 /// within each block of the vector is reversed.)
4861 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4862   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4863          "Only possible block sizes for VREV are: 16, 32, 64");
4864
4865   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4866   if (EltSz == 64)
4867     return false;
4868
4869   unsigned NumElts = VT.getVectorNumElements();
4870   unsigned BlockElts = M[0] + 1;
4871   // If the first shuffle index is UNDEF, be optimistic.
4872   if (M[0] < 0)
4873     BlockElts = BlockSize / EltSz;
4874
4875   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4876     return false;
4877
4878   for (unsigned i = 0; i < NumElts; ++i) {
4879     if (M[i] < 0) continue; // ignore UNDEF indices
4880     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4881       return false;
4882   }
4883
4884   return true;
4885 }
4886
4887 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4888   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4889   // range, then 0 is placed into the resulting vector. So pretty much any mask
4890   // of 8 elements can work here.
4891   return VT == MVT::v8i8 && M.size() == 8;
4892 }
4893
4894 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4895   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4896   if (EltSz == 64)
4897     return false;
4898
4899   unsigned NumElts = VT.getVectorNumElements();
4900   WhichResult = (M[0] == 0 ? 0 : 1);
4901   for (unsigned i = 0; i < NumElts; i += 2) {
4902     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4903         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4904       return false;
4905   }
4906   return true;
4907 }
4908
4909 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4910 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4911 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4912 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4913   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4914   if (EltSz == 64)
4915     return false;
4916
4917   unsigned NumElts = VT.getVectorNumElements();
4918   WhichResult = (M[0] == 0 ? 0 : 1);
4919   for (unsigned i = 0; i < NumElts; i += 2) {
4920     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4921         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4922       return false;
4923   }
4924   return true;
4925 }
4926
4927 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4928   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4929   if (EltSz == 64)
4930     return false;
4931
4932   unsigned NumElts = VT.getVectorNumElements();
4933   WhichResult = (M[0] == 0 ? 0 : 1);
4934   for (unsigned i = 0; i != NumElts; ++i) {
4935     if (M[i] < 0) continue; // ignore UNDEF indices
4936     if ((unsigned) M[i] != 2 * i + WhichResult)
4937       return false;
4938   }
4939
4940   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4941   if (VT.is64BitVector() && EltSz == 32)
4942     return false;
4943
4944   return true;
4945 }
4946
4947 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4948 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4949 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4950 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4951   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4952   if (EltSz == 64)
4953     return false;
4954
4955   unsigned Half = VT.getVectorNumElements() / 2;
4956   WhichResult = (M[0] == 0 ? 0 : 1);
4957   for (unsigned j = 0; j != 2; ++j) {
4958     unsigned Idx = WhichResult;
4959     for (unsigned i = 0; i != Half; ++i) {
4960       int MIdx = M[i + j * Half];
4961       if (MIdx >= 0 && (unsigned) MIdx != Idx)
4962         return false;
4963       Idx += 2;
4964     }
4965   }
4966
4967   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4968   if (VT.is64BitVector() && EltSz == 32)
4969     return false;
4970
4971   return true;
4972 }
4973
4974 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4975   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4976   if (EltSz == 64)
4977     return false;
4978
4979   unsigned NumElts = VT.getVectorNumElements();
4980   WhichResult = (M[0] == 0 ? 0 : 1);
4981   unsigned Idx = WhichResult * NumElts / 2;
4982   for (unsigned i = 0; i != NumElts; i += 2) {
4983     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4984         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4985       return false;
4986     Idx += 1;
4987   }
4988
4989   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4990   if (VT.is64BitVector() && EltSz == 32)
4991     return false;
4992
4993   return true;
4994 }
4995
4996 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4997 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4998 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4999 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5000   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5001   if (EltSz == 64)
5002     return false;
5003
5004   unsigned NumElts = VT.getVectorNumElements();
5005   WhichResult = (M[0] == 0 ? 0 : 1);
5006   unsigned Idx = WhichResult * NumElts / 2;
5007   for (unsigned i = 0; i != NumElts; i += 2) {
5008     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
5009         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
5010       return false;
5011     Idx += 1;
5012   }
5013
5014   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5015   if (VT.is64BitVector() && EltSz == 32)
5016     return false;
5017
5018   return true;
5019 }
5020
5021 /// \return true if this is a reverse operation on an vector.
5022 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5023   unsigned NumElts = VT.getVectorNumElements();
5024   // Make sure the mask has the right size.
5025   if (NumElts != M.size())
5026       return false;
5027
5028   // Look for <15, ..., 3, -1, 1, 0>.
5029   for (unsigned i = 0; i != NumElts; ++i)
5030     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5031       return false;
5032
5033   return true;
5034 }
5035
5036 // If N is an integer constant that can be moved into a register in one
5037 // instruction, return an SDValue of such a constant (will become a MOV
5038 // instruction).  Otherwise return null.
5039 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5040                                      const ARMSubtarget *ST, SDLoc dl) {
5041   uint64_t Val;
5042   if (!isa<ConstantSDNode>(N))
5043     return SDValue();
5044   Val = cast<ConstantSDNode>(N)->getZExtValue();
5045
5046   if (ST->isThumb1Only()) {
5047     if (Val <= 255 || ~Val <= 255)
5048       return DAG.getConstant(Val, dl, MVT::i32);
5049   } else {
5050     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5051       return DAG.getConstant(Val, dl, MVT::i32);
5052   }
5053   return SDValue();
5054 }
5055
5056 // If this is a case we can't handle, return null and let the default
5057 // expansion code take care of it.
5058 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5059                                              const ARMSubtarget *ST) const {
5060   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5061   SDLoc dl(Op);
5062   EVT VT = Op.getValueType();
5063
5064   APInt SplatBits, SplatUndef;
5065   unsigned SplatBitSize;
5066   bool HasAnyUndefs;
5067   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5068     if (SplatBitSize <= 64) {
5069       // Check if an immediate VMOV works.
5070       EVT VmovVT;
5071       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5072                                       SplatUndef.getZExtValue(), SplatBitSize,
5073                                       DAG, dl, VmovVT, VT.is128BitVector(),
5074                                       VMOVModImm);
5075       if (Val.getNode()) {
5076         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5077         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5078       }
5079
5080       // Try an immediate VMVN.
5081       uint64_t NegatedImm = (~SplatBits).getZExtValue();
5082       Val = isNEONModifiedImm(NegatedImm,
5083                                       SplatUndef.getZExtValue(), SplatBitSize,
5084                                       DAG, dl, VmovVT, VT.is128BitVector(),
5085                                       VMVNModImm);
5086       if (Val.getNode()) {
5087         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5088         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5089       }
5090
5091       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5092       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5093         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5094         if (ImmVal != -1) {
5095           SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
5096           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5097         }
5098       }
5099     }
5100   }
5101
5102   // Scan through the operands to see if only one value is used.
5103   //
5104   // As an optimisation, even if more than one value is used it may be more
5105   // profitable to splat with one value then change some lanes.
5106   //
5107   // Heuristically we decide to do this if the vector has a "dominant" value,
5108   // defined as splatted to more than half of the lanes.
5109   unsigned NumElts = VT.getVectorNumElements();
5110   bool isOnlyLowElement = true;
5111   bool usesOnlyOneValue = true;
5112   bool hasDominantValue = false;
5113   bool isConstant = true;
5114
5115   // Map of the number of times a particular SDValue appears in the
5116   // element list.
5117   DenseMap<SDValue, unsigned> ValueCounts;
5118   SDValue Value;
5119   for (unsigned i = 0; i < NumElts; ++i) {
5120     SDValue V = Op.getOperand(i);
5121     if (V.getOpcode() == ISD::UNDEF)
5122       continue;
5123     if (i > 0)
5124       isOnlyLowElement = false;
5125     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5126       isConstant = false;
5127
5128     ValueCounts.insert(std::make_pair(V, 0));
5129     unsigned &Count = ValueCounts[V];
5130
5131     // Is this value dominant? (takes up more than half of the lanes)
5132     if (++Count > (NumElts / 2)) {
5133       hasDominantValue = true;
5134       Value = V;
5135     }
5136   }
5137   if (ValueCounts.size() != 1)
5138     usesOnlyOneValue = false;
5139   if (!Value.getNode() && ValueCounts.size() > 0)
5140     Value = ValueCounts.begin()->first;
5141
5142   if (ValueCounts.size() == 0)
5143     return DAG.getUNDEF(VT);
5144
5145   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5146   // Keep going if we are hitting this case.
5147   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5148     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5149
5150   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5151
5152   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
5153   // i32 and try again.
5154   if (hasDominantValue && EltSize <= 32) {
5155     if (!isConstant) {
5156       SDValue N;
5157
5158       // If we are VDUPing a value that comes directly from a vector, that will
5159       // cause an unnecessary move to and from a GPR, where instead we could
5160       // just use VDUPLANE. We can only do this if the lane being extracted
5161       // is at a constant index, as the VDUP from lane instructions only have
5162       // constant-index forms.
5163       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5164           isa<ConstantSDNode>(Value->getOperand(1))) {
5165         // We need to create a new undef vector to use for the VDUPLANE if the
5166         // size of the vector from which we get the value is different than the
5167         // size of the vector that we need to create. We will insert the element
5168         // such that the register coalescer will remove unnecessary copies.
5169         if (VT != Value->getOperand(0).getValueType()) {
5170           ConstantSDNode *constIndex;
5171           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5172           assert(constIndex && "The index is not a constant!");
5173           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5174                              VT.getVectorNumElements();
5175           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5176                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5177                         Value, DAG.getConstant(index, dl, MVT::i32)),
5178                            DAG.getConstant(index, dl, MVT::i32));
5179         } else
5180           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5181                         Value->getOperand(0), Value->getOperand(1));
5182       } else
5183         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5184
5185       if (!usesOnlyOneValue) {
5186         // The dominant value was splatted as 'N', but we now have to insert
5187         // all differing elements.
5188         for (unsigned I = 0; I < NumElts; ++I) {
5189           if (Op.getOperand(I) == Value)
5190             continue;
5191           SmallVector<SDValue, 3> Ops;
5192           Ops.push_back(N);
5193           Ops.push_back(Op.getOperand(I));
5194           Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
5195           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5196         }
5197       }
5198       return N;
5199     }
5200     if (VT.getVectorElementType().isFloatingPoint()) {
5201       SmallVector<SDValue, 8> Ops;
5202       for (unsigned i = 0; i < NumElts; ++i)
5203         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5204                                   Op.getOperand(i)));
5205       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5206       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5207       Val = LowerBUILD_VECTOR(Val, DAG, ST);
5208       if (Val.getNode())
5209         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5210     }
5211     if (usesOnlyOneValue) {
5212       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5213       if (isConstant && Val.getNode())
5214         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5215     }
5216   }
5217
5218   // If all elements are constants and the case above didn't get hit, fall back
5219   // to the default expansion, which will generate a load from the constant
5220   // pool.
5221   if (isConstant)
5222     return SDValue();
5223
5224   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5225   if (NumElts >= 4) {
5226     SDValue shuffle = ReconstructShuffle(Op, DAG);
5227     if (shuffle != SDValue())
5228       return shuffle;
5229   }
5230
5231   // Vectors with 32- or 64-bit elements can be built by directly assigning
5232   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
5233   // will be legalized.
5234   if (EltSize >= 32) {
5235     // Do the expansion with floating-point types, since that is what the VFP
5236     // registers are defined to use, and since i64 is not legal.
5237     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5238     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5239     SmallVector<SDValue, 8> Ops;
5240     for (unsigned i = 0; i < NumElts; ++i)
5241       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5242     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5243     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5244   }
5245
5246   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5247   // know the default expansion would otherwise fall back on something even
5248   // worse. For a vector with one or two non-undef values, that's
5249   // scalar_to_vector for the elements followed by a shuffle (provided the
5250   // shuffle is valid for the target) and materialization element by element
5251   // on the stack followed by a load for everything else.
5252   if (!isConstant && !usesOnlyOneValue) {
5253     SDValue Vec = DAG.getUNDEF(VT);
5254     for (unsigned i = 0 ; i < NumElts; ++i) {
5255       SDValue V = Op.getOperand(i);
5256       if (V.getOpcode() == ISD::UNDEF)
5257         continue;
5258       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
5259       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5260     }
5261     return Vec;
5262   }
5263
5264   return SDValue();
5265 }
5266
5267 // Gather data to see if the operation can be modelled as a
5268 // shuffle in combination with VEXTs.
5269 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5270                                               SelectionDAG &DAG) const {
5271   SDLoc dl(Op);
5272   EVT VT = Op.getValueType();
5273   unsigned NumElts = VT.getVectorNumElements();
5274
5275   SmallVector<SDValue, 2> SourceVecs;
5276   SmallVector<unsigned, 2> MinElts;
5277   SmallVector<unsigned, 2> MaxElts;
5278
5279   for (unsigned i = 0; i < NumElts; ++i) {
5280     SDValue V = Op.getOperand(i);
5281     if (V.getOpcode() == ISD::UNDEF)
5282       continue;
5283     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5284       // A shuffle can only come from building a vector from various
5285       // elements of other vectors.
5286       return SDValue();
5287     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5288                VT.getVectorElementType()) {
5289       // This code doesn't know how to handle shuffles where the vector
5290       // element types do not match (this happens because type legalization
5291       // promotes the return type of EXTRACT_VECTOR_ELT).
5292       // FIXME: It might be appropriate to extend this code to handle
5293       // mismatched types.
5294       return SDValue();
5295     }
5296
5297     // Record this extraction against the appropriate vector if possible...
5298     SDValue SourceVec = V.getOperand(0);
5299     // If the element number isn't a constant, we can't effectively
5300     // analyze what's going on.
5301     if (!isa<ConstantSDNode>(V.getOperand(1)))
5302       return SDValue();
5303     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5304     bool FoundSource = false;
5305     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5306       if (SourceVecs[j] == SourceVec) {
5307         if (MinElts[j] > EltNo)
5308           MinElts[j] = EltNo;
5309         if (MaxElts[j] < EltNo)
5310           MaxElts[j] = EltNo;
5311         FoundSource = true;
5312         break;
5313       }
5314     }
5315
5316     // Or record a new source if not...
5317     if (!FoundSource) {
5318       SourceVecs.push_back(SourceVec);
5319       MinElts.push_back(EltNo);
5320       MaxElts.push_back(EltNo);
5321     }
5322   }
5323
5324   // Currently only do something sane when at most two source vectors
5325   // involved.
5326   if (SourceVecs.size() > 2)
5327     return SDValue();
5328
5329   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5330   int VEXTOffsets[2] = {0, 0};
5331
5332   // This loop extracts the usage patterns of the source vectors
5333   // and prepares appropriate SDValues for a shuffle if possible.
5334   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5335     if (SourceVecs[i].getValueType() == VT) {
5336       // No VEXT necessary
5337       ShuffleSrcs[i] = SourceVecs[i];
5338       VEXTOffsets[i] = 0;
5339       continue;
5340     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5341       // It probably isn't worth padding out a smaller vector just to
5342       // break it down again in a shuffle.
5343       return SDValue();
5344     }
5345
5346     // Since only 64-bit and 128-bit vectors are legal on ARM and
5347     // we've eliminated the other cases...
5348     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5349            "unexpected vector sizes in ReconstructShuffle");
5350
5351     if (MaxElts[i] - MinElts[i] >= NumElts) {
5352       // Span too large for a VEXT to cope
5353       return SDValue();
5354     }
5355
5356     if (MinElts[i] >= NumElts) {
5357       // The extraction can just take the second half
5358       VEXTOffsets[i] = NumElts;
5359       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5360                                    SourceVecs[i],
5361                                    DAG.getIntPtrConstant(NumElts, dl));
5362     } else if (MaxElts[i] < NumElts) {
5363       // The extraction can just take the first half
5364       VEXTOffsets[i] = 0;
5365       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5366                                    SourceVecs[i],
5367                                    DAG.getIntPtrConstant(0, dl));
5368     } else {
5369       // An actual VEXT is needed
5370       VEXTOffsets[i] = MinElts[i];
5371       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5372                                      SourceVecs[i],
5373                                      DAG.getIntPtrConstant(0, dl));
5374       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5375                                      SourceVecs[i],
5376                                      DAG.getIntPtrConstant(NumElts, dl));
5377       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5378                                    DAG.getConstant(VEXTOffsets[i], dl,
5379                                                    MVT::i32));
5380     }
5381   }
5382
5383   SmallVector<int, 8> Mask;
5384
5385   for (unsigned i = 0; i < NumElts; ++i) {
5386     SDValue Entry = Op.getOperand(i);
5387     if (Entry.getOpcode() == ISD::UNDEF) {
5388       Mask.push_back(-1);
5389       continue;
5390     }
5391
5392     SDValue ExtractVec = Entry.getOperand(0);
5393     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5394                                           .getOperand(1))->getSExtValue();
5395     if (ExtractVec == SourceVecs[0]) {
5396       Mask.push_back(ExtractElt - VEXTOffsets[0]);
5397     } else {
5398       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5399     }
5400   }
5401
5402   // Final check before we try to produce nonsense...
5403   if (isShuffleMaskLegal(Mask, VT))
5404     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5405                                 &Mask[0]);
5406
5407   return SDValue();
5408 }
5409
5410 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5411 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5412 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5413 /// are assumed to be legal.
5414 bool
5415 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5416                                       EVT VT) const {
5417   if (VT.getVectorNumElements() == 4 &&
5418       (VT.is128BitVector() || VT.is64BitVector())) {
5419     unsigned PFIndexes[4];
5420     for (unsigned i = 0; i != 4; ++i) {
5421       if (M[i] < 0)
5422         PFIndexes[i] = 8;
5423       else
5424         PFIndexes[i] = M[i];
5425     }
5426
5427     // Compute the index in the perfect shuffle table.
5428     unsigned PFTableIndex =
5429       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5430     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5431     unsigned Cost = (PFEntry >> 30);
5432
5433     if (Cost <= 4)
5434       return true;
5435   }
5436
5437   bool ReverseVEXT;
5438   unsigned Imm, WhichResult;
5439
5440   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5441   return (EltSize >= 32 ||
5442           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5443           isVREVMask(M, VT, 64) ||
5444           isVREVMask(M, VT, 32) ||
5445           isVREVMask(M, VT, 16) ||
5446           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5447           isVTBLMask(M, VT) ||
5448           isVTRNMask(M, VT, WhichResult) ||
5449           isVUZPMask(M, VT, WhichResult) ||
5450           isVZIPMask(M, VT, WhichResult) ||
5451           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5452           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5453           isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5454           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5455 }
5456
5457 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5458 /// the specified operations to build the shuffle.
5459 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5460                                       SDValue RHS, SelectionDAG &DAG,
5461                                       SDLoc dl) {
5462   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5463   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5464   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5465
5466   enum {
5467     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5468     OP_VREV,
5469     OP_VDUP0,
5470     OP_VDUP1,
5471     OP_VDUP2,
5472     OP_VDUP3,
5473     OP_VEXT1,
5474     OP_VEXT2,
5475     OP_VEXT3,
5476     OP_VUZPL, // VUZP, left result
5477     OP_VUZPR, // VUZP, right result
5478     OP_VZIPL, // VZIP, left result
5479     OP_VZIPR, // VZIP, right result
5480     OP_VTRNL, // VTRN, left result
5481     OP_VTRNR  // VTRN, right result
5482   };
5483
5484   if (OpNum == OP_COPY) {
5485     if (LHSID == (1*9+2)*9+3) return LHS;
5486     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5487     return RHS;
5488   }
5489
5490   SDValue OpLHS, OpRHS;
5491   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5492   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5493   EVT VT = OpLHS.getValueType();
5494
5495   switch (OpNum) {
5496   default: llvm_unreachable("Unknown shuffle opcode!");
5497   case OP_VREV:
5498     // VREV divides the vector in half and swaps within the half.
5499     if (VT.getVectorElementType() == MVT::i32 ||
5500         VT.getVectorElementType() == MVT::f32)
5501       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5502     // vrev <4 x i16> -> VREV32
5503     if (VT.getVectorElementType() == MVT::i16)
5504       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5505     // vrev <4 x i8> -> VREV16
5506     assert(VT.getVectorElementType() == MVT::i8);
5507     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5508   case OP_VDUP0:
5509   case OP_VDUP1:
5510   case OP_VDUP2:
5511   case OP_VDUP3:
5512     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5513                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
5514   case OP_VEXT1:
5515   case OP_VEXT2:
5516   case OP_VEXT3:
5517     return DAG.getNode(ARMISD::VEXT, dl, VT,
5518                        OpLHS, OpRHS,
5519                        DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
5520   case OP_VUZPL:
5521   case OP_VUZPR:
5522     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5523                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5524   case OP_VZIPL:
5525   case OP_VZIPR:
5526     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5527                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5528   case OP_VTRNL:
5529   case OP_VTRNR:
5530     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5531                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5532   }
5533 }
5534
5535 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5536                                        ArrayRef<int> ShuffleMask,
5537                                        SelectionDAG &DAG) {
5538   // Check to see if we can use the VTBL instruction.
5539   SDValue V1 = Op.getOperand(0);
5540   SDValue V2 = Op.getOperand(1);
5541   SDLoc DL(Op);
5542
5543   SmallVector<SDValue, 8> VTBLMask;
5544   for (ArrayRef<int>::iterator
5545          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5546     VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
5547
5548   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5549     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5550                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5551
5552   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5553                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5554 }
5555
5556 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5557                                                       SelectionDAG &DAG) {
5558   SDLoc DL(Op);
5559   SDValue OpLHS = Op.getOperand(0);
5560   EVT VT = OpLHS.getValueType();
5561
5562   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5563          "Expect an v8i16/v16i8 type");
5564   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5565   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5566   // extract the first 8 bytes into the top double word and the last 8 bytes
5567   // into the bottom double word. The v8i16 case is similar.
5568   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5569   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5570                      DAG.getConstant(ExtractNum, DL, MVT::i32));
5571 }
5572
5573 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5574   SDValue V1 = Op.getOperand(0);
5575   SDValue V2 = Op.getOperand(1);
5576   SDLoc dl(Op);
5577   EVT VT = Op.getValueType();
5578   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5579
5580   // Convert shuffles that are directly supported on NEON to target-specific
5581   // DAG nodes, instead of keeping them as shuffles and matching them again
5582   // during code selection.  This is more efficient and avoids the possibility
5583   // of inconsistencies between legalization and selection.
5584   // FIXME: floating-point vectors should be canonicalized to integer vectors
5585   // of the same time so that they get CSEd properly.
5586   ArrayRef<int> ShuffleMask = SVN->getMask();
5587
5588   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5589   if (EltSize <= 32) {
5590     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5591       int Lane = SVN->getSplatIndex();
5592       // If this is undef splat, generate it via "just" vdup, if possible.
5593       if (Lane == -1) Lane = 0;
5594
5595       // Test if V1 is a SCALAR_TO_VECTOR.
5596       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5597         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5598       }
5599       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5600       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5601       // reaches it).
5602       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5603           !isa<ConstantSDNode>(V1.getOperand(0))) {
5604         bool IsScalarToVector = true;
5605         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5606           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5607             IsScalarToVector = false;
5608             break;
5609           }
5610         if (IsScalarToVector)
5611           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5612       }
5613       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5614                          DAG.getConstant(Lane, dl, MVT::i32));
5615     }
5616
5617     bool ReverseVEXT;
5618     unsigned Imm;
5619     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5620       if (ReverseVEXT)
5621         std::swap(V1, V2);
5622       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5623                          DAG.getConstant(Imm, dl, MVT::i32));
5624     }
5625
5626     if (isVREVMask(ShuffleMask, VT, 64))
5627       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5628     if (isVREVMask(ShuffleMask, VT, 32))
5629       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5630     if (isVREVMask(ShuffleMask, VT, 16))
5631       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5632
5633     if (V2->getOpcode() == ISD::UNDEF &&
5634         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5635       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5636                          DAG.getConstant(Imm, dl, MVT::i32));
5637     }
5638
5639     // Check for Neon shuffles that modify both input vectors in place.
5640     // If both results are used, i.e., if there are two shuffles with the same
5641     // source operands and with masks corresponding to both results of one of
5642     // these operations, DAG memoization will ensure that a single node is
5643     // used for both shuffles.
5644     unsigned WhichResult;
5645     if (isVTRNMask(ShuffleMask, VT, WhichResult))
5646       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5647                          V1, V2).getValue(WhichResult);
5648     if (isVUZPMask(ShuffleMask, VT, WhichResult))
5649       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5650                          V1, V2).getValue(WhichResult);
5651     if (isVZIPMask(ShuffleMask, VT, WhichResult))
5652       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5653                          V1, V2).getValue(WhichResult);
5654
5655     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5656       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5657                          V1, V1).getValue(WhichResult);
5658     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5659       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5660                          V1, V1).getValue(WhichResult);
5661     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5662       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5663                          V1, V1).getValue(WhichResult);
5664   }
5665
5666   // If the shuffle is not directly supported and it has 4 elements, use
5667   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5668   unsigned NumElts = VT.getVectorNumElements();
5669   if (NumElts == 4) {
5670     unsigned PFIndexes[4];
5671     for (unsigned i = 0; i != 4; ++i) {
5672       if (ShuffleMask[i] < 0)
5673         PFIndexes[i] = 8;
5674       else
5675         PFIndexes[i] = ShuffleMask[i];
5676     }
5677
5678     // Compute the index in the perfect shuffle table.
5679     unsigned PFTableIndex =
5680       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5681     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5682     unsigned Cost = (PFEntry >> 30);
5683
5684     if (Cost <= 4)
5685       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5686   }
5687
5688   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5689   if (EltSize >= 32) {
5690     // Do the expansion with floating-point types, since that is what the VFP
5691     // registers are defined to use, and since i64 is not legal.
5692     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5693     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5694     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5695     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5696     SmallVector<SDValue, 8> Ops;
5697     for (unsigned i = 0; i < NumElts; ++i) {
5698       if (ShuffleMask[i] < 0)
5699         Ops.push_back(DAG.getUNDEF(EltVT));
5700       else
5701         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5702                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
5703                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5704                                                   dl, MVT::i32)));
5705     }
5706     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5707     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5708   }
5709
5710   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5711     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5712
5713   if (VT == MVT::v8i8) {
5714     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5715     if (NewOp.getNode())
5716       return NewOp;
5717   }
5718
5719   return SDValue();
5720 }
5721
5722 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5723   // INSERT_VECTOR_ELT is legal only for immediate indexes.
5724   SDValue Lane = Op.getOperand(2);
5725   if (!isa<ConstantSDNode>(Lane))
5726     return SDValue();
5727
5728   return Op;
5729 }
5730
5731 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5732   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5733   SDValue Lane = Op.getOperand(1);
5734   if (!isa<ConstantSDNode>(Lane))
5735     return SDValue();
5736
5737   SDValue Vec = Op.getOperand(0);
5738   if (Op.getValueType() == MVT::i32 &&
5739       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5740     SDLoc dl(Op);
5741     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5742   }
5743
5744   return Op;
5745 }
5746
5747 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5748   // The only time a CONCAT_VECTORS operation can have legal types is when
5749   // two 64-bit vectors are concatenated to a 128-bit vector.
5750   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5751          "unexpected CONCAT_VECTORS");
5752   SDLoc dl(Op);
5753   SDValue Val = DAG.getUNDEF(MVT::v2f64);
5754   SDValue Op0 = Op.getOperand(0);
5755   SDValue Op1 = Op.getOperand(1);
5756   if (Op0.getOpcode() != ISD::UNDEF)
5757     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5758                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5759                       DAG.getIntPtrConstant(0, dl));
5760   if (Op1.getOpcode() != ISD::UNDEF)
5761     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5762                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5763                       DAG.getIntPtrConstant(1, dl));
5764   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5765 }
5766
5767 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5768 /// element has been zero/sign-extended, depending on the isSigned parameter,
5769 /// from an integer type half its size.
5770 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5771                                    bool isSigned) {
5772   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5773   EVT VT = N->getValueType(0);
5774   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5775     SDNode *BVN = N->getOperand(0).getNode();
5776     if (BVN->getValueType(0) != MVT::v4i32 ||
5777         BVN->getOpcode() != ISD::BUILD_VECTOR)
5778       return false;
5779     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5780     unsigned HiElt = 1 - LoElt;
5781     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5782     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5783     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5784     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5785     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5786       return false;
5787     if (isSigned) {
5788       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5789           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5790         return true;
5791     } else {
5792       if (Hi0->isNullValue() && Hi1->isNullValue())
5793         return true;
5794     }
5795     return false;
5796   }
5797
5798   if (N->getOpcode() != ISD::BUILD_VECTOR)
5799     return false;
5800
5801   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5802     SDNode *Elt = N->getOperand(i).getNode();
5803     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5804       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5805       unsigned HalfSize = EltSize / 2;
5806       if (isSigned) {
5807         if (!isIntN(HalfSize, C->getSExtValue()))
5808           return false;
5809       } else {
5810         if (!isUIntN(HalfSize, C->getZExtValue()))
5811           return false;
5812       }
5813       continue;
5814     }
5815     return false;
5816   }
5817
5818   return true;
5819 }
5820
5821 /// isSignExtended - Check if a node is a vector value that is sign-extended
5822 /// or a constant BUILD_VECTOR with sign-extended elements.
5823 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5824   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5825     return true;
5826   if (isExtendedBUILD_VECTOR(N, DAG, true))
5827     return true;
5828   return false;
5829 }
5830
5831 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5832 /// or a constant BUILD_VECTOR with zero-extended elements.
5833 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5834   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5835     return true;
5836   if (isExtendedBUILD_VECTOR(N, DAG, false))
5837     return true;
5838   return false;
5839 }
5840
5841 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5842   if (OrigVT.getSizeInBits() >= 64)
5843     return OrigVT;
5844
5845   assert(OrigVT.isSimple() && "Expecting a simple value type");
5846
5847   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5848   switch (OrigSimpleTy) {
5849   default: llvm_unreachable("Unexpected Vector Type");
5850   case MVT::v2i8:
5851   case MVT::v2i16:
5852      return MVT::v2i32;
5853   case MVT::v4i8:
5854     return  MVT::v4i16;
5855   }
5856 }
5857
5858 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5859 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5860 /// We insert the required extension here to get the vector to fill a D register.
5861 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5862                                             const EVT &OrigTy,
5863                                             const EVT &ExtTy,
5864                                             unsigned ExtOpcode) {
5865   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5866   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5867   // 64-bits we need to insert a new extension so that it will be 64-bits.
5868   assert(ExtTy.is128BitVector() && "Unexpected extension size");
5869   if (OrigTy.getSizeInBits() >= 64)
5870     return N;
5871
5872   // Must extend size to at least 64 bits to be used as an operand for VMULL.
5873   EVT NewVT = getExtensionTo64Bits(OrigTy);
5874
5875   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5876 }
5877
5878 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5879 /// does not do any sign/zero extension. If the original vector is less
5880 /// than 64 bits, an appropriate extension will be added after the load to
5881 /// reach a total size of 64 bits. We have to add the extension separately
5882 /// because ARM does not have a sign/zero extending load for vectors.
5883 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5884   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5885
5886   // The load already has the right type.
5887   if (ExtendedTy == LD->getMemoryVT())
5888     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5889                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5890                 LD->isNonTemporal(), LD->isInvariant(),
5891                 LD->getAlignment());
5892
5893   // We need to create a zextload/sextload. We cannot just create a load
5894   // followed by a zext/zext node because LowerMUL is also run during normal
5895   // operation legalization where we can't create illegal types.
5896   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5897                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5898                         LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
5899                         LD->isNonTemporal(), LD->getAlignment());
5900 }
5901
5902 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5903 /// extending load, or BUILD_VECTOR with extended elements, return the
5904 /// unextended value. The unextended vector should be 64 bits so that it can
5905 /// be used as an operand to a VMULL instruction. If the original vector size
5906 /// before extension is less than 64 bits we add a an extension to resize
5907 /// the vector to 64 bits.
5908 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5909   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5910     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5911                                         N->getOperand(0)->getValueType(0),
5912                                         N->getValueType(0),
5913                                         N->getOpcode());
5914
5915   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5916     return SkipLoadExtensionForVMULL(LD, DAG);
5917
5918   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
5919   // have been legalized as a BITCAST from v4i32.
5920   if (N->getOpcode() == ISD::BITCAST) {
5921     SDNode *BVN = N->getOperand(0).getNode();
5922     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5923            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5924     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5925     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5926                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5927   }
5928   // Construct a new BUILD_VECTOR with elements truncated to half the size.
5929   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5930   EVT VT = N->getValueType(0);
5931   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5932   unsigned NumElts = VT.getVectorNumElements();
5933   MVT TruncVT = MVT::getIntegerVT(EltSize);
5934   SmallVector<SDValue, 8> Ops;
5935   SDLoc dl(N);
5936   for (unsigned i = 0; i != NumElts; ++i) {
5937     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5938     const APInt &CInt = C->getAPIntValue();
5939     // Element types smaller than 32 bits are not legal, so use i32 elements.
5940     // The values are implicitly truncated so sext vs. zext doesn't matter.
5941     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
5942   }
5943   return DAG.getNode(ISD::BUILD_VECTOR, dl,
5944                      MVT::getVectorVT(TruncVT, NumElts), Ops);
5945 }
5946
5947 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5948   unsigned Opcode = N->getOpcode();
5949   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5950     SDNode *N0 = N->getOperand(0).getNode();
5951     SDNode *N1 = N->getOperand(1).getNode();
5952     return N0->hasOneUse() && N1->hasOneUse() &&
5953       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5954   }
5955   return false;
5956 }
5957
5958 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5959   unsigned Opcode = N->getOpcode();
5960   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5961     SDNode *N0 = N->getOperand(0).getNode();
5962     SDNode *N1 = N->getOperand(1).getNode();
5963     return N0->hasOneUse() && N1->hasOneUse() &&
5964       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5965   }
5966   return false;
5967 }
5968
5969 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5970   // Multiplications are only custom-lowered for 128-bit vectors so that
5971   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
5972   EVT VT = Op.getValueType();
5973   assert(VT.is128BitVector() && VT.isInteger() &&
5974          "unexpected type for custom-lowering ISD::MUL");
5975   SDNode *N0 = Op.getOperand(0).getNode();
5976   SDNode *N1 = Op.getOperand(1).getNode();
5977   unsigned NewOpc = 0;
5978   bool isMLA = false;
5979   bool isN0SExt = isSignExtended(N0, DAG);
5980   bool isN1SExt = isSignExtended(N1, DAG);
5981   if (isN0SExt && isN1SExt)
5982     NewOpc = ARMISD::VMULLs;
5983   else {
5984     bool isN0ZExt = isZeroExtended(N0, DAG);
5985     bool isN1ZExt = isZeroExtended(N1, DAG);
5986     if (isN0ZExt && isN1ZExt)
5987       NewOpc = ARMISD::VMULLu;
5988     else if (isN1SExt || isN1ZExt) {
5989       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5990       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5991       if (isN1SExt && isAddSubSExt(N0, DAG)) {
5992         NewOpc = ARMISD::VMULLs;
5993         isMLA = true;
5994       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5995         NewOpc = ARMISD::VMULLu;
5996         isMLA = true;
5997       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5998         std::swap(N0, N1);
5999         NewOpc = ARMISD::VMULLu;
6000         isMLA = true;
6001       }
6002     }
6003
6004     if (!NewOpc) {
6005       if (VT == MVT::v2i64)
6006         // Fall through to expand this.  It is not legal.
6007         return SDValue();
6008       else
6009         // Other vector multiplications are legal.
6010         return Op;
6011     }
6012   }
6013
6014   // Legalize to a VMULL instruction.
6015   SDLoc DL(Op);
6016   SDValue Op0;
6017   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
6018   if (!isMLA) {
6019     Op0 = SkipExtensionForVMULL(N0, DAG);
6020     assert(Op0.getValueType().is64BitVector() &&
6021            Op1.getValueType().is64BitVector() &&
6022            "unexpected types for extended operands to VMULL");
6023     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
6024   }
6025
6026   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
6027   // isel lowering to take advantage of no-stall back to back vmul + vmla.
6028   //   vmull q0, d4, d6
6029   //   vmlal q0, d5, d6
6030   // is faster than
6031   //   vaddl q0, d4, d5
6032   //   vmovl q1, d6
6033   //   vmul  q0, q0, q1
6034   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
6035   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
6036   EVT Op1VT = Op1.getValueType();
6037   return DAG.getNode(N0->getOpcode(), DL, VT,
6038                      DAG.getNode(NewOpc, DL, VT,
6039                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
6040                      DAG.getNode(NewOpc, DL, VT,
6041                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
6042 }
6043
6044 static SDValue
6045 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
6046   // Convert to float
6047   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
6048   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
6049   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
6050   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
6051   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
6052   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
6053   // Get reciprocal estimate.
6054   // float4 recip = vrecpeq_f32(yf);
6055   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6056                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6057                    Y);
6058   // Because char has a smaller range than uchar, we can actually get away
6059   // without any newton steps.  This requires that we use a weird bias
6060   // of 0xb000, however (again, this has been exhaustively tested).
6061   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
6062   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
6063   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
6064   Y = DAG.getConstant(0xb000, dl, MVT::i32);
6065   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
6066   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6067   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6068   // Convert back to short.
6069   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6070   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6071   return X;
6072 }
6073
6074 static SDValue
6075 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
6076   SDValue N2;
6077   // Convert to float.
6078   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6079   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6080   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6081   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6082   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6083   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6084
6085   // Use reciprocal estimate and one refinement step.
6086   // float4 recip = vrecpeq_f32(yf);
6087   // recip *= vrecpsq_f32(yf, recip);
6088   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6089                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6090                    N1);
6091   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6092                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6093                    N1, N2);
6094   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6095   // Because short has a smaller range than ushort, we can actually get away
6096   // with only a single newton step.  This requires that we use a weird bias
6097   // of 89, however (again, this has been exhaustively tested).
6098   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6099   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6100   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6101   N1 = DAG.getConstant(0x89, dl, MVT::i32);
6102   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6103   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6104   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6105   // Convert back to integer and return.
6106   // return vmovn_s32(vcvt_s32_f32(result));
6107   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6108   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6109   return N0;
6110 }
6111
6112 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6113   EVT VT = Op.getValueType();
6114   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6115          "unexpected type for custom-lowering ISD::SDIV");
6116
6117   SDLoc dl(Op);
6118   SDValue N0 = Op.getOperand(0);
6119   SDValue N1 = Op.getOperand(1);
6120   SDValue N2, N3;
6121
6122   if (VT == MVT::v8i8) {
6123     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6124     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6125
6126     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6127                      DAG.getIntPtrConstant(4, dl));
6128     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6129                      DAG.getIntPtrConstant(4, dl));
6130     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6131                      DAG.getIntPtrConstant(0, dl));
6132     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6133                      DAG.getIntPtrConstant(0, dl));
6134
6135     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6136     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6137
6138     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6139     N0 = LowerCONCAT_VECTORS(N0, DAG);
6140
6141     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6142     return N0;
6143   }
6144   return LowerSDIV_v4i16(N0, N1, dl, DAG);
6145 }
6146
6147 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6148   EVT VT = Op.getValueType();
6149   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6150          "unexpected type for custom-lowering ISD::UDIV");
6151
6152   SDLoc dl(Op);
6153   SDValue N0 = Op.getOperand(0);
6154   SDValue N1 = Op.getOperand(1);
6155   SDValue N2, N3;
6156
6157   if (VT == MVT::v8i8) {
6158     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6159     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6160
6161     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6162                      DAG.getIntPtrConstant(4, dl));
6163     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6164                      DAG.getIntPtrConstant(4, dl));
6165     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6166                      DAG.getIntPtrConstant(0, dl));
6167     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6168                      DAG.getIntPtrConstant(0, dl));
6169
6170     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6171     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6172
6173     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6174     N0 = LowerCONCAT_VECTORS(N0, DAG);
6175
6176     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6177                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
6178                                      MVT::i32),
6179                      N0);
6180     return N0;
6181   }
6182
6183   // v4i16 sdiv ... Convert to float.
6184   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6185   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6186   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6187   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6188   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6189   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6190
6191   // Use reciprocal estimate and two refinement steps.
6192   // float4 recip = vrecpeq_f32(yf);
6193   // recip *= vrecpsq_f32(yf, recip);
6194   // recip *= vrecpsq_f32(yf, recip);
6195   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6196                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6197                    BN1);
6198   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6199                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6200                    BN1, N2);
6201   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6202   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6203                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6204                    BN1, N2);
6205   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6206   // Simply multiplying by the reciprocal estimate can leave us a few ulps
6207   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6208   // and that it will never cause us to return an answer too large).
6209   // float4 result = as_float4(as_int4(xf*recip) + 2);
6210   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6211   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6212   N1 = DAG.getConstant(2, dl, MVT::i32);
6213   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6214   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6215   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6216   // Convert back to integer and return.
6217   // return vmovn_u32(vcvt_s32_f32(result));
6218   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6219   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6220   return N0;
6221 }
6222
6223 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6224   EVT VT = Op.getNode()->getValueType(0);
6225   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6226
6227   unsigned Opc;
6228   bool ExtraOp = false;
6229   switch (Op.getOpcode()) {
6230   default: llvm_unreachable("Invalid code");
6231   case ISD::ADDC: Opc = ARMISD::ADDC; break;
6232   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6233   case ISD::SUBC: Opc = ARMISD::SUBC; break;
6234   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6235   }
6236
6237   if (!ExtraOp)
6238     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6239                        Op.getOperand(1));
6240   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6241                      Op.getOperand(1), Op.getOperand(2));
6242 }
6243
6244 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6245   assert(Subtarget->isTargetDarwin());
6246
6247   // For iOS, we want to call an alternative entry point: __sincos_stret,
6248   // return values are passed via sret.
6249   SDLoc dl(Op);
6250   SDValue Arg = Op.getOperand(0);
6251   EVT ArgVT = Arg.getValueType();
6252   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6253
6254   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6255   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6256
6257   // Pair of floats / doubles used to pass the result.
6258   StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
6259
6260   // Create stack object for sret.
6261   const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
6262   const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
6263   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6264   SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
6265
6266   ArgListTy Args;
6267   ArgListEntry Entry;
6268
6269   Entry.Node = SRet;
6270   Entry.Ty = RetTy->getPointerTo();
6271   Entry.isSExt = false;
6272   Entry.isZExt = false;
6273   Entry.isSRet = true;
6274   Args.push_back(Entry);
6275
6276   Entry.Node = Arg;
6277   Entry.Ty = ArgTy;
6278   Entry.isSExt = false;
6279   Entry.isZExt = false;
6280   Args.push_back(Entry);
6281
6282   const char *LibcallName  = (ArgVT == MVT::f64)
6283   ? "__sincos_stret" : "__sincosf_stret";
6284   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
6285
6286   TargetLowering::CallLoweringInfo CLI(DAG);
6287   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6288     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6289                std::move(Args), 0)
6290     .setDiscardResult();
6291
6292   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6293
6294   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6295                                 MachinePointerInfo(), false, false, false, 0);
6296
6297   // Address of cos field.
6298   SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
6299                             DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
6300   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6301                                 MachinePointerInfo(), false, false, false, 0);
6302
6303   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6304   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6305                      LoadSin.getValue(0), LoadCos.getValue(0));
6306 }
6307
6308 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6309   // Monotonic load/store is legal for all targets
6310   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6311     return Op;
6312
6313   // Acquire/Release load/store is not legal for targets without a
6314   // dmb or equivalent available.
6315   return SDValue();
6316 }
6317
6318 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6319                                     SmallVectorImpl<SDValue> &Results,
6320                                     SelectionDAG &DAG,
6321                                     const ARMSubtarget *Subtarget) {
6322   SDLoc DL(N);
6323   SDValue Cycles32, OutChain;
6324
6325   if (Subtarget->hasPerfMon()) {
6326     // Under Power Management extensions, the cycle-count is:
6327     //    mrc p15, #0, <Rt>, c9, c13, #0
6328     SDValue Ops[] = { N->getOperand(0), // Chain
6329                       DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
6330                       DAG.getConstant(15, DL, MVT::i32),
6331                       DAG.getConstant(0, DL, MVT::i32),
6332                       DAG.getConstant(9, DL, MVT::i32),
6333                       DAG.getConstant(13, DL, MVT::i32),
6334                       DAG.getConstant(0, DL, MVT::i32)
6335     };
6336
6337     Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6338                            DAG.getVTList(MVT::i32, MVT::Other), Ops);
6339     OutChain = Cycles32.getValue(1);
6340   } else {
6341     // Intrinsic is defined to return 0 on unsupported platforms. Technically
6342     // there are older ARM CPUs that have implementation-specific ways of
6343     // obtaining this information (FIXME!).
6344     Cycles32 = DAG.getConstant(0, DL, MVT::i32);
6345     OutChain = DAG.getEntryNode();
6346   }
6347
6348
6349   SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6350                                  Cycles32, DAG.getConstant(0, DL, MVT::i32));
6351   Results.push_back(Cycles64);
6352   Results.push_back(OutChain);
6353 }
6354
6355 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6356   switch (Op.getOpcode()) {
6357   default: llvm_unreachable("Don't know how to custom lower this!");
6358   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6359   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6360   case ISD::GlobalAddress:
6361     switch (Subtarget->getTargetTriple().getObjectFormat()) {
6362     default: llvm_unreachable("unknown object format");
6363     case Triple::COFF:
6364       return LowerGlobalAddressWindows(Op, DAG);
6365     case Triple::ELF:
6366       return LowerGlobalAddressELF(Op, DAG);
6367     case Triple::MachO:
6368       return LowerGlobalAddressDarwin(Op, DAG);
6369     }
6370   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6371   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6372   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6373   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6374   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6375   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6376   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6377   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6378   case ISD::SINT_TO_FP:
6379   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6380   case ISD::FP_TO_SINT:
6381   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6382   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6383   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6384   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6385   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6386   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6387   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6388   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6389                                                                Subtarget);
6390   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6391   case ISD::SHL:
6392   case ISD::SRL:
6393   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6394   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6395   case ISD::SRL_PARTS:
6396   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6397   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6398   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6399   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6400   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6401   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6402   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6403   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6404   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6405   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6406   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6407   case ISD::MUL:           return LowerMUL(Op, DAG);
6408   case ISD::SDIV:          return LowerSDIV(Op, DAG);
6409   case ISD::UDIV:          return LowerUDIV(Op, DAG);
6410   case ISD::ADDC:
6411   case ISD::ADDE:
6412   case ISD::SUBC:
6413   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6414   case ISD::SADDO:
6415   case ISD::UADDO:
6416   case ISD::SSUBO:
6417   case ISD::USUBO:
6418     return LowerXALUO(Op, DAG);
6419   case ISD::ATOMIC_LOAD:
6420   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6421   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6422   case ISD::SDIVREM:
6423   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6424   case ISD::DYNAMIC_STACKALLOC:
6425     if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6426       return LowerDYNAMIC_STACKALLOC(Op, DAG);
6427     llvm_unreachable("Don't know how to custom lower this!");
6428   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6429   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6430   }
6431 }
6432
6433 /// ReplaceNodeResults - Replace the results of node with an illegal result
6434 /// type with new values built out of custom code.
6435 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6436                                            SmallVectorImpl<SDValue>&Results,
6437                                            SelectionDAG &DAG) const {
6438   SDValue Res;
6439   switch (N->getOpcode()) {
6440   default:
6441     llvm_unreachable("Don't know how to custom expand this!");
6442   case ISD::BITCAST:
6443     Res = ExpandBITCAST(N, DAG);
6444     break;
6445   case ISD::SRL:
6446   case ISD::SRA:
6447     Res = Expand64BitShift(N, DAG, Subtarget);
6448     break;
6449   case ISD::READCYCLECOUNTER:
6450     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6451     return;
6452   }
6453   if (Res.getNode())
6454     Results.push_back(Res);
6455 }
6456
6457 //===----------------------------------------------------------------------===//
6458 //                           ARM Scheduler Hooks
6459 //===----------------------------------------------------------------------===//
6460
6461 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6462 /// registers the function context.
6463 void ARMTargetLowering::
6464 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6465                        MachineBasicBlock *DispatchBB, int FI) const {
6466   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6467   DebugLoc dl = MI->getDebugLoc();
6468   MachineFunction *MF = MBB->getParent();
6469   MachineRegisterInfo *MRI = &MF->getRegInfo();
6470   MachineConstantPool *MCP = MF->getConstantPool();
6471   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6472   const Function *F = MF->getFunction();
6473
6474   bool isThumb = Subtarget->isThumb();
6475   bool isThumb2 = Subtarget->isThumb2();
6476
6477   unsigned PCLabelId = AFI->createPICLabelUId();
6478   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6479   ARMConstantPoolValue *CPV =
6480     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6481   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6482
6483   const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
6484                                            : &ARM::GPRRegClass;
6485
6486   // Grab constant pool and fixed stack memory operands.
6487   MachineMemOperand *CPMMO =
6488     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6489                              MachineMemOperand::MOLoad, 4, 4);
6490
6491   MachineMemOperand *FIMMOSt =
6492     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6493                              MachineMemOperand::MOStore, 4, 4);
6494
6495   // Load the address of the dispatch MBB into the jump buffer.
6496   if (isThumb2) {
6497     // Incoming value: jbuf
6498     //   ldr.n  r5, LCPI1_1
6499     //   orr    r5, r5, #1
6500     //   add    r5, pc
6501     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6502     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6503     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6504                    .addConstantPoolIndex(CPI)
6505                    .addMemOperand(CPMMO));
6506     // Set the low bit because of thumb mode.
6507     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6508     AddDefaultCC(
6509       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6510                      .addReg(NewVReg1, RegState::Kill)
6511                      .addImm(0x01)));
6512     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6513     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6514       .addReg(NewVReg2, RegState::Kill)
6515       .addImm(PCLabelId);
6516     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6517                    .addReg(NewVReg3, RegState::Kill)
6518                    .addFrameIndex(FI)
6519                    .addImm(36)  // &jbuf[1] :: pc
6520                    .addMemOperand(FIMMOSt));
6521   } else if (isThumb) {
6522     // Incoming value: jbuf
6523     //   ldr.n  r1, LCPI1_4
6524     //   add    r1, pc
6525     //   mov    r2, #1
6526     //   orrs   r1, r2
6527     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6528     //   str    r1, [r2]
6529     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6530     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6531                    .addConstantPoolIndex(CPI)
6532                    .addMemOperand(CPMMO));
6533     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6534     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6535       .addReg(NewVReg1, RegState::Kill)
6536       .addImm(PCLabelId);
6537     // Set the low bit because of thumb mode.
6538     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6539     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6540                    .addReg(ARM::CPSR, RegState::Define)
6541                    .addImm(1));
6542     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6543     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6544                    .addReg(ARM::CPSR, RegState::Define)
6545                    .addReg(NewVReg2, RegState::Kill)
6546                    .addReg(NewVReg3, RegState::Kill));
6547     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6548     BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
6549             .addFrameIndex(FI)
6550             .addImm(36); // &jbuf[1] :: pc
6551     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6552                    .addReg(NewVReg4, RegState::Kill)
6553                    .addReg(NewVReg5, RegState::Kill)
6554                    .addImm(0)
6555                    .addMemOperand(FIMMOSt));
6556   } else {
6557     // Incoming value: jbuf
6558     //   ldr  r1, LCPI1_1
6559     //   add  r1, pc, r1
6560     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6561     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6562     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6563                    .addConstantPoolIndex(CPI)
6564                    .addImm(0)
6565                    .addMemOperand(CPMMO));
6566     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6567     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6568                    .addReg(NewVReg1, RegState::Kill)
6569                    .addImm(PCLabelId));
6570     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6571                    .addReg(NewVReg2, RegState::Kill)
6572                    .addFrameIndex(FI)
6573                    .addImm(36)  // &jbuf[1] :: pc
6574                    .addMemOperand(FIMMOSt));
6575   }
6576 }
6577
6578 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr *MI,
6579                                               MachineBasicBlock *MBB) const {
6580   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6581   DebugLoc dl = MI->getDebugLoc();
6582   MachineFunction *MF = MBB->getParent();
6583   MachineRegisterInfo *MRI = &MF->getRegInfo();
6584   MachineFrameInfo *MFI = MF->getFrameInfo();
6585   int FI = MFI->getFunctionContextIndex();
6586
6587   const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
6588                                                         : &ARM::GPRnopcRegClass;
6589
6590   // Get a mapping of the call site numbers to all of the landing pads they're
6591   // associated with.
6592   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6593   unsigned MaxCSNum = 0;
6594   MachineModuleInfo &MMI = MF->getMMI();
6595   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6596        ++BB) {
6597     if (!BB->isLandingPad()) continue;
6598
6599     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6600     // pad.
6601     for (MachineBasicBlock::iterator
6602            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6603       if (!II->isEHLabel()) continue;
6604
6605       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6606       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6607
6608       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6609       for (SmallVectorImpl<unsigned>::iterator
6610              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6611            CSI != CSE; ++CSI) {
6612         CallSiteNumToLPad[*CSI].push_back(BB);
6613         MaxCSNum = std::max(MaxCSNum, *CSI);
6614       }
6615       break;
6616     }
6617   }
6618
6619   // Get an ordered list of the machine basic blocks for the jump table.
6620   std::vector<MachineBasicBlock*> LPadList;
6621   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6622   LPadList.reserve(CallSiteNumToLPad.size());
6623   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6624     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6625     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6626            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6627       LPadList.push_back(*II);
6628       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6629     }
6630   }
6631
6632   assert(!LPadList.empty() &&
6633          "No landing pad destinations for the dispatch jump table!");
6634
6635   // Create the jump table and associated information.
6636   MachineJumpTableInfo *JTI =
6637     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6638   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6639   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6640
6641   // Create the MBBs for the dispatch code.
6642
6643   // Shove the dispatch's address into the return slot in the function context.
6644   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6645   DispatchBB->setIsLandingPad();
6646
6647   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6648   unsigned trap_opcode;
6649   if (Subtarget->isThumb())
6650     trap_opcode = ARM::tTRAP;
6651   else
6652     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6653
6654   BuildMI(TrapBB, dl, TII->get(trap_opcode));
6655   DispatchBB->addSuccessor(TrapBB);
6656
6657   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6658   DispatchBB->addSuccessor(DispContBB);
6659
6660   // Insert and MBBs.
6661   MF->insert(MF->end(), DispatchBB);
6662   MF->insert(MF->end(), DispContBB);
6663   MF->insert(MF->end(), TrapBB);
6664
6665   // Insert code into the entry block that creates and registers the function
6666   // context.
6667   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6668
6669   MachineMemOperand *FIMMOLd =
6670     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6671                              MachineMemOperand::MOLoad |
6672                              MachineMemOperand::MOVolatile, 4, 4);
6673
6674   MachineInstrBuilder MIB;
6675   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6676
6677   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6678   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6679
6680   // Add a register mask with no preserved registers.  This results in all
6681   // registers being marked as clobbered.
6682   MIB.addRegMask(RI.getNoPreservedMask());
6683
6684   unsigned NumLPads = LPadList.size();
6685   if (Subtarget->isThumb2()) {
6686     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6687     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6688                    .addFrameIndex(FI)
6689                    .addImm(4)
6690                    .addMemOperand(FIMMOLd));
6691
6692     if (NumLPads < 256) {
6693       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6694                      .addReg(NewVReg1)
6695                      .addImm(LPadList.size()));
6696     } else {
6697       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6698       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6699                      .addImm(NumLPads & 0xFFFF));
6700
6701       unsigned VReg2 = VReg1;
6702       if ((NumLPads & 0xFFFF0000) != 0) {
6703         VReg2 = MRI->createVirtualRegister(TRC);
6704         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6705                        .addReg(VReg1)
6706                        .addImm(NumLPads >> 16));
6707       }
6708
6709       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6710                      .addReg(NewVReg1)
6711                      .addReg(VReg2));
6712     }
6713
6714     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6715       .addMBB(TrapBB)
6716       .addImm(ARMCC::HI)
6717       .addReg(ARM::CPSR);
6718
6719     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6720     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6721                    .addJumpTableIndex(MJTI));
6722
6723     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6724     AddDefaultCC(
6725       AddDefaultPred(
6726         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6727         .addReg(NewVReg3, RegState::Kill)
6728         .addReg(NewVReg1)
6729         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6730
6731     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6732       .addReg(NewVReg4, RegState::Kill)
6733       .addReg(NewVReg1)
6734       .addJumpTableIndex(MJTI);
6735   } else if (Subtarget->isThumb()) {
6736     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6737     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6738                    .addFrameIndex(FI)
6739                    .addImm(1)
6740                    .addMemOperand(FIMMOLd));
6741
6742     if (NumLPads < 256) {
6743       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6744                      .addReg(NewVReg1)
6745                      .addImm(NumLPads));
6746     } else {
6747       MachineConstantPool *ConstantPool = MF->getConstantPool();
6748       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6749       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6750
6751       // MachineConstantPool wants an explicit alignment.
6752       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6753       if (Align == 0)
6754         Align = getDataLayout()->getTypeAllocSize(C->getType());
6755       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6756
6757       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6758       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6759                      .addReg(VReg1, RegState::Define)
6760                      .addConstantPoolIndex(Idx));
6761       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6762                      .addReg(NewVReg1)
6763                      .addReg(VReg1));
6764     }
6765
6766     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6767       .addMBB(TrapBB)
6768       .addImm(ARMCC::HI)
6769       .addReg(ARM::CPSR);
6770
6771     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6772     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6773                    .addReg(ARM::CPSR, RegState::Define)
6774                    .addReg(NewVReg1)
6775                    .addImm(2));
6776
6777     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6778     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6779                    .addJumpTableIndex(MJTI));
6780
6781     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6782     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6783                    .addReg(ARM::CPSR, RegState::Define)
6784                    .addReg(NewVReg2, RegState::Kill)
6785                    .addReg(NewVReg3));
6786
6787     MachineMemOperand *JTMMOLd =
6788       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6789                                MachineMemOperand::MOLoad, 4, 4);
6790
6791     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6792     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6793                    .addReg(NewVReg4, RegState::Kill)
6794                    .addImm(0)
6795                    .addMemOperand(JTMMOLd));
6796
6797     unsigned NewVReg6 = NewVReg5;
6798     if (RelocM == Reloc::PIC_) {
6799       NewVReg6 = MRI->createVirtualRegister(TRC);
6800       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6801                      .addReg(ARM::CPSR, RegState::Define)
6802                      .addReg(NewVReg5, RegState::Kill)
6803                      .addReg(NewVReg3));
6804     }
6805
6806     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6807       .addReg(NewVReg6, RegState::Kill)
6808       .addJumpTableIndex(MJTI);
6809   } else {
6810     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6811     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6812                    .addFrameIndex(FI)
6813                    .addImm(4)
6814                    .addMemOperand(FIMMOLd));
6815
6816     if (NumLPads < 256) {
6817       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6818                      .addReg(NewVReg1)
6819                      .addImm(NumLPads));
6820     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6821       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6822       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6823                      .addImm(NumLPads & 0xFFFF));
6824
6825       unsigned VReg2 = VReg1;
6826       if ((NumLPads & 0xFFFF0000) != 0) {
6827         VReg2 = MRI->createVirtualRegister(TRC);
6828         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6829                        .addReg(VReg1)
6830                        .addImm(NumLPads >> 16));
6831       }
6832
6833       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6834                      .addReg(NewVReg1)
6835                      .addReg(VReg2));
6836     } else {
6837       MachineConstantPool *ConstantPool = MF->getConstantPool();
6838       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6839       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6840
6841       // MachineConstantPool wants an explicit alignment.
6842       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6843       if (Align == 0)
6844         Align = getDataLayout()->getTypeAllocSize(C->getType());
6845       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6846
6847       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6848       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6849                      .addReg(VReg1, RegState::Define)
6850                      .addConstantPoolIndex(Idx)
6851                      .addImm(0));
6852       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6853                      .addReg(NewVReg1)
6854                      .addReg(VReg1, RegState::Kill));
6855     }
6856
6857     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6858       .addMBB(TrapBB)
6859       .addImm(ARMCC::HI)
6860       .addReg(ARM::CPSR);
6861
6862     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6863     AddDefaultCC(
6864       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6865                      .addReg(NewVReg1)
6866                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6867     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6868     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6869                    .addJumpTableIndex(MJTI));
6870
6871     MachineMemOperand *JTMMOLd =
6872       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6873                                MachineMemOperand::MOLoad, 4, 4);
6874     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6875     AddDefaultPred(
6876       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6877       .addReg(NewVReg3, RegState::Kill)
6878       .addReg(NewVReg4)
6879       .addImm(0)
6880       .addMemOperand(JTMMOLd));
6881
6882     if (RelocM == Reloc::PIC_) {
6883       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6884         .addReg(NewVReg5, RegState::Kill)
6885         .addReg(NewVReg4)
6886         .addJumpTableIndex(MJTI);
6887     } else {
6888       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6889         .addReg(NewVReg5, RegState::Kill)
6890         .addJumpTableIndex(MJTI);
6891     }
6892   }
6893
6894   // Add the jump table entries as successors to the MBB.
6895   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6896   for (std::vector<MachineBasicBlock*>::iterator
6897          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6898     MachineBasicBlock *CurMBB = *I;
6899     if (SeenMBBs.insert(CurMBB).second)
6900       DispContBB->addSuccessor(CurMBB);
6901   }
6902
6903   // N.B. the order the invoke BBs are processed in doesn't matter here.
6904   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
6905   SmallVector<MachineBasicBlock*, 64> MBBLPads;
6906   for (MachineBasicBlock *BB : InvokeBBs) {
6907
6908     // Remove the landing pad successor from the invoke block and replace it
6909     // with the new dispatch block.
6910     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6911                                                   BB->succ_end());
6912     while (!Successors.empty()) {
6913       MachineBasicBlock *SMBB = Successors.pop_back_val();
6914       if (SMBB->isLandingPad()) {
6915         BB->removeSuccessor(SMBB);
6916         MBBLPads.push_back(SMBB);
6917       }
6918     }
6919
6920     BB->addSuccessor(DispatchBB);
6921
6922     // Find the invoke call and mark all of the callee-saved registers as
6923     // 'implicit defined' so that they're spilled. This prevents code from
6924     // moving instructions to before the EH block, where they will never be
6925     // executed.
6926     for (MachineBasicBlock::reverse_iterator
6927            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6928       if (!II->isCall()) continue;
6929
6930       DenseMap<unsigned, bool> DefRegs;
6931       for (MachineInstr::mop_iterator
6932              OI = II->operands_begin(), OE = II->operands_end();
6933            OI != OE; ++OI) {
6934         if (!OI->isReg()) continue;
6935         DefRegs[OI->getReg()] = true;
6936       }
6937
6938       MachineInstrBuilder MIB(*MF, &*II);
6939
6940       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6941         unsigned Reg = SavedRegs[i];
6942         if (Subtarget->isThumb2() &&
6943             !ARM::tGPRRegClass.contains(Reg) &&
6944             !ARM::hGPRRegClass.contains(Reg))
6945           continue;
6946         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6947           continue;
6948         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6949           continue;
6950         if (!DefRegs[Reg])
6951           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6952       }
6953
6954       break;
6955     }
6956   }
6957
6958   // Mark all former landing pads as non-landing pads. The dispatch is the only
6959   // landing pad now.
6960   for (SmallVectorImpl<MachineBasicBlock*>::iterator
6961          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6962     (*I)->setIsLandingPad(false);
6963
6964   // The instruction is gone now.
6965   MI->eraseFromParent();
6966 }
6967
6968 static
6969 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6970   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6971        E = MBB->succ_end(); I != E; ++I)
6972     if (*I != Succ)
6973       return *I;
6974   llvm_unreachable("Expecting a BB with two successors!");
6975 }
6976
6977 /// Return the load opcode for a given load size. If load size >= 8,
6978 /// neon opcode will be returned.
6979 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
6980   if (LdSize >= 8)
6981     return LdSize == 16 ? ARM::VLD1q32wb_fixed
6982                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
6983   if (IsThumb1)
6984     return LdSize == 4 ? ARM::tLDRi
6985                        : LdSize == 2 ? ARM::tLDRHi
6986                                      : LdSize == 1 ? ARM::tLDRBi : 0;
6987   if (IsThumb2)
6988     return LdSize == 4 ? ARM::t2LDR_POST
6989                        : LdSize == 2 ? ARM::t2LDRH_POST
6990                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
6991   return LdSize == 4 ? ARM::LDR_POST_IMM
6992                      : LdSize == 2 ? ARM::LDRH_POST
6993                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
6994 }
6995
6996 /// Return the store opcode for a given store size. If store size >= 8,
6997 /// neon opcode will be returned.
6998 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
6999   if (StSize >= 8)
7000     return StSize == 16 ? ARM::VST1q32wb_fixed
7001                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7002   if (IsThumb1)
7003     return StSize == 4 ? ARM::tSTRi
7004                        : StSize == 2 ? ARM::tSTRHi
7005                                      : StSize == 1 ? ARM::tSTRBi : 0;
7006   if (IsThumb2)
7007     return StSize == 4 ? ARM::t2STR_POST
7008                        : StSize == 2 ? ARM::t2STRH_POST
7009                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
7010   return StSize == 4 ? ARM::STR_POST_IMM
7011                      : StSize == 2 ? ARM::STRH_POST
7012                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7013 }
7014
7015 /// Emit a post-increment load operation with given size. The instructions
7016 /// will be added to BB at Pos.
7017 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7018                        const TargetInstrInfo *TII, DebugLoc dl,
7019                        unsigned LdSize, unsigned Data, unsigned AddrIn,
7020                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7021   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7022   assert(LdOpc != 0 && "Should have a load opcode");
7023   if (LdSize >= 8) {
7024     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7025                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7026                        .addImm(0));
7027   } else if (IsThumb1) {
7028     // load + update AddrIn
7029     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7030                        .addReg(AddrIn).addImm(0));
7031     MachineInstrBuilder MIB =
7032         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7033     MIB = AddDefaultT1CC(MIB);
7034     MIB.addReg(AddrIn).addImm(LdSize);
7035     AddDefaultPred(MIB);
7036   } else if (IsThumb2) {
7037     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7038                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7039                        .addImm(LdSize));
7040   } else { // arm
7041     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7042                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7043                        .addReg(0).addImm(LdSize));
7044   }
7045 }
7046
7047 /// Emit a post-increment store operation with given size. The instructions
7048 /// will be added to BB at Pos.
7049 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7050                        const TargetInstrInfo *TII, DebugLoc dl,
7051                        unsigned StSize, unsigned Data, unsigned AddrIn,
7052                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7053   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7054   assert(StOpc != 0 && "Should have a store opcode");
7055   if (StSize >= 8) {
7056     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7057                        .addReg(AddrIn).addImm(0).addReg(Data));
7058   } else if (IsThumb1) {
7059     // store + update AddrIn
7060     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7061                        .addReg(AddrIn).addImm(0));
7062     MachineInstrBuilder MIB =
7063         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7064     MIB = AddDefaultT1CC(MIB);
7065     MIB.addReg(AddrIn).addImm(StSize);
7066     AddDefaultPred(MIB);
7067   } else if (IsThumb2) {
7068     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7069                        .addReg(Data).addReg(AddrIn).addImm(StSize));
7070   } else { // arm
7071     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7072                        .addReg(Data).addReg(AddrIn).addReg(0)
7073                        .addImm(StSize));
7074   }
7075 }
7076
7077 MachineBasicBlock *
7078 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7079                                    MachineBasicBlock *BB) const {
7080   // This pseudo instruction has 3 operands: dst, src, size
7081   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7082   // Otherwise, we will generate unrolled scalar copies.
7083   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7084   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7085   MachineFunction::iterator It = BB;
7086   ++It;
7087
7088   unsigned dest = MI->getOperand(0).getReg();
7089   unsigned src = MI->getOperand(1).getReg();
7090   unsigned SizeVal = MI->getOperand(2).getImm();
7091   unsigned Align = MI->getOperand(3).getImm();
7092   DebugLoc dl = MI->getDebugLoc();
7093
7094   MachineFunction *MF = BB->getParent();
7095   MachineRegisterInfo &MRI = MF->getRegInfo();
7096   unsigned UnitSize = 0;
7097   const TargetRegisterClass *TRC = nullptr;
7098   const TargetRegisterClass *VecTRC = nullptr;
7099
7100   bool IsThumb1 = Subtarget->isThumb1Only();
7101   bool IsThumb2 = Subtarget->isThumb2();
7102
7103   if (Align & 1) {
7104     UnitSize = 1;
7105   } else if (Align & 2) {
7106     UnitSize = 2;
7107   } else {
7108     // Check whether we can use NEON instructions.
7109     if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
7110         Subtarget->hasNEON()) {
7111       if ((Align % 16 == 0) && SizeVal >= 16)
7112         UnitSize = 16;
7113       else if ((Align % 8 == 0) && SizeVal >= 8)
7114         UnitSize = 8;
7115     }
7116     // Can't use NEON instructions.
7117     if (UnitSize == 0)
7118       UnitSize = 4;
7119   }
7120
7121   // Select the correct opcode and register class for unit size load/store
7122   bool IsNeon = UnitSize >= 8;
7123   TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
7124   if (IsNeon)
7125     VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
7126                             : UnitSize == 8 ? &ARM::DPRRegClass
7127                                             : nullptr;
7128
7129   unsigned BytesLeft = SizeVal % UnitSize;
7130   unsigned LoopSize = SizeVal - BytesLeft;
7131
7132   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7133     // Use LDR and STR to copy.
7134     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7135     // [destOut] = STR_POST(scratch, destIn, UnitSize)
7136     unsigned srcIn = src;
7137     unsigned destIn = dest;
7138     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7139       unsigned srcOut = MRI.createVirtualRegister(TRC);
7140       unsigned destOut = MRI.createVirtualRegister(TRC);
7141       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7142       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7143                  IsThumb1, IsThumb2);
7144       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7145                  IsThumb1, IsThumb2);
7146       srcIn = srcOut;
7147       destIn = destOut;
7148     }
7149
7150     // Handle the leftover bytes with LDRB and STRB.
7151     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7152     // [destOut] = STRB_POST(scratch, destIn, 1)
7153     for (unsigned i = 0; i < BytesLeft; i++) {
7154       unsigned srcOut = MRI.createVirtualRegister(TRC);
7155       unsigned destOut = MRI.createVirtualRegister(TRC);
7156       unsigned scratch = MRI.createVirtualRegister(TRC);
7157       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7158                  IsThumb1, IsThumb2);
7159       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7160                  IsThumb1, IsThumb2);
7161       srcIn = srcOut;
7162       destIn = destOut;
7163     }
7164     MI->eraseFromParent();   // The instruction is gone now.
7165     return BB;
7166   }
7167
7168   // Expand the pseudo op to a loop.
7169   // thisMBB:
7170   //   ...
7171   //   movw varEnd, # --> with thumb2
7172   //   movt varEnd, #
7173   //   ldrcp varEnd, idx --> without thumb2
7174   //   fallthrough --> loopMBB
7175   // loopMBB:
7176   //   PHI varPhi, varEnd, varLoop
7177   //   PHI srcPhi, src, srcLoop
7178   //   PHI destPhi, dst, destLoop
7179   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7180   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7181   //   subs varLoop, varPhi, #UnitSize
7182   //   bne loopMBB
7183   //   fallthrough --> exitMBB
7184   // exitMBB:
7185   //   epilogue to handle left-over bytes
7186   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7187   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7188   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7189   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7190   MF->insert(It, loopMBB);
7191   MF->insert(It, exitMBB);
7192
7193   // Transfer the remainder of BB and its successor edges to exitMBB.
7194   exitMBB->splice(exitMBB->begin(), BB,
7195                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7196   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7197
7198   // Load an immediate to varEnd.
7199   unsigned varEnd = MRI.createVirtualRegister(TRC);
7200   if (Subtarget->useMovt(*MF)) {
7201     unsigned Vtmp = varEnd;
7202     if ((LoopSize & 0xFFFF0000) != 0)
7203       Vtmp = MRI.createVirtualRegister(TRC);
7204     AddDefaultPred(BuildMI(BB, dl,
7205                            TII->get(IsThumb2 ? ARM::t2MOVi16 : ARM::MOVi16),
7206                            Vtmp).addImm(LoopSize & 0xFFFF));
7207
7208     if ((LoopSize & 0xFFFF0000) != 0)
7209       AddDefaultPred(BuildMI(BB, dl,
7210                              TII->get(IsThumb2 ? ARM::t2MOVTi16 : ARM::MOVTi16),
7211                              varEnd)
7212                          .addReg(Vtmp)
7213                          .addImm(LoopSize >> 16));
7214   } else {
7215     MachineConstantPool *ConstantPool = MF->getConstantPool();
7216     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7217     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7218
7219     // MachineConstantPool wants an explicit alignment.
7220     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7221     if (Align == 0)
7222       Align = getDataLayout()->getTypeAllocSize(C->getType());
7223     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7224
7225     if (IsThumb1)
7226       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7227           varEnd, RegState::Define).addConstantPoolIndex(Idx));
7228     else
7229       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7230           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7231   }
7232   BB->addSuccessor(loopMBB);
7233
7234   // Generate the loop body:
7235   //   varPhi = PHI(varLoop, varEnd)
7236   //   srcPhi = PHI(srcLoop, src)
7237   //   destPhi = PHI(destLoop, dst)
7238   MachineBasicBlock *entryBB = BB;
7239   BB = loopMBB;
7240   unsigned varLoop = MRI.createVirtualRegister(TRC);
7241   unsigned varPhi = MRI.createVirtualRegister(TRC);
7242   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7243   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7244   unsigned destLoop = MRI.createVirtualRegister(TRC);
7245   unsigned destPhi = MRI.createVirtualRegister(TRC);
7246
7247   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7248     .addReg(varLoop).addMBB(loopMBB)
7249     .addReg(varEnd).addMBB(entryBB);
7250   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7251     .addReg(srcLoop).addMBB(loopMBB)
7252     .addReg(src).addMBB(entryBB);
7253   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7254     .addReg(destLoop).addMBB(loopMBB)
7255     .addReg(dest).addMBB(entryBB);
7256
7257   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7258   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7259   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7260   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7261              IsThumb1, IsThumb2);
7262   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7263              IsThumb1, IsThumb2);
7264
7265   // Decrement loop variable by UnitSize.
7266   if (IsThumb1) {
7267     MachineInstrBuilder MIB =
7268         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7269     MIB = AddDefaultT1CC(MIB);
7270     MIB.addReg(varPhi).addImm(UnitSize);
7271     AddDefaultPred(MIB);
7272   } else {
7273     MachineInstrBuilder MIB =
7274         BuildMI(*BB, BB->end(), dl,
7275                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7276     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7277     MIB->getOperand(5).setReg(ARM::CPSR);
7278     MIB->getOperand(5).setIsDef(true);
7279   }
7280   BuildMI(*BB, BB->end(), dl,
7281           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7282       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7283
7284   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7285   BB->addSuccessor(loopMBB);
7286   BB->addSuccessor(exitMBB);
7287
7288   // Add epilogue to handle BytesLeft.
7289   BB = exitMBB;
7290   MachineInstr *StartOfExit = exitMBB->begin();
7291
7292   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7293   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7294   unsigned srcIn = srcLoop;
7295   unsigned destIn = destLoop;
7296   for (unsigned i = 0; i < BytesLeft; i++) {
7297     unsigned srcOut = MRI.createVirtualRegister(TRC);
7298     unsigned destOut = MRI.createVirtualRegister(TRC);
7299     unsigned scratch = MRI.createVirtualRegister(TRC);
7300     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7301                IsThumb1, IsThumb2);
7302     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7303                IsThumb1, IsThumb2);
7304     srcIn = srcOut;
7305     destIn = destOut;
7306   }
7307
7308   MI->eraseFromParent();   // The instruction is gone now.
7309   return BB;
7310 }
7311
7312 MachineBasicBlock *
7313 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7314                                        MachineBasicBlock *MBB) const {
7315   const TargetMachine &TM = getTargetMachine();
7316   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
7317   DebugLoc DL = MI->getDebugLoc();
7318
7319   assert(Subtarget->isTargetWindows() &&
7320          "__chkstk is only supported on Windows");
7321   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7322
7323   // __chkstk takes the number of words to allocate on the stack in R4, and
7324   // returns the stack adjustment in number of bytes in R4.  This will not
7325   // clober any other registers (other than the obvious lr).
7326   //
7327   // Although, technically, IP should be considered a register which may be
7328   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
7329   // thumb-2 environment, so there is no interworking required.  As a result, we
7330   // do not expect a veneer to be emitted by the linker, clobbering IP.
7331   //
7332   // Each module receives its own copy of __chkstk, so no import thunk is
7333   // required, again, ensuring that IP is not clobbered.
7334   //
7335   // Finally, although some linkers may theoretically provide a trampoline for
7336   // out of range calls (which is quite common due to a 32M range limitation of
7337   // branches for Thumb), we can generate the long-call version via
7338   // -mcmodel=large, alleviating the need for the trampoline which may clobber
7339   // IP.
7340
7341   switch (TM.getCodeModel()) {
7342   case CodeModel::Small:
7343   case CodeModel::Medium:
7344   case CodeModel::Default:
7345   case CodeModel::Kernel:
7346     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7347       .addImm((unsigned)ARMCC::AL).addReg(0)
7348       .addExternalSymbol("__chkstk")
7349       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7350       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7351       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7352     break;
7353   case CodeModel::Large:
7354   case CodeModel::JITDefault: {
7355     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7356     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7357
7358     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7359       .addExternalSymbol("__chkstk");
7360     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7361       .addImm((unsigned)ARMCC::AL).addReg(0)
7362       .addReg(Reg, RegState::Kill)
7363       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7364       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7365       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7366     break;
7367   }
7368   }
7369
7370   AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7371                                       ARM::SP)
7372                               .addReg(ARM::SP).addReg(ARM::R4)));
7373
7374   MI->eraseFromParent();
7375   return MBB;
7376 }
7377
7378 MachineBasicBlock *
7379 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7380                                                MachineBasicBlock *BB) const {
7381   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7382   DebugLoc dl = MI->getDebugLoc();
7383   bool isThumb2 = Subtarget->isThumb2();
7384   switch (MI->getOpcode()) {
7385   default: {
7386     MI->dump();
7387     llvm_unreachable("Unexpected instr type to insert");
7388   }
7389   // The Thumb2 pre-indexed stores have the same MI operands, they just
7390   // define them differently in the .td files from the isel patterns, so
7391   // they need pseudos.
7392   case ARM::t2STR_preidx:
7393     MI->setDesc(TII->get(ARM::t2STR_PRE));
7394     return BB;
7395   case ARM::t2STRB_preidx:
7396     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7397     return BB;
7398   case ARM::t2STRH_preidx:
7399     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7400     return BB;
7401
7402   case ARM::STRi_preidx:
7403   case ARM::STRBi_preidx: {
7404     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7405       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7406     // Decode the offset.
7407     unsigned Offset = MI->getOperand(4).getImm();
7408     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7409     Offset = ARM_AM::getAM2Offset(Offset);
7410     if (isSub)
7411       Offset = -Offset;
7412
7413     MachineMemOperand *MMO = *MI->memoperands_begin();
7414     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7415       .addOperand(MI->getOperand(0))  // Rn_wb
7416       .addOperand(MI->getOperand(1))  // Rt
7417       .addOperand(MI->getOperand(2))  // Rn
7418       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7419       .addOperand(MI->getOperand(5))  // pred
7420       .addOperand(MI->getOperand(6))
7421       .addMemOperand(MMO);
7422     MI->eraseFromParent();
7423     return BB;
7424   }
7425   case ARM::STRr_preidx:
7426   case ARM::STRBr_preidx:
7427   case ARM::STRH_preidx: {
7428     unsigned NewOpc;
7429     switch (MI->getOpcode()) {
7430     default: llvm_unreachable("unexpected opcode!");
7431     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7432     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7433     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7434     }
7435     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7436     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7437       MIB.addOperand(MI->getOperand(i));
7438     MI->eraseFromParent();
7439     return BB;
7440   }
7441
7442   case ARM::tMOVCCr_pseudo: {
7443     // To "insert" a SELECT_CC instruction, we actually have to insert the
7444     // diamond control-flow pattern.  The incoming instruction knows the
7445     // destination vreg to set, the condition code register to branch on, the
7446     // true/false values to select between, and a branch opcode to use.
7447     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7448     MachineFunction::iterator It = BB;
7449     ++It;
7450
7451     //  thisMBB:
7452     //  ...
7453     //   TrueVal = ...
7454     //   cmpTY ccX, r1, r2
7455     //   bCC copy1MBB
7456     //   fallthrough --> copy0MBB
7457     MachineBasicBlock *thisMBB  = BB;
7458     MachineFunction *F = BB->getParent();
7459     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7460     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7461     F->insert(It, copy0MBB);
7462     F->insert(It, sinkMBB);
7463
7464     // Transfer the remainder of BB and its successor edges to sinkMBB.
7465     sinkMBB->splice(sinkMBB->begin(), BB,
7466                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7467     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7468
7469     BB->addSuccessor(copy0MBB);
7470     BB->addSuccessor(sinkMBB);
7471
7472     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7473       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7474
7475     //  copy0MBB:
7476     //   %FalseValue = ...
7477     //   # fallthrough to sinkMBB
7478     BB = copy0MBB;
7479
7480     // Update machine-CFG edges
7481     BB->addSuccessor(sinkMBB);
7482
7483     //  sinkMBB:
7484     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7485     //  ...
7486     BB = sinkMBB;
7487     BuildMI(*BB, BB->begin(), dl,
7488             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7489       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7490       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7491
7492     MI->eraseFromParent();   // The pseudo instruction is gone now.
7493     return BB;
7494   }
7495
7496   case ARM::BCCi64:
7497   case ARM::BCCZi64: {
7498     // If there is an unconditional branch to the other successor, remove it.
7499     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7500
7501     // Compare both parts that make up the double comparison separately for
7502     // equality.
7503     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7504
7505     unsigned LHS1 = MI->getOperand(1).getReg();
7506     unsigned LHS2 = MI->getOperand(2).getReg();
7507     if (RHSisZero) {
7508       AddDefaultPred(BuildMI(BB, dl,
7509                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7510                      .addReg(LHS1).addImm(0));
7511       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7512         .addReg(LHS2).addImm(0)
7513         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7514     } else {
7515       unsigned RHS1 = MI->getOperand(3).getReg();
7516       unsigned RHS2 = MI->getOperand(4).getReg();
7517       AddDefaultPred(BuildMI(BB, dl,
7518                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7519                      .addReg(LHS1).addReg(RHS1));
7520       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7521         .addReg(LHS2).addReg(RHS2)
7522         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7523     }
7524
7525     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7526     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7527     if (MI->getOperand(0).getImm() == ARMCC::NE)
7528       std::swap(destMBB, exitMBB);
7529
7530     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7531       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7532     if (isThumb2)
7533       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7534     else
7535       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7536
7537     MI->eraseFromParent();   // The pseudo instruction is gone now.
7538     return BB;
7539   }
7540
7541   case ARM::Int_eh_sjlj_setjmp:
7542   case ARM::Int_eh_sjlj_setjmp_nofp:
7543   case ARM::tInt_eh_sjlj_setjmp:
7544   case ARM::t2Int_eh_sjlj_setjmp:
7545   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7546     EmitSjLjDispatchBlock(MI, BB);
7547     return BB;
7548
7549   case ARM::ABS:
7550   case ARM::t2ABS: {
7551     // To insert an ABS instruction, we have to insert the
7552     // diamond control-flow pattern.  The incoming instruction knows the
7553     // source vreg to test against 0, the destination vreg to set,
7554     // the condition code register to branch on, the
7555     // true/false values to select between, and a branch opcode to use.
7556     // It transforms
7557     //     V1 = ABS V0
7558     // into
7559     //     V2 = MOVS V0
7560     //     BCC                      (branch to SinkBB if V0 >= 0)
7561     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7562     //     SinkBB: V1 = PHI(V2, V3)
7563     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7564     MachineFunction::iterator BBI = BB;
7565     ++BBI;
7566     MachineFunction *Fn = BB->getParent();
7567     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7568     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7569     Fn->insert(BBI, RSBBB);
7570     Fn->insert(BBI, SinkBB);
7571
7572     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7573     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7574     bool ABSSrcKIll = MI->getOperand(1).isKill();
7575     bool isThumb2 = Subtarget->isThumb2();
7576     MachineRegisterInfo &MRI = Fn->getRegInfo();
7577     // In Thumb mode S must not be specified if source register is the SP or
7578     // PC and if destination register is the SP, so restrict register class
7579     unsigned NewRsbDstReg =
7580       MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
7581
7582     // Transfer the remainder of BB and its successor edges to sinkMBB.
7583     SinkBB->splice(SinkBB->begin(), BB,
7584                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
7585     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7586
7587     BB->addSuccessor(RSBBB);
7588     BB->addSuccessor(SinkBB);
7589
7590     // fall through to SinkMBB
7591     RSBBB->addSuccessor(SinkBB);
7592
7593     // insert a cmp at the end of BB
7594     AddDefaultPred(BuildMI(BB, dl,
7595                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7596                    .addReg(ABSSrcReg).addImm(0));
7597
7598     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7599     BuildMI(BB, dl,
7600       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7601       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7602
7603     // insert rsbri in RSBBB
7604     // Note: BCC and rsbri will be converted into predicated rsbmi
7605     // by if-conversion pass
7606     BuildMI(*RSBBB, RSBBB->begin(), dl,
7607       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7608       .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
7609       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7610
7611     // insert PHI in SinkBB,
7612     // reuse ABSDstReg to not change uses of ABS instruction
7613     BuildMI(*SinkBB, SinkBB->begin(), dl,
7614       TII->get(ARM::PHI), ABSDstReg)
7615       .addReg(NewRsbDstReg).addMBB(RSBBB)
7616       .addReg(ABSSrcReg).addMBB(BB);
7617
7618     // remove ABS instruction
7619     MI->eraseFromParent();
7620
7621     // return last added BB
7622     return SinkBB;
7623   }
7624   case ARM::COPY_STRUCT_BYVAL_I32:
7625     ++NumLoopByVals;
7626     return EmitStructByval(MI, BB);
7627   case ARM::WIN__CHKSTK:
7628     return EmitLowered__chkstk(MI, BB);
7629   }
7630 }
7631
7632 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7633                                                       SDNode *Node) const {
7634   const MCInstrDesc *MCID = &MI->getDesc();
7635   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7636   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7637   // operand is still set to noreg. If needed, set the optional operand's
7638   // register to CPSR, and remove the redundant implicit def.
7639   //
7640   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7641
7642   // Rename pseudo opcodes.
7643   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7644   if (NewOpc) {
7645     const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
7646     MCID = &TII->get(NewOpc);
7647
7648     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7649            "converted opcode should be the same except for cc_out");
7650
7651     MI->setDesc(*MCID);
7652
7653     // Add the optional cc_out operand
7654     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7655   }
7656   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7657
7658   // Any ARM instruction that sets the 's' bit should specify an optional
7659   // "cc_out" operand in the last operand position.
7660   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7661     assert(!NewOpc && "Optional cc_out operand required");
7662     return;
7663   }
7664   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7665   // since we already have an optional CPSR def.
7666   bool definesCPSR = false;
7667   bool deadCPSR = false;
7668   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7669        i != e; ++i) {
7670     const MachineOperand &MO = MI->getOperand(i);
7671     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7672       definesCPSR = true;
7673       if (MO.isDead())
7674         deadCPSR = true;
7675       MI->RemoveOperand(i);
7676       break;
7677     }
7678   }
7679   if (!definesCPSR) {
7680     assert(!NewOpc && "Optional cc_out operand required");
7681     return;
7682   }
7683   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7684   if (deadCPSR) {
7685     assert(!MI->getOperand(ccOutIdx).getReg() &&
7686            "expect uninitialized optional cc_out operand");
7687     return;
7688   }
7689
7690   // If this instruction was defined with an optional CPSR def and its dag node
7691   // had a live implicit CPSR def, then activate the optional CPSR def.
7692   MachineOperand &MO = MI->getOperand(ccOutIdx);
7693   MO.setReg(ARM::CPSR);
7694   MO.setIsDef(true);
7695 }
7696
7697 //===----------------------------------------------------------------------===//
7698 //                           ARM Optimization Hooks
7699 //===----------------------------------------------------------------------===//
7700
7701 // Helper function that checks if N is a null or all ones constant.
7702 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7703   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7704   if (!C)
7705     return false;
7706   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7707 }
7708
7709 // Return true if N is conditionally 0 or all ones.
7710 // Detects these expressions where cc is an i1 value:
7711 //
7712 //   (select cc 0, y)   [AllOnes=0]
7713 //   (select cc y, 0)   [AllOnes=0]
7714 //   (zext cc)          [AllOnes=0]
7715 //   (sext cc)          [AllOnes=0/1]
7716 //   (select cc -1, y)  [AllOnes=1]
7717 //   (select cc y, -1)  [AllOnes=1]
7718 //
7719 // Invert is set when N is the null/all ones constant when CC is false.
7720 // OtherOp is set to the alternative value of N.
7721 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7722                                        SDValue &CC, bool &Invert,
7723                                        SDValue &OtherOp,
7724                                        SelectionDAG &DAG) {
7725   switch (N->getOpcode()) {
7726   default: return false;
7727   case ISD::SELECT: {
7728     CC = N->getOperand(0);
7729     SDValue N1 = N->getOperand(1);
7730     SDValue N2 = N->getOperand(2);
7731     if (isZeroOrAllOnes(N1, AllOnes)) {
7732       Invert = false;
7733       OtherOp = N2;
7734       return true;
7735     }
7736     if (isZeroOrAllOnes(N2, AllOnes)) {
7737       Invert = true;
7738       OtherOp = N1;
7739       return true;
7740     }
7741     return false;
7742   }
7743   case ISD::ZERO_EXTEND:
7744     // (zext cc) can never be the all ones value.
7745     if (AllOnes)
7746       return false;
7747     // Fall through.
7748   case ISD::SIGN_EXTEND: {
7749     SDLoc dl(N);
7750     EVT VT = N->getValueType(0);
7751     CC = N->getOperand(0);
7752     if (CC.getValueType() != MVT::i1)
7753       return false;
7754     Invert = !AllOnes;
7755     if (AllOnes)
7756       // When looking for an AllOnes constant, N is an sext, and the 'other'
7757       // value is 0.
7758       OtherOp = DAG.getConstant(0, dl, VT);
7759     else if (N->getOpcode() == ISD::ZERO_EXTEND)
7760       // When looking for a 0 constant, N can be zext or sext.
7761       OtherOp = DAG.getConstant(1, dl, VT);
7762     else
7763       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
7764                                 VT);
7765     return true;
7766   }
7767   }
7768 }
7769
7770 // Combine a constant select operand into its use:
7771 //
7772 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
7773 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
7774 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
7775 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
7776 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
7777 //
7778 // The transform is rejected if the select doesn't have a constant operand that
7779 // is null, or all ones when AllOnes is set.
7780 //
7781 // Also recognize sext/zext from i1:
7782 //
7783 //   (add (zext cc), x) -> (select cc (add x, 1), x)
7784 //   (add (sext cc), x) -> (select cc (add x, -1), x)
7785 //
7786 // These transformations eventually create predicated instructions.
7787 //
7788 // @param N       The node to transform.
7789 // @param Slct    The N operand that is a select.
7790 // @param OtherOp The other N operand (x above).
7791 // @param DCI     Context.
7792 // @param AllOnes Require the select constant to be all ones instead of null.
7793 // @returns The new node, or SDValue() on failure.
7794 static
7795 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7796                             TargetLowering::DAGCombinerInfo &DCI,
7797                             bool AllOnes = false) {
7798   SelectionDAG &DAG = DCI.DAG;
7799   EVT VT = N->getValueType(0);
7800   SDValue NonConstantVal;
7801   SDValue CCOp;
7802   bool SwapSelectOps;
7803   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7804                                   NonConstantVal, DAG))
7805     return SDValue();
7806
7807   // Slct is now know to be the desired identity constant when CC is true.
7808   SDValue TrueVal = OtherOp;
7809   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7810                                  OtherOp, NonConstantVal);
7811   // Unless SwapSelectOps says CC should be false.
7812   if (SwapSelectOps)
7813     std::swap(TrueVal, FalseVal);
7814
7815   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7816                      CCOp, TrueVal, FalseVal);
7817 }
7818
7819 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7820 static
7821 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7822                                        TargetLowering::DAGCombinerInfo &DCI) {
7823   SDValue N0 = N->getOperand(0);
7824   SDValue N1 = N->getOperand(1);
7825   if (N0.getNode()->hasOneUse()) {
7826     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7827     if (Result.getNode())
7828       return Result;
7829   }
7830   if (N1.getNode()->hasOneUse()) {
7831     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7832     if (Result.getNode())
7833       return Result;
7834   }
7835   return SDValue();
7836 }
7837
7838 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7839 // (only after legalization).
7840 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7841                                  TargetLowering::DAGCombinerInfo &DCI,
7842                                  const ARMSubtarget *Subtarget) {
7843
7844   // Only perform optimization if after legalize, and if NEON is available. We
7845   // also expected both operands to be BUILD_VECTORs.
7846   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7847       || N0.getOpcode() != ISD::BUILD_VECTOR
7848       || N1.getOpcode() != ISD::BUILD_VECTOR)
7849     return SDValue();
7850
7851   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7852   EVT VT = N->getValueType(0);
7853   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7854     return SDValue();
7855
7856   // Check that the vector operands are of the right form.
7857   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7858   // operands, where N is the size of the formed vector.
7859   // Each EXTRACT_VECTOR should have the same input vector and odd or even
7860   // index such that we have a pair wise add pattern.
7861
7862   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7863   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7864     return SDValue();
7865   SDValue Vec = N0->getOperand(0)->getOperand(0);
7866   SDNode *V = Vec.getNode();
7867   unsigned nextIndex = 0;
7868
7869   // For each operands to the ADD which are BUILD_VECTORs,
7870   // check to see if each of their operands are an EXTRACT_VECTOR with
7871   // the same vector and appropriate index.
7872   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7873     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7874         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7875
7876       SDValue ExtVec0 = N0->getOperand(i);
7877       SDValue ExtVec1 = N1->getOperand(i);
7878
7879       // First operand is the vector, verify its the same.
7880       if (V != ExtVec0->getOperand(0).getNode() ||
7881           V != ExtVec1->getOperand(0).getNode())
7882         return SDValue();
7883
7884       // Second is the constant, verify its correct.
7885       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7886       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7887
7888       // For the constant, we want to see all the even or all the odd.
7889       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7890           || C1->getZExtValue() != nextIndex+1)
7891         return SDValue();
7892
7893       // Increment index.
7894       nextIndex+=2;
7895     } else
7896       return SDValue();
7897   }
7898
7899   // Create VPADDL node.
7900   SelectionDAG &DAG = DCI.DAG;
7901   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7902
7903   SDLoc dl(N);
7904
7905   // Build operand list.
7906   SmallVector<SDValue, 8> Ops;
7907   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
7908                                 TLI.getPointerTy()));
7909
7910   // Input is the vector.
7911   Ops.push_back(Vec);
7912
7913   // Get widened type and narrowed type.
7914   MVT widenType;
7915   unsigned numElem = VT.getVectorNumElements();
7916   
7917   EVT inputLaneType = Vec.getValueType().getVectorElementType();
7918   switch (inputLaneType.getSimpleVT().SimpleTy) {
7919     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7920     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7921     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7922     default:
7923       llvm_unreachable("Invalid vector element type for padd optimization.");
7924   }
7925
7926   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
7927   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
7928   return DAG.getNode(ExtOp, dl, VT, tmp);
7929 }
7930
7931 static SDValue findMUL_LOHI(SDValue V) {
7932   if (V->getOpcode() == ISD::UMUL_LOHI ||
7933       V->getOpcode() == ISD::SMUL_LOHI)
7934     return V;
7935   return SDValue();
7936 }
7937
7938 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7939                                      TargetLowering::DAGCombinerInfo &DCI,
7940                                      const ARMSubtarget *Subtarget) {
7941
7942   if (Subtarget->isThumb1Only()) return SDValue();
7943
7944   // Only perform the checks after legalize when the pattern is available.
7945   if (DCI.isBeforeLegalize()) return SDValue();
7946
7947   // Look for multiply add opportunities.
7948   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7949   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7950   // a glue link from the first add to the second add.
7951   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7952   // a S/UMLAL instruction.
7953   //                  UMUL_LOHI
7954   //                 / :lo    \ :hi
7955   //                /          \          [no multiline comment]
7956   //    loAdd ->  ADDE         |
7957   //                 \ :glue  /
7958   //                  \      /
7959   //                    ADDC   <- hiAdd
7960   //
7961   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7962   SDValue AddcOp0 = AddcNode->getOperand(0);
7963   SDValue AddcOp1 = AddcNode->getOperand(1);
7964
7965   // Check if the two operands are from the same mul_lohi node.
7966   if (AddcOp0.getNode() == AddcOp1.getNode())
7967     return SDValue();
7968
7969   assert(AddcNode->getNumValues() == 2 &&
7970          AddcNode->getValueType(0) == MVT::i32 &&
7971          "Expect ADDC with two result values. First: i32");
7972
7973   // Check that we have a glued ADDC node.
7974   if (AddcNode->getValueType(1) != MVT::Glue)
7975     return SDValue();
7976
7977   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7978   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7979       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7980       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7981       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7982     return SDValue();
7983
7984   // Look for the glued ADDE.
7985   SDNode* AddeNode = AddcNode->getGluedUser();
7986   if (!AddeNode)
7987     return SDValue();
7988
7989   // Make sure it is really an ADDE.
7990   if (AddeNode->getOpcode() != ISD::ADDE)
7991     return SDValue();
7992
7993   assert(AddeNode->getNumOperands() == 3 &&
7994          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
7995          "ADDE node has the wrong inputs");
7996
7997   // Check for the triangle shape.
7998   SDValue AddeOp0 = AddeNode->getOperand(0);
7999   SDValue AddeOp1 = AddeNode->getOperand(1);
8000
8001   // Make sure that the ADDE operands are not coming from the same node.
8002   if (AddeOp0.getNode() == AddeOp1.getNode())
8003     return SDValue();
8004
8005   // Find the MUL_LOHI node walking up ADDE's operands.
8006   bool IsLeftOperandMUL = false;
8007   SDValue MULOp = findMUL_LOHI(AddeOp0);
8008   if (MULOp == SDValue())
8009    MULOp = findMUL_LOHI(AddeOp1);
8010   else
8011     IsLeftOperandMUL = true;
8012   if (MULOp == SDValue())
8013     return SDValue();
8014
8015   // Figure out the right opcode.
8016   unsigned Opc = MULOp->getOpcode();
8017   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8018
8019   // Figure out the high and low input values to the MLAL node.
8020   SDValue* HiAdd = nullptr;
8021   SDValue* LoMul = nullptr;
8022   SDValue* LowAdd = nullptr;
8023
8024   // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
8025   if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
8026     return SDValue();
8027
8028   if (IsLeftOperandMUL)
8029     HiAdd = &AddeOp1;
8030   else
8031     HiAdd = &AddeOp0;
8032
8033
8034   // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
8035   // whose low result is fed to the ADDC we are checking.
8036
8037   if (AddcOp0 == MULOp.getValue(0)) {
8038     LoMul = &AddcOp0;
8039     LowAdd = &AddcOp1;
8040   }
8041   if (AddcOp1 == MULOp.getValue(0)) {
8042     LoMul = &AddcOp1;
8043     LowAdd = &AddcOp0;
8044   }
8045
8046   if (!LoMul)
8047     return SDValue();
8048
8049   // Create the merged node.
8050   SelectionDAG &DAG = DCI.DAG;
8051
8052   // Build operand list.
8053   SmallVector<SDValue, 8> Ops;
8054   Ops.push_back(LoMul->getOperand(0));
8055   Ops.push_back(LoMul->getOperand(1));
8056   Ops.push_back(*LowAdd);
8057   Ops.push_back(*HiAdd);
8058
8059   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
8060                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
8061
8062   // Replace the ADDs' nodes uses by the MLA node's values.
8063   SDValue HiMLALResult(MLALNode.getNode(), 1);
8064   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8065
8066   SDValue LoMLALResult(MLALNode.getNode(), 0);
8067   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8068
8069   // Return original node to notify the driver to stop replacing.
8070   SDValue resNode(AddcNode, 0);
8071   return resNode;
8072 }
8073
8074 /// PerformADDCCombine - Target-specific dag combine transform from
8075 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8076 static SDValue PerformADDCCombine(SDNode *N,
8077                                  TargetLowering::DAGCombinerInfo &DCI,
8078                                  const ARMSubtarget *Subtarget) {
8079
8080   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8081
8082 }
8083
8084 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8085 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
8086 /// called with the default operands, and if that fails, with commuted
8087 /// operands.
8088 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8089                                           TargetLowering::DAGCombinerInfo &DCI,
8090                                           const ARMSubtarget *Subtarget){
8091
8092   // Attempt to create vpaddl for this add.
8093   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8094   if (Result.getNode())
8095     return Result;
8096
8097   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8098   if (N0.getNode()->hasOneUse()) {
8099     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8100     if (Result.getNode()) return Result;
8101   }
8102   return SDValue();
8103 }
8104
8105 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8106 ///
8107 static SDValue PerformADDCombine(SDNode *N,
8108                                  TargetLowering::DAGCombinerInfo &DCI,
8109                                  const ARMSubtarget *Subtarget) {
8110   SDValue N0 = N->getOperand(0);
8111   SDValue N1 = N->getOperand(1);
8112
8113   // First try with the default operand order.
8114   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8115   if (Result.getNode())
8116     return Result;
8117
8118   // If that didn't work, try again with the operands commuted.
8119   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8120 }
8121
8122 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8123 ///
8124 static SDValue PerformSUBCombine(SDNode *N,
8125                                  TargetLowering::DAGCombinerInfo &DCI) {
8126   SDValue N0 = N->getOperand(0);
8127   SDValue N1 = N->getOperand(1);
8128
8129   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8130   if (N1.getNode()->hasOneUse()) {
8131     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8132     if (Result.getNode()) return Result;
8133   }
8134
8135   return SDValue();
8136 }
8137
8138 /// PerformVMULCombine
8139 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8140 /// special multiplier accumulator forwarding.
8141 ///   vmul d3, d0, d2
8142 ///   vmla d3, d1, d2
8143 /// is faster than
8144 ///   vadd d3, d0, d1
8145 ///   vmul d3, d3, d2
8146 //  However, for (A + B) * (A + B),
8147 //    vadd d2, d0, d1
8148 //    vmul d3, d0, d2
8149 //    vmla d3, d1, d2
8150 //  is slower than
8151 //    vadd d2, d0, d1
8152 //    vmul d3, d2, d2
8153 static SDValue PerformVMULCombine(SDNode *N,
8154                                   TargetLowering::DAGCombinerInfo &DCI,
8155                                   const ARMSubtarget *Subtarget) {
8156   if (!Subtarget->hasVMLxForwarding())
8157     return SDValue();
8158
8159   SelectionDAG &DAG = DCI.DAG;
8160   SDValue N0 = N->getOperand(0);
8161   SDValue N1 = N->getOperand(1);
8162   unsigned Opcode = N0.getOpcode();
8163   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8164       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8165     Opcode = N1.getOpcode();
8166     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8167         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8168       return SDValue();
8169     std::swap(N0, N1);
8170   }
8171
8172   if (N0 == N1)
8173     return SDValue();
8174
8175   EVT VT = N->getValueType(0);
8176   SDLoc DL(N);
8177   SDValue N00 = N0->getOperand(0);
8178   SDValue N01 = N0->getOperand(1);
8179   return DAG.getNode(Opcode, DL, VT,
8180                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8181                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8182 }
8183
8184 static SDValue PerformMULCombine(SDNode *N,
8185                                  TargetLowering::DAGCombinerInfo &DCI,
8186                                  const ARMSubtarget *Subtarget) {
8187   SelectionDAG &DAG = DCI.DAG;
8188
8189   if (Subtarget->isThumb1Only())
8190     return SDValue();
8191
8192   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8193     return SDValue();
8194
8195   EVT VT = N->getValueType(0);
8196   if (VT.is64BitVector() || VT.is128BitVector())
8197     return PerformVMULCombine(N, DCI, Subtarget);
8198   if (VT != MVT::i32)
8199     return SDValue();
8200
8201   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8202   if (!C)
8203     return SDValue();
8204
8205   int64_t MulAmt = C->getSExtValue();
8206   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8207
8208   ShiftAmt = ShiftAmt & (32 - 1);
8209   SDValue V = N->getOperand(0);
8210   SDLoc DL(N);
8211
8212   SDValue Res;
8213   MulAmt >>= ShiftAmt;
8214
8215   if (MulAmt >= 0) {
8216     if (isPowerOf2_32(MulAmt - 1)) {
8217       // (mul x, 2^N + 1) => (add (shl x, N), x)
8218       Res = DAG.getNode(ISD::ADD, DL, VT,
8219                         V,
8220                         DAG.getNode(ISD::SHL, DL, VT,
8221                                     V,
8222                                     DAG.getConstant(Log2_32(MulAmt - 1), DL,
8223                                                     MVT::i32)));
8224     } else if (isPowerOf2_32(MulAmt + 1)) {
8225       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8226       Res = DAG.getNode(ISD::SUB, DL, VT,
8227                         DAG.getNode(ISD::SHL, DL, VT,
8228                                     V,
8229                                     DAG.getConstant(Log2_32(MulAmt + 1), DL,
8230                                                     MVT::i32)),
8231                         V);
8232     } else
8233       return SDValue();
8234   } else {
8235     uint64_t MulAmtAbs = -MulAmt;
8236     if (isPowerOf2_32(MulAmtAbs + 1)) {
8237       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8238       Res = DAG.getNode(ISD::SUB, DL, VT,
8239                         V,
8240                         DAG.getNode(ISD::SHL, DL, VT,
8241                                     V,
8242                                     DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
8243                                                     MVT::i32)));
8244     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8245       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8246       Res = DAG.getNode(ISD::ADD, DL, VT,
8247                         V,
8248                         DAG.getNode(ISD::SHL, DL, VT,
8249                                     V,
8250                                     DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
8251                                                     MVT::i32)));
8252       Res = DAG.getNode(ISD::SUB, DL, VT,
8253                         DAG.getConstant(0, DL, MVT::i32), Res);
8254
8255     } else
8256       return SDValue();
8257   }
8258
8259   if (ShiftAmt != 0)
8260     Res = DAG.getNode(ISD::SHL, DL, VT,
8261                       Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
8262
8263   // Do not add new nodes to DAG combiner worklist.
8264   DCI.CombineTo(N, Res, false);
8265   return SDValue();
8266 }
8267
8268 static SDValue PerformANDCombine(SDNode *N,
8269                                  TargetLowering::DAGCombinerInfo &DCI,
8270                                  const ARMSubtarget *Subtarget) {
8271
8272   // Attempt to use immediate-form VBIC
8273   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8274   SDLoc dl(N);
8275   EVT VT = N->getValueType(0);
8276   SelectionDAG &DAG = DCI.DAG;
8277
8278   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8279     return SDValue();
8280
8281   APInt SplatBits, SplatUndef;
8282   unsigned SplatBitSize;
8283   bool HasAnyUndefs;
8284   if (BVN &&
8285       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8286     if (SplatBitSize <= 64) {
8287       EVT VbicVT;
8288       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8289                                       SplatUndef.getZExtValue(), SplatBitSize,
8290                                       DAG, dl, VbicVT, VT.is128BitVector(),
8291                                       OtherModImm);
8292       if (Val.getNode()) {
8293         SDValue Input =
8294           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8295         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8296         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8297       }
8298     }
8299   }
8300
8301   if (!Subtarget->isThumb1Only()) {
8302     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8303     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8304     if (Result.getNode())
8305       return Result;
8306   }
8307
8308   return SDValue();
8309 }
8310
8311 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8312 static SDValue PerformORCombine(SDNode *N,
8313                                 TargetLowering::DAGCombinerInfo &DCI,
8314                                 const ARMSubtarget *Subtarget) {
8315   // Attempt to use immediate-form VORR
8316   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8317   SDLoc dl(N);
8318   EVT VT = N->getValueType(0);
8319   SelectionDAG &DAG = DCI.DAG;
8320
8321   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8322     return SDValue();
8323
8324   APInt SplatBits, SplatUndef;
8325   unsigned SplatBitSize;
8326   bool HasAnyUndefs;
8327   if (BVN && Subtarget->hasNEON() &&
8328       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8329     if (SplatBitSize <= 64) {
8330       EVT VorrVT;
8331       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8332                                       SplatUndef.getZExtValue(), SplatBitSize,
8333                                       DAG, dl, VorrVT, VT.is128BitVector(),
8334                                       OtherModImm);
8335       if (Val.getNode()) {
8336         SDValue Input =
8337           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8338         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8339         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8340       }
8341     }
8342   }
8343
8344   if (!Subtarget->isThumb1Only()) {
8345     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8346     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8347     if (Result.getNode())
8348       return Result;
8349   }
8350
8351   // The code below optimizes (or (and X, Y), Z).
8352   // The AND operand needs to have a single user to make these optimizations
8353   // profitable.
8354   SDValue N0 = N->getOperand(0);
8355   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8356     return SDValue();
8357   SDValue N1 = N->getOperand(1);
8358
8359   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8360   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8361       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8362     APInt SplatUndef;
8363     unsigned SplatBitSize;
8364     bool HasAnyUndefs;
8365
8366     APInt SplatBits0, SplatBits1;
8367     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8368     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8369     // Ensure that the second operand of both ands are constants
8370     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8371                                       HasAnyUndefs) && !HasAnyUndefs) {
8372         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8373                                           HasAnyUndefs) && !HasAnyUndefs) {
8374             // Ensure that the bit width of the constants are the same and that
8375             // the splat arguments are logical inverses as per the pattern we
8376             // are trying to simplify.
8377             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8378                 SplatBits0 == ~SplatBits1) {
8379                 // Canonicalize the vector type to make instruction selection
8380                 // simpler.
8381                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8382                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8383                                              N0->getOperand(1),
8384                                              N0->getOperand(0),
8385                                              N1->getOperand(0));
8386                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8387             }
8388         }
8389     }
8390   }
8391
8392   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8393   // reasonable.
8394
8395   // BFI is only available on V6T2+
8396   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8397     return SDValue();
8398
8399   SDLoc DL(N);
8400   // 1) or (and A, mask), val => ARMbfi A, val, mask
8401   //      iff (val & mask) == val
8402   //
8403   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8404   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8405   //          && mask == ~mask2
8406   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8407   //          && ~mask == mask2
8408   //  (i.e., copy a bitfield value into another bitfield of the same width)
8409
8410   if (VT != MVT::i32)
8411     return SDValue();
8412
8413   SDValue N00 = N0.getOperand(0);
8414
8415   // The value and the mask need to be constants so we can verify this is
8416   // actually a bitfield set. If the mask is 0xffff, we can do better
8417   // via a movt instruction, so don't use BFI in that case.
8418   SDValue MaskOp = N0.getOperand(1);
8419   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8420   if (!MaskC)
8421     return SDValue();
8422   unsigned Mask = MaskC->getZExtValue();
8423   if (Mask == 0xffff)
8424     return SDValue();
8425   SDValue Res;
8426   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8427   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8428   if (N1C) {
8429     unsigned Val = N1C->getZExtValue();
8430     if ((Val & ~Mask) != Val)
8431       return SDValue();
8432
8433     if (ARM::isBitFieldInvertedMask(Mask)) {
8434       Val >>= countTrailingZeros(~Mask);
8435
8436       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8437                         DAG.getConstant(Val, DL, MVT::i32),
8438                         DAG.getConstant(Mask, DL, MVT::i32));
8439
8440       // Do not add new nodes to DAG combiner worklist.
8441       DCI.CombineTo(N, Res, false);
8442       return SDValue();
8443     }
8444   } else if (N1.getOpcode() == ISD::AND) {
8445     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8446     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8447     if (!N11C)
8448       return SDValue();
8449     unsigned Mask2 = N11C->getZExtValue();
8450
8451     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8452     // as is to match.
8453     if (ARM::isBitFieldInvertedMask(Mask) &&
8454         (Mask == ~Mask2)) {
8455       // The pack halfword instruction works better for masks that fit it,
8456       // so use that when it's available.
8457       if (Subtarget->hasT2ExtractPack() &&
8458           (Mask == 0xffff || Mask == 0xffff0000))
8459         return SDValue();
8460       // 2a
8461       unsigned amt = countTrailingZeros(Mask2);
8462       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8463                         DAG.getConstant(amt, DL, MVT::i32));
8464       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8465                         DAG.getConstant(Mask, DL, MVT::i32));
8466       // Do not add new nodes to DAG combiner worklist.
8467       DCI.CombineTo(N, Res, false);
8468       return SDValue();
8469     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8470                (~Mask == Mask2)) {
8471       // The pack halfword instruction works better for masks that fit it,
8472       // so use that when it's available.
8473       if (Subtarget->hasT2ExtractPack() &&
8474           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8475         return SDValue();
8476       // 2b
8477       unsigned lsb = countTrailingZeros(Mask);
8478       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8479                         DAG.getConstant(lsb, DL, MVT::i32));
8480       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8481                         DAG.getConstant(Mask2, DL, MVT::i32));
8482       // Do not add new nodes to DAG combiner worklist.
8483       DCI.CombineTo(N, Res, false);
8484       return SDValue();
8485     }
8486   }
8487
8488   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8489       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8490       ARM::isBitFieldInvertedMask(~Mask)) {
8491     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8492     // where lsb(mask) == #shamt and masked bits of B are known zero.
8493     SDValue ShAmt = N00.getOperand(1);
8494     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8495     unsigned LSB = countTrailingZeros(Mask);
8496     if (ShAmtC != LSB)
8497       return SDValue();
8498
8499     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8500                       DAG.getConstant(~Mask, DL, MVT::i32));
8501
8502     // Do not add new nodes to DAG combiner worklist.
8503     DCI.CombineTo(N, Res, false);
8504   }
8505
8506   return SDValue();
8507 }
8508
8509 static SDValue PerformXORCombine(SDNode *N,
8510                                  TargetLowering::DAGCombinerInfo &DCI,
8511                                  const ARMSubtarget *Subtarget) {
8512   EVT VT = N->getValueType(0);
8513   SelectionDAG &DAG = DCI.DAG;
8514
8515   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8516     return SDValue();
8517
8518   if (!Subtarget->isThumb1Only()) {
8519     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8520     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8521     if (Result.getNode())
8522       return Result;
8523   }
8524
8525   return SDValue();
8526 }
8527
8528 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8529 /// the bits being cleared by the AND are not demanded by the BFI.
8530 static SDValue PerformBFICombine(SDNode *N,
8531                                  TargetLowering::DAGCombinerInfo &DCI) {
8532   SDValue N1 = N->getOperand(1);
8533   if (N1.getOpcode() == ISD::AND) {
8534     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8535     if (!N11C)
8536       return SDValue();
8537     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8538     unsigned LSB = countTrailingZeros(~InvMask);
8539     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8540     assert(Width <
8541                static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
8542            "undefined behavior");
8543     unsigned Mask = (1u << Width) - 1;
8544     unsigned Mask2 = N11C->getZExtValue();
8545     if ((Mask & (~Mask2)) == 0)
8546       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8547                              N->getOperand(0), N1.getOperand(0),
8548                              N->getOperand(2));
8549   }
8550   return SDValue();
8551 }
8552
8553 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8554 /// ARMISD::VMOVRRD.
8555 static SDValue PerformVMOVRRDCombine(SDNode *N,
8556                                      TargetLowering::DAGCombinerInfo &DCI,
8557                                      const ARMSubtarget *Subtarget) {
8558   // vmovrrd(vmovdrr x, y) -> x,y
8559   SDValue InDouble = N->getOperand(0);
8560   if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
8561     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8562
8563   // vmovrrd(load f64) -> (load i32), (load i32)
8564   SDNode *InNode = InDouble.getNode();
8565   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8566       InNode->getValueType(0) == MVT::f64 &&
8567       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8568       !cast<LoadSDNode>(InNode)->isVolatile()) {
8569     // TODO: Should this be done for non-FrameIndex operands?
8570     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8571
8572     SelectionDAG &DAG = DCI.DAG;
8573     SDLoc DL(LD);
8574     SDValue BasePtr = LD->getBasePtr();
8575     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8576                                  LD->getPointerInfo(), LD->isVolatile(),
8577                                  LD->isNonTemporal(), LD->isInvariant(),
8578                                  LD->getAlignment());
8579
8580     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8581                                     DAG.getConstant(4, DL, MVT::i32));
8582     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8583                                  LD->getPointerInfo(), LD->isVolatile(),
8584                                  LD->isNonTemporal(), LD->isInvariant(),
8585                                  std::min(4U, LD->getAlignment() / 2));
8586
8587     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8588     if (DCI.DAG.getTargetLoweringInfo().isBigEndian())
8589       std::swap (NewLD1, NewLD2);
8590     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8591     return Result;
8592   }
8593
8594   return SDValue();
8595 }
8596
8597 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8598 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8599 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8600   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8601   SDValue Op0 = N->getOperand(0);
8602   SDValue Op1 = N->getOperand(1);
8603   if (Op0.getOpcode() == ISD::BITCAST)
8604     Op0 = Op0.getOperand(0);
8605   if (Op1.getOpcode() == ISD::BITCAST)
8606     Op1 = Op1.getOperand(0);
8607   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8608       Op0.getNode() == Op1.getNode() &&
8609       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8610     return DAG.getNode(ISD::BITCAST, SDLoc(N),
8611                        N->getValueType(0), Op0.getOperand(0));
8612   return SDValue();
8613 }
8614
8615 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8616 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8617 /// i64 vector to have f64 elements, since the value can then be loaded
8618 /// directly into a VFP register.
8619 static bool hasNormalLoadOperand(SDNode *N) {
8620   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8621   for (unsigned i = 0; i < NumElts; ++i) {
8622     SDNode *Elt = N->getOperand(i).getNode();
8623     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8624       return true;
8625   }
8626   return false;
8627 }
8628
8629 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8630 /// ISD::BUILD_VECTOR.
8631 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8632                                           TargetLowering::DAGCombinerInfo &DCI,
8633                                           const ARMSubtarget *Subtarget) {
8634   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8635   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
8636   // into a pair of GPRs, which is fine when the value is used as a scalar,
8637   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8638   SelectionDAG &DAG = DCI.DAG;
8639   if (N->getNumOperands() == 2) {
8640     SDValue RV = PerformVMOVDRRCombine(N, DAG);
8641     if (RV.getNode())
8642       return RV;
8643   }
8644
8645   // Load i64 elements as f64 values so that type legalization does not split
8646   // them up into i32 values.
8647   EVT VT = N->getValueType(0);
8648   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8649     return SDValue();
8650   SDLoc dl(N);
8651   SmallVector<SDValue, 8> Ops;
8652   unsigned NumElts = VT.getVectorNumElements();
8653   for (unsigned i = 0; i < NumElts; ++i) {
8654     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8655     Ops.push_back(V);
8656     // Make the DAGCombiner fold the bitcast.
8657     DCI.AddToWorklist(V.getNode());
8658   }
8659   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8660   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8661   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8662 }
8663
8664 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8665 static SDValue
8666 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8667   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8668   // At that time, we may have inserted bitcasts from integer to float.
8669   // If these bitcasts have survived DAGCombine, change the lowering of this
8670   // BUILD_VECTOR in something more vector friendly, i.e., that does not
8671   // force to use floating point types.
8672
8673   // Make sure we can change the type of the vector.
8674   // This is possible iff:
8675   // 1. The vector is only used in a bitcast to a integer type. I.e.,
8676   //    1.1. Vector is used only once.
8677   //    1.2. Use is a bit convert to an integer type.
8678   // 2. The size of its operands are 32-bits (64-bits are not legal).
8679   EVT VT = N->getValueType(0);
8680   EVT EltVT = VT.getVectorElementType();
8681
8682   // Check 1.1. and 2.
8683   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8684     return SDValue();
8685
8686   // By construction, the input type must be float.
8687   assert(EltVT == MVT::f32 && "Unexpected type!");
8688
8689   // Check 1.2.
8690   SDNode *Use = *N->use_begin();
8691   if (Use->getOpcode() != ISD::BITCAST ||
8692       Use->getValueType(0).isFloatingPoint())
8693     return SDValue();
8694
8695   // Check profitability.
8696   // Model is, if more than half of the relevant operands are bitcast from
8697   // i32, turn the build_vector into a sequence of insert_vector_elt.
8698   // Relevant operands are everything that is not statically
8699   // (i.e., at compile time) bitcasted.
8700   unsigned NumOfBitCastedElts = 0;
8701   unsigned NumElts = VT.getVectorNumElements();
8702   unsigned NumOfRelevantElts = NumElts;
8703   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8704     SDValue Elt = N->getOperand(Idx);
8705     if (Elt->getOpcode() == ISD::BITCAST) {
8706       // Assume only bit cast to i32 will go away.
8707       if (Elt->getOperand(0).getValueType() == MVT::i32)
8708         ++NumOfBitCastedElts;
8709     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8710       // Constants are statically casted, thus do not count them as
8711       // relevant operands.
8712       --NumOfRelevantElts;
8713   }
8714
8715   // Check if more than half of the elements require a non-free bitcast.
8716   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8717     return SDValue();
8718
8719   SelectionDAG &DAG = DCI.DAG;
8720   // Create the new vector type.
8721   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8722   // Check if the type is legal.
8723   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8724   if (!TLI.isTypeLegal(VecVT))
8725     return SDValue();
8726
8727   // Combine:
8728   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8729   // => BITCAST INSERT_VECTOR_ELT
8730   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8731   //                      (BITCAST EN), N.
8732   SDValue Vec = DAG.getUNDEF(VecVT);
8733   SDLoc dl(N);
8734   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8735     SDValue V = N->getOperand(Idx);
8736     if (V.getOpcode() == ISD::UNDEF)
8737       continue;
8738     if (V.getOpcode() == ISD::BITCAST &&
8739         V->getOperand(0).getValueType() == MVT::i32)
8740       // Fold obvious case.
8741       V = V.getOperand(0);
8742     else {
8743       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
8744       // Make the DAGCombiner fold the bitcasts.
8745       DCI.AddToWorklist(V.getNode());
8746     }
8747     SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
8748     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8749   }
8750   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8751   // Make the DAGCombiner fold the bitcasts.
8752   DCI.AddToWorklist(Vec.getNode());
8753   return Vec;
8754 }
8755
8756 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8757 /// ISD::INSERT_VECTOR_ELT.
8758 static SDValue PerformInsertEltCombine(SDNode *N,
8759                                        TargetLowering::DAGCombinerInfo &DCI) {
8760   // Bitcast an i64 load inserted into a vector to f64.
8761   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8762   EVT VT = N->getValueType(0);
8763   SDNode *Elt = N->getOperand(1).getNode();
8764   if (VT.getVectorElementType() != MVT::i64 ||
8765       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8766     return SDValue();
8767
8768   SelectionDAG &DAG = DCI.DAG;
8769   SDLoc dl(N);
8770   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8771                                  VT.getVectorNumElements());
8772   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8773   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8774   // Make the DAGCombiner fold the bitcasts.
8775   DCI.AddToWorklist(Vec.getNode());
8776   DCI.AddToWorklist(V.getNode());
8777   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8778                                Vec, V, N->getOperand(2));
8779   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8780 }
8781
8782 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8783 /// ISD::VECTOR_SHUFFLE.
8784 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8785   // The LLVM shufflevector instruction does not require the shuffle mask
8786   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8787   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
8788   // operands do not match the mask length, they are extended by concatenating
8789   // them with undef vectors.  That is probably the right thing for other
8790   // targets, but for NEON it is better to concatenate two double-register
8791   // size vector operands into a single quad-register size vector.  Do that
8792   // transformation here:
8793   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
8794   //   shuffle(concat(v1, v2), undef)
8795   SDValue Op0 = N->getOperand(0);
8796   SDValue Op1 = N->getOperand(1);
8797   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8798       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8799       Op0.getNumOperands() != 2 ||
8800       Op1.getNumOperands() != 2)
8801     return SDValue();
8802   SDValue Concat0Op1 = Op0.getOperand(1);
8803   SDValue Concat1Op1 = Op1.getOperand(1);
8804   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8805       Concat1Op1.getOpcode() != ISD::UNDEF)
8806     return SDValue();
8807   // Skip the transformation if any of the types are illegal.
8808   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8809   EVT VT = N->getValueType(0);
8810   if (!TLI.isTypeLegal(VT) ||
8811       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8812       !TLI.isTypeLegal(Concat1Op1.getValueType()))
8813     return SDValue();
8814
8815   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
8816                                   Op0.getOperand(0), Op1.getOperand(0));
8817   // Translate the shuffle mask.
8818   SmallVector<int, 16> NewMask;
8819   unsigned NumElts = VT.getVectorNumElements();
8820   unsigned HalfElts = NumElts/2;
8821   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8822   for (unsigned n = 0; n < NumElts; ++n) {
8823     int MaskElt = SVN->getMaskElt(n);
8824     int NewElt = -1;
8825     if (MaskElt < (int)HalfElts)
8826       NewElt = MaskElt;
8827     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8828       NewElt = HalfElts + MaskElt - NumElts;
8829     NewMask.push_back(NewElt);
8830   }
8831   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
8832                               DAG.getUNDEF(VT), NewMask.data());
8833 }
8834
8835 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
8836 /// NEON load/store intrinsics, and generic vector load/stores, to merge
8837 /// base address updates.
8838 /// For generic load/stores, the memory type is assumed to be a vector.
8839 /// The caller is assumed to have checked legality.
8840 static SDValue CombineBaseUpdate(SDNode *N,
8841                                  TargetLowering::DAGCombinerInfo &DCI) {
8842   SelectionDAG &DAG = DCI.DAG;
8843   const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8844                             N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8845   const bool isStore = N->getOpcode() == ISD::STORE;
8846   const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
8847   SDValue Addr = N->getOperand(AddrOpIdx);
8848   MemSDNode *MemN = cast<MemSDNode>(N);
8849   SDLoc dl(N);
8850
8851   // Search for a use of the address operand that is an increment.
8852   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8853          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8854     SDNode *User = *UI;
8855     if (User->getOpcode() != ISD::ADD ||
8856         UI.getUse().getResNo() != Addr.getResNo())
8857       continue;
8858
8859     // Check that the add is independent of the load/store.  Otherwise, folding
8860     // it would create a cycle.
8861     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8862       continue;
8863
8864     // Find the new opcode for the updating load/store.
8865     bool isLoadOp = true;
8866     bool isLaneOp = false;
8867     unsigned NewOpc = 0;
8868     unsigned NumVecs = 0;
8869     if (isIntrinsic) {
8870       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8871       switch (IntNo) {
8872       default: llvm_unreachable("unexpected intrinsic for Neon base update");
8873       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
8874         NumVecs = 1; break;
8875       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
8876         NumVecs = 2; break;
8877       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
8878         NumVecs = 3; break;
8879       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
8880         NumVecs = 4; break;
8881       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8882         NumVecs = 2; isLaneOp = true; break;
8883       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8884         NumVecs = 3; isLaneOp = true; break;
8885       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8886         NumVecs = 4; isLaneOp = true; break;
8887       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
8888         NumVecs = 1; isLoadOp = false; break;
8889       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
8890         NumVecs = 2; isLoadOp = false; break;
8891       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
8892         NumVecs = 3; isLoadOp = false; break;
8893       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
8894         NumVecs = 4; isLoadOp = false; break;
8895       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8896         NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
8897       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8898         NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
8899       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8900         NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
8901       }
8902     } else {
8903       isLaneOp = true;
8904       switch (N->getOpcode()) {
8905       default: llvm_unreachable("unexpected opcode for Neon base update");
8906       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8907       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8908       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8909       case ISD::LOAD:       NewOpc = ARMISD::VLD1_UPD;
8910         NumVecs = 1; isLaneOp = false; break;
8911       case ISD::STORE:      NewOpc = ARMISD::VST1_UPD;
8912         NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
8913       }
8914     }
8915
8916     // Find the size of memory referenced by the load/store.
8917     EVT VecTy;
8918     if (isLoadOp) {
8919       VecTy = N->getValueType(0);
8920     } else if (isIntrinsic) {
8921       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8922     } else {
8923       assert(isStore && "Node has to be a load, a store, or an intrinsic!");
8924       VecTy = N->getOperand(1).getValueType();
8925     }
8926
8927     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8928     if (isLaneOp)
8929       NumBytes /= VecTy.getVectorNumElements();
8930
8931     // If the increment is a constant, it must match the memory ref size.
8932     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8933     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8934       uint64_t IncVal = CInc->getZExtValue();
8935       if (IncVal != NumBytes)
8936         continue;
8937     } else if (NumBytes >= 3 * 16) {
8938       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8939       // separate instructions that make it harder to use a non-constant update.
8940       continue;
8941     }
8942
8943     // OK, we found an ADD we can fold into the base update.
8944     // Now, create a _UPD node, taking care of not breaking alignment.
8945
8946     EVT AlignedVecTy = VecTy;
8947     unsigned Alignment = MemN->getAlignment();
8948
8949     // If this is a less-than-standard-aligned load/store, change the type to
8950     // match the standard alignment.
8951     // The alignment is overlooked when selecting _UPD variants; and it's
8952     // easier to introduce bitcasts here than fix that.
8953     // There are 3 ways to get to this base-update combine:
8954     // - intrinsics: they are assumed to be properly aligned (to the standard
8955     //   alignment of the memory type), so we don't need to do anything.
8956     // - ARMISD::VLDx nodes: they are only generated from the aforementioned
8957     //   intrinsics, so, likewise, there's nothing to do.
8958     // - generic load/store instructions: the alignment is specified as an
8959     //   explicit operand, rather than implicitly as the standard alignment
8960     //   of the memory type (like the intrisics).  We need to change the
8961     //   memory type to match the explicit alignment.  That way, we don't
8962     //   generate non-standard-aligned ARMISD::VLDx nodes.
8963     if (isa<LSBaseSDNode>(N)) {
8964       if (Alignment == 0)
8965         Alignment = 1;
8966       if (Alignment < VecTy.getScalarSizeInBits() / 8) {
8967         MVT EltTy = MVT::getIntegerVT(Alignment * 8);
8968         assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
8969         assert(!isLaneOp && "Unexpected generic load/store lane.");
8970         unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
8971         AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
8972       }
8973       // Don't set an explicit alignment on regular load/stores that we want
8974       // to transform to VLD/VST 1_UPD nodes.
8975       // This matches the behavior of regular load/stores, which only get an
8976       // explicit alignment if the MMO alignment is larger than the standard
8977       // alignment of the memory type.
8978       // Intrinsics, however, always get an explicit alignment, set to the
8979       // alignment of the MMO.
8980       Alignment = 1;
8981     }
8982
8983     // Create the new updating load/store node.
8984     // First, create an SDVTList for the new updating node's results.
8985     EVT Tys[6];
8986     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
8987     unsigned n;
8988     for (n = 0; n < NumResultVecs; ++n)
8989       Tys[n] = AlignedVecTy;
8990     Tys[n++] = MVT::i32;
8991     Tys[n] = MVT::Other;
8992     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
8993
8994     // Then, gather the new node's operands.
8995     SmallVector<SDValue, 8> Ops;
8996     Ops.push_back(N->getOperand(0)); // incoming chain
8997     Ops.push_back(N->getOperand(AddrOpIdx));
8998     Ops.push_back(Inc);
8999
9000     if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
9001       // Try to match the intrinsic's signature
9002       Ops.push_back(StN->getValue());
9003     } else {
9004       // Loads (and of course intrinsics) match the intrinsics' signature,
9005       // so just add all but the alignment operand.
9006       for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
9007         Ops.push_back(N->getOperand(i));
9008     }
9009
9010     // For all node types, the alignment operand is always the last one.
9011     Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
9012
9013     // If this is a non-standard-aligned STORE, the penultimate operand is the
9014     // stored value.  Bitcast it to the aligned type.
9015     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
9016       SDValue &StVal = Ops[Ops.size()-2];
9017       StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
9018     }
9019
9020     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys,
9021                                            Ops, AlignedVecTy,
9022                                            MemN->getMemOperand());
9023
9024     // Update the uses.
9025     SmallVector<SDValue, 5> NewResults;
9026     for (unsigned i = 0; i < NumResultVecs; ++i)
9027       NewResults.push_back(SDValue(UpdN.getNode(), i));
9028
9029     // If this is an non-standard-aligned LOAD, the first result is the loaded
9030     // value.  Bitcast it to the expected result type.
9031     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
9032       SDValue &LdVal = NewResults[0];
9033       LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
9034     }
9035
9036     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9037     DCI.CombineTo(N, NewResults);
9038     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9039
9040     break;
9041   }
9042   return SDValue();
9043 }
9044
9045 static SDValue PerformVLDCombine(SDNode *N,
9046                                  TargetLowering::DAGCombinerInfo &DCI) {
9047   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9048     return SDValue();
9049
9050   return CombineBaseUpdate(N, DCI);
9051 }
9052
9053 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9054 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9055 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
9056 /// return true.
9057 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9058   SelectionDAG &DAG = DCI.DAG;
9059   EVT VT = N->getValueType(0);
9060   // vldN-dup instructions only support 64-bit vectors for N > 1.
9061   if (!VT.is64BitVector())
9062     return false;
9063
9064   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9065   SDNode *VLD = N->getOperand(0).getNode();
9066   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9067     return false;
9068   unsigned NumVecs = 0;
9069   unsigned NewOpc = 0;
9070   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9071   if (IntNo == Intrinsic::arm_neon_vld2lane) {
9072     NumVecs = 2;
9073     NewOpc = ARMISD::VLD2DUP;
9074   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9075     NumVecs = 3;
9076     NewOpc = ARMISD::VLD3DUP;
9077   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9078     NumVecs = 4;
9079     NewOpc = ARMISD::VLD4DUP;
9080   } else {
9081     return false;
9082   }
9083
9084   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9085   // numbers match the load.
9086   unsigned VLDLaneNo =
9087     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9088   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9089        UI != UE; ++UI) {
9090     // Ignore uses of the chain result.
9091     if (UI.getUse().getResNo() == NumVecs)
9092       continue;
9093     SDNode *User = *UI;
9094     if (User->getOpcode() != ARMISD::VDUPLANE ||
9095         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9096       return false;
9097   }
9098
9099   // Create the vldN-dup node.
9100   EVT Tys[5];
9101   unsigned n;
9102   for (n = 0; n < NumVecs; ++n)
9103     Tys[n] = VT;
9104   Tys[n] = MVT::Other;
9105   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9106   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9107   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9108   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9109                                            Ops, VLDMemInt->getMemoryVT(),
9110                                            VLDMemInt->getMemOperand());
9111
9112   // Update the uses.
9113   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9114        UI != UE; ++UI) {
9115     unsigned ResNo = UI.getUse().getResNo();
9116     // Ignore uses of the chain result.
9117     if (ResNo == NumVecs)
9118       continue;
9119     SDNode *User = *UI;
9120     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9121   }
9122
9123   // Now the vldN-lane intrinsic is dead except for its chain result.
9124   // Update uses of the chain.
9125   std::vector<SDValue> VLDDupResults;
9126   for (unsigned n = 0; n < NumVecs; ++n)
9127     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9128   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9129   DCI.CombineTo(VLD, VLDDupResults);
9130
9131   return true;
9132 }
9133
9134 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9135 /// ARMISD::VDUPLANE.
9136 static SDValue PerformVDUPLANECombine(SDNode *N,
9137                                       TargetLowering::DAGCombinerInfo &DCI) {
9138   SDValue Op = N->getOperand(0);
9139
9140   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9141   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9142   if (CombineVLDDUP(N, DCI))
9143     return SDValue(N, 0);
9144
9145   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9146   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9147   while (Op.getOpcode() == ISD::BITCAST)
9148     Op = Op.getOperand(0);
9149   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9150     return SDValue();
9151
9152   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9153   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9154   // The canonical VMOV for a zero vector uses a 32-bit element size.
9155   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9156   unsigned EltBits;
9157   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9158     EltSize = 8;
9159   EVT VT = N->getValueType(0);
9160   if (EltSize > VT.getVectorElementType().getSizeInBits())
9161     return SDValue();
9162
9163   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9164 }
9165
9166 static SDValue PerformLOADCombine(SDNode *N,
9167                                   TargetLowering::DAGCombinerInfo &DCI) {
9168   EVT VT = N->getValueType(0);
9169
9170   // If this is a legal vector load, try to combine it into a VLD1_UPD.
9171   if (ISD::isNormalLoad(N) && VT.isVector() &&
9172       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9173     return CombineBaseUpdate(N, DCI);
9174
9175   return SDValue();
9176 }
9177
9178 /// PerformSTORECombine - Target-specific dag combine xforms for
9179 /// ISD::STORE.
9180 static SDValue PerformSTORECombine(SDNode *N,
9181                                    TargetLowering::DAGCombinerInfo &DCI) {
9182   StoreSDNode *St = cast<StoreSDNode>(N);
9183   if (St->isVolatile())
9184     return SDValue();
9185
9186   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
9187   // pack all of the elements in one place.  Next, store to memory in fewer
9188   // chunks.
9189   SDValue StVal = St->getValue();
9190   EVT VT = StVal.getValueType();
9191   if (St->isTruncatingStore() && VT.isVector()) {
9192     SelectionDAG &DAG = DCI.DAG;
9193     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9194     EVT StVT = St->getMemoryVT();
9195     unsigned NumElems = VT.getVectorNumElements();
9196     assert(StVT != VT && "Cannot truncate to the same type");
9197     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
9198     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
9199
9200     // From, To sizes and ElemCount must be pow of two
9201     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
9202
9203     // We are going to use the original vector elt for storing.
9204     // Accumulated smaller vector elements must be a multiple of the store size.
9205     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
9206
9207     unsigned SizeRatio  = FromEltSz / ToEltSz;
9208     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
9209
9210     // Create a type on which we perform the shuffle.
9211     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9212                                      NumElems*SizeRatio);
9213     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9214
9215     SDLoc DL(St);
9216     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9217     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9218     for (unsigned i = 0; i < NumElems; ++i)
9219       ShuffleVec[i] = TLI.isBigEndian() ? (i+1) * SizeRatio - 1 : i * SizeRatio;
9220
9221     // Can't shuffle using an illegal type.
9222     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9223
9224     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9225                                 DAG.getUNDEF(WideVec.getValueType()),
9226                                 ShuffleVec.data());
9227     // At this point all of the data is stored at the bottom of the
9228     // register. We now need to save it to mem.
9229
9230     // Find the largest store unit
9231     MVT StoreType = MVT::i8;
9232     for (MVT Tp : MVT::integer_valuetypes()) {
9233       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9234         StoreType = Tp;
9235     }
9236     // Didn't find a legal store type.
9237     if (!TLI.isTypeLegal(StoreType))
9238       return SDValue();
9239
9240     // Bitcast the original vector into a vector of store-size units
9241     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9242             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9243     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9244     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9245     SmallVector<SDValue, 8> Chains;
9246     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8, DL,
9247                                         TLI.getPointerTy());
9248     SDValue BasePtr = St->getBasePtr();
9249
9250     // Perform one or more big stores into memory.
9251     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9252     for (unsigned I = 0; I < E; I++) {
9253       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9254                                    StoreType, ShuffWide,
9255                                    DAG.getIntPtrConstant(I, DL));
9256       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9257                                 St->getPointerInfo(), St->isVolatile(),
9258                                 St->isNonTemporal(), St->getAlignment());
9259       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9260                             Increment);
9261       Chains.push_back(Ch);
9262     }
9263     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
9264   }
9265
9266   if (!ISD::isNormalStore(St))
9267     return SDValue();
9268
9269   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9270   // ARM stores of arguments in the same cache line.
9271   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9272       StVal.getNode()->hasOneUse()) {
9273     SelectionDAG  &DAG = DCI.DAG;
9274     bool isBigEndian = DAG.getTargetLoweringInfo().isBigEndian();
9275     SDLoc DL(St);
9276     SDValue BasePtr = St->getBasePtr();
9277     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9278                                   StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
9279                                   BasePtr, St->getPointerInfo(), St->isVolatile(),
9280                                   St->isNonTemporal(), St->getAlignment());
9281
9282     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9283                                     DAG.getConstant(4, DL, MVT::i32));
9284     return DAG.getStore(NewST1.getValue(0), DL,
9285                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
9286                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9287                         St->isNonTemporal(),
9288                         std::min(4U, St->getAlignment() / 2));
9289   }
9290
9291   if (StVal.getValueType() == MVT::i64 &&
9292       StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9293
9294     // Bitcast an i64 store extracted from a vector to f64.
9295     // Otherwise, the i64 value will be legalized to a pair of i32 values.
9296     SelectionDAG &DAG = DCI.DAG;
9297     SDLoc dl(StVal);
9298     SDValue IntVec = StVal.getOperand(0);
9299     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9300                                    IntVec.getValueType().getVectorNumElements());
9301     SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9302     SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9303                                  Vec, StVal.getOperand(1));
9304     dl = SDLoc(N);
9305     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9306     // Make the DAGCombiner fold the bitcasts.
9307     DCI.AddToWorklist(Vec.getNode());
9308     DCI.AddToWorklist(ExtElt.getNode());
9309     DCI.AddToWorklist(V.getNode());
9310     return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9311                         St->getPointerInfo(), St->isVolatile(),
9312                         St->isNonTemporal(), St->getAlignment(),
9313                         St->getAAInfo());
9314   }
9315
9316   // If this is a legal vector store, try to combine it into a VST1_UPD.
9317   if (ISD::isNormalStore(N) && VT.isVector() &&
9318       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9319     return CombineBaseUpdate(N, DCI);
9320
9321   return SDValue();
9322 }
9323
9324 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9325 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9326 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9327 {
9328   integerPart cN;
9329   integerPart c0 = 0;
9330   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9331        I != E; I++) {
9332     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9333     if (!C)
9334       return false;
9335
9336     bool isExact;
9337     APFloat APF = C->getValueAPF();
9338     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9339         != APFloat::opOK || !isExact)
9340       return false;
9341
9342     c0 = (I == 0) ? cN : c0;
9343     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9344       return false;
9345   }
9346   C = c0;
9347   return true;
9348 }
9349
9350 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9351 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9352 /// when the VMUL has a constant operand that is a power of 2.
9353 ///
9354 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9355 ///  vmul.f32        d16, d17, d16
9356 ///  vcvt.s32.f32    d16, d16
9357 /// becomes:
9358 ///  vcvt.s32.f32    d16, d16, #3
9359 static SDValue PerformVCVTCombine(SDNode *N,
9360                                   TargetLowering::DAGCombinerInfo &DCI,
9361                                   const ARMSubtarget *Subtarget) {
9362   SelectionDAG &DAG = DCI.DAG;
9363   SDValue Op = N->getOperand(0);
9364
9365   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9366       Op.getOpcode() != ISD::FMUL)
9367     return SDValue();
9368
9369   uint64_t C;
9370   SDValue N0 = Op->getOperand(0);
9371   SDValue ConstVec = Op->getOperand(1);
9372   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9373
9374   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9375       !isConstVecPow2(ConstVec, isSigned, C))
9376     return SDValue();
9377
9378   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9379   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9380   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9381   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32 ||
9382       NumLanes > 4) {
9383     // These instructions only exist converting from f32 to i32. We can handle
9384     // smaller integers by generating an extra truncate, but larger ones would
9385     // be lossy. We also can't handle more then 4 lanes, since these intructions
9386     // only support v2i32/v4i32 types.
9387     return SDValue();
9388   }
9389
9390   SDLoc dl(N);
9391   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9392     Intrinsic::arm_neon_vcvtfp2fxu;
9393   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9394                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9395                                  DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9396                                  N0,
9397                                  DAG.getConstant(Log2_64(C), dl, MVT::i32));
9398
9399   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9400     FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
9401
9402   return FixConv;
9403 }
9404
9405 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9406 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9407 /// when the VDIV has a constant operand that is a power of 2.
9408 ///
9409 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9410 ///  vcvt.f32.s32    d16, d16
9411 ///  vdiv.f32        d16, d17, d16
9412 /// becomes:
9413 ///  vcvt.f32.s32    d16, d16, #3
9414 static SDValue PerformVDIVCombine(SDNode *N,
9415                                   TargetLowering::DAGCombinerInfo &DCI,
9416                                   const ARMSubtarget *Subtarget) {
9417   SelectionDAG &DAG = DCI.DAG;
9418   SDValue Op = N->getOperand(0);
9419   unsigned OpOpcode = Op.getNode()->getOpcode();
9420
9421   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9422       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9423     return SDValue();
9424
9425   uint64_t C;
9426   SDValue ConstVec = N->getOperand(1);
9427   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9428
9429   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9430       !isConstVecPow2(ConstVec, isSigned, C))
9431     return SDValue();
9432
9433   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9434   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9435   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9436     // These instructions only exist converting from i32 to f32. We can handle
9437     // smaller integers by generating an extra extend, but larger ones would
9438     // be lossy.
9439     return SDValue();
9440   }
9441
9442   SDLoc dl(N);
9443   SDValue ConvInput = Op.getOperand(0);
9444   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9445   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9446     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9447                             dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9448                             ConvInput);
9449
9450   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9451     Intrinsic::arm_neon_vcvtfxu2fp;
9452   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9453                      Op.getValueType(),
9454                      DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9455                      ConvInput, DAG.getConstant(Log2_64(C), dl, MVT::i32));
9456 }
9457
9458 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9459 /// operand of a vector shift operation, where all the elements of the
9460 /// build_vector must have the same constant integer value.
9461 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9462   // Ignore bit_converts.
9463   while (Op.getOpcode() == ISD::BITCAST)
9464     Op = Op.getOperand(0);
9465   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9466   APInt SplatBits, SplatUndef;
9467   unsigned SplatBitSize;
9468   bool HasAnyUndefs;
9469   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9470                                       HasAnyUndefs, ElementBits) ||
9471       SplatBitSize > ElementBits)
9472     return false;
9473   Cnt = SplatBits.getSExtValue();
9474   return true;
9475 }
9476
9477 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9478 /// operand of a vector shift left operation.  That value must be in the range:
9479 ///   0 <= Value < ElementBits for a left shift; or
9480 ///   0 <= Value <= ElementBits for a long left shift.
9481 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9482   assert(VT.isVector() && "vector shift count is not a vector type");
9483   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9484   if (! getVShiftImm(Op, ElementBits, Cnt))
9485     return false;
9486   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9487 }
9488
9489 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9490 /// operand of a vector shift right operation.  For a shift opcode, the value
9491 /// is positive, but for an intrinsic the value count must be negative. The
9492 /// absolute value must be in the range:
9493 ///   1 <= |Value| <= ElementBits for a right shift; or
9494 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9495 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9496                          int64_t &Cnt) {
9497   assert(VT.isVector() && "vector shift count is not a vector type");
9498   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9499   if (! getVShiftImm(Op, ElementBits, Cnt))
9500     return false;
9501   if (isIntrinsic)
9502     Cnt = -Cnt;
9503   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9504 }
9505
9506 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9507 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9508   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9509   switch (IntNo) {
9510   default:
9511     // Don't do anything for most intrinsics.
9512     break;
9513
9514   // Vector shifts: check for immediate versions and lower them.
9515   // Note: This is done during DAG combining instead of DAG legalizing because
9516   // the build_vectors for 64-bit vector element shift counts are generally
9517   // not legal, and it is hard to see their values after they get legalized to
9518   // loads from a constant pool.
9519   case Intrinsic::arm_neon_vshifts:
9520   case Intrinsic::arm_neon_vshiftu:
9521   case Intrinsic::arm_neon_vrshifts:
9522   case Intrinsic::arm_neon_vrshiftu:
9523   case Intrinsic::arm_neon_vrshiftn:
9524   case Intrinsic::arm_neon_vqshifts:
9525   case Intrinsic::arm_neon_vqshiftu:
9526   case Intrinsic::arm_neon_vqshiftsu:
9527   case Intrinsic::arm_neon_vqshiftns:
9528   case Intrinsic::arm_neon_vqshiftnu:
9529   case Intrinsic::arm_neon_vqshiftnsu:
9530   case Intrinsic::arm_neon_vqrshiftns:
9531   case Intrinsic::arm_neon_vqrshiftnu:
9532   case Intrinsic::arm_neon_vqrshiftnsu: {
9533     EVT VT = N->getOperand(1).getValueType();
9534     int64_t Cnt;
9535     unsigned VShiftOpc = 0;
9536
9537     switch (IntNo) {
9538     case Intrinsic::arm_neon_vshifts:
9539     case Intrinsic::arm_neon_vshiftu:
9540       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9541         VShiftOpc = ARMISD::VSHL;
9542         break;
9543       }
9544       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9545         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9546                      ARMISD::VSHRs : ARMISD::VSHRu);
9547         break;
9548       }
9549       return SDValue();
9550
9551     case Intrinsic::arm_neon_vrshifts:
9552     case Intrinsic::arm_neon_vrshiftu:
9553       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9554         break;
9555       return SDValue();
9556
9557     case Intrinsic::arm_neon_vqshifts:
9558     case Intrinsic::arm_neon_vqshiftu:
9559       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9560         break;
9561       return SDValue();
9562
9563     case Intrinsic::arm_neon_vqshiftsu:
9564       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9565         break;
9566       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9567
9568     case Intrinsic::arm_neon_vrshiftn:
9569     case Intrinsic::arm_neon_vqshiftns:
9570     case Intrinsic::arm_neon_vqshiftnu:
9571     case Intrinsic::arm_neon_vqshiftnsu:
9572     case Intrinsic::arm_neon_vqrshiftns:
9573     case Intrinsic::arm_neon_vqrshiftnu:
9574     case Intrinsic::arm_neon_vqrshiftnsu:
9575       // Narrowing shifts require an immediate right shift.
9576       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9577         break;
9578       llvm_unreachable("invalid shift count for narrowing vector shift "
9579                        "intrinsic");
9580
9581     default:
9582       llvm_unreachable("unhandled vector shift");
9583     }
9584
9585     switch (IntNo) {
9586     case Intrinsic::arm_neon_vshifts:
9587     case Intrinsic::arm_neon_vshiftu:
9588       // Opcode already set above.
9589       break;
9590     case Intrinsic::arm_neon_vrshifts:
9591       VShiftOpc = ARMISD::VRSHRs; break;
9592     case Intrinsic::arm_neon_vrshiftu:
9593       VShiftOpc = ARMISD::VRSHRu; break;
9594     case Intrinsic::arm_neon_vrshiftn:
9595       VShiftOpc = ARMISD::VRSHRN; break;
9596     case Intrinsic::arm_neon_vqshifts:
9597       VShiftOpc = ARMISD::VQSHLs; break;
9598     case Intrinsic::arm_neon_vqshiftu:
9599       VShiftOpc = ARMISD::VQSHLu; break;
9600     case Intrinsic::arm_neon_vqshiftsu:
9601       VShiftOpc = ARMISD::VQSHLsu; break;
9602     case Intrinsic::arm_neon_vqshiftns:
9603       VShiftOpc = ARMISD::VQSHRNs; break;
9604     case Intrinsic::arm_neon_vqshiftnu:
9605       VShiftOpc = ARMISD::VQSHRNu; break;
9606     case Intrinsic::arm_neon_vqshiftnsu:
9607       VShiftOpc = ARMISD::VQSHRNsu; break;
9608     case Intrinsic::arm_neon_vqrshiftns:
9609       VShiftOpc = ARMISD::VQRSHRNs; break;
9610     case Intrinsic::arm_neon_vqrshiftnu:
9611       VShiftOpc = ARMISD::VQRSHRNu; break;
9612     case Intrinsic::arm_neon_vqrshiftnsu:
9613       VShiftOpc = ARMISD::VQRSHRNsu; break;
9614     }
9615
9616     SDLoc dl(N);
9617     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
9618                        N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
9619   }
9620
9621   case Intrinsic::arm_neon_vshiftins: {
9622     EVT VT = N->getOperand(1).getValueType();
9623     int64_t Cnt;
9624     unsigned VShiftOpc = 0;
9625
9626     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9627       VShiftOpc = ARMISD::VSLI;
9628     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9629       VShiftOpc = ARMISD::VSRI;
9630     else {
9631       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9632     }
9633
9634     SDLoc dl(N);
9635     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
9636                        N->getOperand(1), N->getOperand(2),
9637                        DAG.getConstant(Cnt, dl, MVT::i32));
9638   }
9639
9640   case Intrinsic::arm_neon_vqrshifts:
9641   case Intrinsic::arm_neon_vqrshiftu:
9642     // No immediate versions of these to check for.
9643     break;
9644   }
9645
9646   return SDValue();
9647 }
9648
9649 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9650 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9651 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9652 /// vector element shift counts are generally not legal, and it is hard to see
9653 /// their values after they get legalized to loads from a constant pool.
9654 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9655                                    const ARMSubtarget *ST) {
9656   EVT VT = N->getValueType(0);
9657   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9658     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9659     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9660     SDValue N1 = N->getOperand(1);
9661     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9662       SDValue N0 = N->getOperand(0);
9663       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9664           DAG.MaskedValueIsZero(N0.getOperand(0),
9665                                 APInt::getHighBitsSet(32, 16)))
9666         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9667     }
9668   }
9669
9670   // Nothing to be done for scalar shifts.
9671   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9672   if (!VT.isVector() || !TLI.isTypeLegal(VT))
9673     return SDValue();
9674
9675   assert(ST->hasNEON() && "unexpected vector shift");
9676   int64_t Cnt;
9677
9678   switch (N->getOpcode()) {
9679   default: llvm_unreachable("unexpected shift opcode");
9680
9681   case ISD::SHL:
9682     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
9683       SDLoc dl(N);
9684       return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
9685                          DAG.getConstant(Cnt, dl, MVT::i32));
9686     }
9687     break;
9688
9689   case ISD::SRA:
9690   case ISD::SRL:
9691     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9692       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9693                             ARMISD::VSHRs : ARMISD::VSHRu);
9694       SDLoc dl(N);
9695       return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
9696                          DAG.getConstant(Cnt, dl, MVT::i32));
9697     }
9698   }
9699   return SDValue();
9700 }
9701
9702 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9703 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9704 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9705                                     const ARMSubtarget *ST) {
9706   SDValue N0 = N->getOperand(0);
9707
9708   // Check for sign- and zero-extensions of vector extract operations of 8-
9709   // and 16-bit vector elements.  NEON supports these directly.  They are
9710   // handled during DAG combining because type legalization will promote them
9711   // to 32-bit types and it is messy to recognize the operations after that.
9712   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9713     SDValue Vec = N0.getOperand(0);
9714     SDValue Lane = N0.getOperand(1);
9715     EVT VT = N->getValueType(0);
9716     EVT EltVT = N0.getValueType();
9717     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9718
9719     if (VT == MVT::i32 &&
9720         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9721         TLI.isTypeLegal(Vec.getValueType()) &&
9722         isa<ConstantSDNode>(Lane)) {
9723
9724       unsigned Opc = 0;
9725       switch (N->getOpcode()) {
9726       default: llvm_unreachable("unexpected opcode");
9727       case ISD::SIGN_EXTEND:
9728         Opc = ARMISD::VGETLANEs;
9729         break;
9730       case ISD::ZERO_EXTEND:
9731       case ISD::ANY_EXTEND:
9732         Opc = ARMISD::VGETLANEu;
9733         break;
9734       }
9735       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9736     }
9737   }
9738
9739   return SDValue();
9740 }
9741
9742 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9743 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9744 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9745                                        const ARMSubtarget *ST) {
9746   // If the target supports NEON, try to use vmax/vmin instructions for f32
9747   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
9748   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
9749   // a NaN; only do the transformation when it matches that behavior.
9750
9751   // For now only do this when using NEON for FP operations; if using VFP, it
9752   // is not obvious that the benefit outweighs the cost of switching to the
9753   // NEON pipeline.
9754   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9755       N->getValueType(0) != MVT::f32)
9756     return SDValue();
9757
9758   SDValue CondLHS = N->getOperand(0);
9759   SDValue CondRHS = N->getOperand(1);
9760   SDValue LHS = N->getOperand(2);
9761   SDValue RHS = N->getOperand(3);
9762   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9763
9764   unsigned Opcode = 0;
9765   bool IsReversed;
9766   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9767     IsReversed = false; // x CC y ? x : y
9768   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9769     IsReversed = true ; // x CC y ? y : x
9770   } else {
9771     return SDValue();
9772   }
9773
9774   bool IsUnordered;
9775   switch (CC) {
9776   default: break;
9777   case ISD::SETOLT:
9778   case ISD::SETOLE:
9779   case ISD::SETLT:
9780   case ISD::SETLE:
9781   case ISD::SETULT:
9782   case ISD::SETULE:
9783     // If LHS is NaN, an ordered comparison will be false and the result will
9784     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
9785     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9786     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9787     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9788       break;
9789     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9790     // will return -0, so vmin can only be used for unsafe math or if one of
9791     // the operands is known to be nonzero.
9792     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9793         !DAG.getTarget().Options.UnsafeFPMath &&
9794         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9795       break;
9796     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9797     break;
9798
9799   case ISD::SETOGT:
9800   case ISD::SETOGE:
9801   case ISD::SETGT:
9802   case ISD::SETGE:
9803   case ISD::SETUGT:
9804   case ISD::SETUGE:
9805     // If LHS is NaN, an ordered comparison will be false and the result will
9806     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
9807     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9808     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9809     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9810       break;
9811     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9812     // will return +0, so vmax can only be used for unsafe math or if one of
9813     // the operands is known to be nonzero.
9814     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9815         !DAG.getTarget().Options.UnsafeFPMath &&
9816         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9817       break;
9818     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9819     break;
9820   }
9821
9822   if (!Opcode)
9823     return SDValue();
9824   return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9825 }
9826
9827 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9828 SDValue
9829 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9830   SDValue Cmp = N->getOperand(4);
9831   if (Cmp.getOpcode() != ARMISD::CMPZ)
9832     // Only looking at EQ and NE cases.
9833     return SDValue();
9834
9835   EVT VT = N->getValueType(0);
9836   SDLoc dl(N);
9837   SDValue LHS = Cmp.getOperand(0);
9838   SDValue RHS = Cmp.getOperand(1);
9839   SDValue FalseVal = N->getOperand(0);
9840   SDValue TrueVal = N->getOperand(1);
9841   SDValue ARMcc = N->getOperand(2);
9842   ARMCC::CondCodes CC =
9843     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9844
9845   // Simplify
9846   //   mov     r1, r0
9847   //   cmp     r1, x
9848   //   mov     r0, y
9849   //   moveq   r0, x
9850   // to
9851   //   cmp     r0, x
9852   //   movne   r0, y
9853   //
9854   //   mov     r1, r0
9855   //   cmp     r1, x
9856   //   mov     r0, x
9857   //   movne   r0, y
9858   // to
9859   //   cmp     r0, x
9860   //   movne   r0, y
9861   /// FIXME: Turn this into a target neutral optimization?
9862   SDValue Res;
9863   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9864     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9865                       N->getOperand(3), Cmp);
9866   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9867     SDValue ARMcc;
9868     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9869     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9870                       N->getOperand(3), NewCmp);
9871   }
9872
9873   if (Res.getNode()) {
9874     APInt KnownZero, KnownOne;
9875     DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
9876     // Capture demanded bits information that would be otherwise lost.
9877     if (KnownZero == 0xfffffffe)
9878       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9879                         DAG.getValueType(MVT::i1));
9880     else if (KnownZero == 0xffffff00)
9881       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9882                         DAG.getValueType(MVT::i8));
9883     else if (KnownZero == 0xffff0000)
9884       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9885                         DAG.getValueType(MVT::i16));
9886   }
9887
9888   return Res;
9889 }
9890
9891 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9892                                              DAGCombinerInfo &DCI) const {
9893   switch (N->getOpcode()) {
9894   default: break;
9895   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
9896   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
9897   case ISD::SUB:        return PerformSUBCombine(N, DCI);
9898   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
9899   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
9900   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
9901   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
9902   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
9903   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
9904   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9905   case ISD::STORE:      return PerformSTORECombine(N, DCI);
9906   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
9907   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9908   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9909   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9910   case ISD::FP_TO_SINT:
9911   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9912   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
9913   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9914   case ISD::SHL:
9915   case ISD::SRA:
9916   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
9917   case ISD::SIGN_EXTEND:
9918   case ISD::ZERO_EXTEND:
9919   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9920   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9921   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9922   case ISD::LOAD:       return PerformLOADCombine(N, DCI);
9923   case ARMISD::VLD2DUP:
9924   case ARMISD::VLD3DUP:
9925   case ARMISD::VLD4DUP:
9926     return PerformVLDCombine(N, DCI);
9927   case ARMISD::BUILD_VECTOR:
9928     return PerformARMBUILD_VECTORCombine(N, DCI);
9929   case ISD::INTRINSIC_VOID:
9930   case ISD::INTRINSIC_W_CHAIN:
9931     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9932     case Intrinsic::arm_neon_vld1:
9933     case Intrinsic::arm_neon_vld2:
9934     case Intrinsic::arm_neon_vld3:
9935     case Intrinsic::arm_neon_vld4:
9936     case Intrinsic::arm_neon_vld2lane:
9937     case Intrinsic::arm_neon_vld3lane:
9938     case Intrinsic::arm_neon_vld4lane:
9939     case Intrinsic::arm_neon_vst1:
9940     case Intrinsic::arm_neon_vst2:
9941     case Intrinsic::arm_neon_vst3:
9942     case Intrinsic::arm_neon_vst4:
9943     case Intrinsic::arm_neon_vst2lane:
9944     case Intrinsic::arm_neon_vst3lane:
9945     case Intrinsic::arm_neon_vst4lane:
9946       return PerformVLDCombine(N, DCI);
9947     default: break;
9948     }
9949     break;
9950   }
9951   return SDValue();
9952 }
9953
9954 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9955                                                           EVT VT) const {
9956   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9957 }
9958
9959 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
9960                                                        unsigned,
9961                                                        unsigned,
9962                                                        bool *Fast) const {
9963   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9964   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9965
9966   switch (VT.getSimpleVT().SimpleTy) {
9967   default:
9968     return false;
9969   case MVT::i8:
9970   case MVT::i16:
9971   case MVT::i32: {
9972     // Unaligned access can use (for example) LRDB, LRDH, LDR
9973     if (AllowsUnaligned) {
9974       if (Fast)
9975         *Fast = Subtarget->hasV7Ops();
9976       return true;
9977     }
9978     return false;
9979   }
9980   case MVT::f64:
9981   case MVT::v2f64: {
9982     // For any little-endian targets with neon, we can support unaligned ld/st
9983     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9984     // A big-endian target may also explicitly support unaligned accesses
9985     if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9986       if (Fast)
9987         *Fast = true;
9988       return true;
9989     }
9990     return false;
9991   }
9992   }
9993 }
9994
9995 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9996                        unsigned AlignCheck) {
9997   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9998           (DstAlign == 0 || DstAlign % AlignCheck == 0));
9999 }
10000
10001 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10002                                            unsigned DstAlign, unsigned SrcAlign,
10003                                            bool IsMemset, bool ZeroMemset,
10004                                            bool MemcpyStrSrc,
10005                                            MachineFunction &MF) const {
10006   const Function *F = MF.getFunction();
10007
10008   // See if we can use NEON instructions for this...
10009   if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
10010       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10011     bool Fast;
10012     if (Size >= 16 &&
10013         (memOpAlign(SrcAlign, DstAlign, 16) ||
10014          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
10015       return MVT::v2f64;
10016     } else if (Size >= 8 &&
10017                (memOpAlign(SrcAlign, DstAlign, 8) ||
10018                 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
10019                  Fast))) {
10020       return MVT::f64;
10021     }
10022   }
10023
10024   // Lowering to i32/i16 if the size permits.
10025   if (Size >= 4)
10026     return MVT::i32;
10027   else if (Size >= 2)
10028     return MVT::i16;
10029
10030   // Let the target-independent logic figure it out.
10031   return MVT::Other;
10032 }
10033
10034 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10035   if (Val.getOpcode() != ISD::LOAD)
10036     return false;
10037
10038   EVT VT1 = Val.getValueType();
10039   if (!VT1.isSimple() || !VT1.isInteger() ||
10040       !VT2.isSimple() || !VT2.isInteger())
10041     return false;
10042
10043   switch (VT1.getSimpleVT().SimpleTy) {
10044   default: break;
10045   case MVT::i1:
10046   case MVT::i8:
10047   case MVT::i16:
10048     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10049     return true;
10050   }
10051
10052   return false;
10053 }
10054
10055 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
10056   EVT VT = ExtVal.getValueType();
10057
10058   if (!isTypeLegal(VT))
10059     return false;
10060
10061   // Don't create a loadext if we can fold the extension into a wide/long
10062   // instruction.
10063   // If there's more than one user instruction, the loadext is desirable no
10064   // matter what.  There can be two uses by the same instruction.
10065   if (ExtVal->use_empty() ||
10066       !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
10067     return true;
10068
10069   SDNode *U = *ExtVal->use_begin();
10070   if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
10071        U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
10072     return false;
10073
10074   return true;
10075 }
10076
10077 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10078   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10079     return false;
10080
10081   if (!isTypeLegal(EVT::getEVT(Ty1)))
10082     return false;
10083
10084   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10085
10086   // Assuming the caller doesn't have a zeroext or signext return parameter,
10087   // truncation all the way down to i1 is valid.
10088   return true;
10089 }
10090
10091
10092 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10093   if (V < 0)
10094     return false;
10095
10096   unsigned Scale = 1;
10097   switch (VT.getSimpleVT().SimpleTy) {
10098   default: return false;
10099   case MVT::i1:
10100   case MVT::i8:
10101     // Scale == 1;
10102     break;
10103   case MVT::i16:
10104     // Scale == 2;
10105     Scale = 2;
10106     break;
10107   case MVT::i32:
10108     // Scale == 4;
10109     Scale = 4;
10110     break;
10111   }
10112
10113   if ((V & (Scale - 1)) != 0)
10114     return false;
10115   V /= Scale;
10116   return V == (V & ((1LL << 5) - 1));
10117 }
10118
10119 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10120                                       const ARMSubtarget *Subtarget) {
10121   bool isNeg = false;
10122   if (V < 0) {
10123     isNeg = true;
10124     V = - V;
10125   }
10126
10127   switch (VT.getSimpleVT().SimpleTy) {
10128   default: return false;
10129   case MVT::i1:
10130   case MVT::i8:
10131   case MVT::i16:
10132   case MVT::i32:
10133     // + imm12 or - imm8
10134     if (isNeg)
10135       return V == (V & ((1LL << 8) - 1));
10136     return V == (V & ((1LL << 12) - 1));
10137   case MVT::f32:
10138   case MVT::f64:
10139     // Same as ARM mode. FIXME: NEON?
10140     if (!Subtarget->hasVFP2())
10141       return false;
10142     if ((V & 3) != 0)
10143       return false;
10144     V >>= 2;
10145     return V == (V & ((1LL << 8) - 1));
10146   }
10147 }
10148
10149 /// isLegalAddressImmediate - Return true if the integer value can be used
10150 /// as the offset of the target addressing mode for load / store of the
10151 /// given type.
10152 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10153                                     const ARMSubtarget *Subtarget) {
10154   if (V == 0)
10155     return true;
10156
10157   if (!VT.isSimple())
10158     return false;
10159
10160   if (Subtarget->isThumb1Only())
10161     return isLegalT1AddressImmediate(V, VT);
10162   else if (Subtarget->isThumb2())
10163     return isLegalT2AddressImmediate(V, VT, Subtarget);
10164
10165   // ARM mode.
10166   if (V < 0)
10167     V = - V;
10168   switch (VT.getSimpleVT().SimpleTy) {
10169   default: return false;
10170   case MVT::i1:
10171   case MVT::i8:
10172   case MVT::i32:
10173     // +- imm12
10174     return V == (V & ((1LL << 12) - 1));
10175   case MVT::i16:
10176     // +- imm8
10177     return V == (V & ((1LL << 8) - 1));
10178   case MVT::f32:
10179   case MVT::f64:
10180     if (!Subtarget->hasVFP2()) // FIXME: NEON?
10181       return false;
10182     if ((V & 3) != 0)
10183       return false;
10184     V >>= 2;
10185     return V == (V & ((1LL << 8) - 1));
10186   }
10187 }
10188
10189 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10190                                                       EVT VT) const {
10191   int Scale = AM.Scale;
10192   if (Scale < 0)
10193     return false;
10194
10195   switch (VT.getSimpleVT().SimpleTy) {
10196   default: return false;
10197   case MVT::i1:
10198   case MVT::i8:
10199   case MVT::i16:
10200   case MVT::i32:
10201     if (Scale == 1)
10202       return true;
10203     // r + r << imm
10204     Scale = Scale & ~1;
10205     return Scale == 2 || Scale == 4 || Scale == 8;
10206   case MVT::i64:
10207     // r + r
10208     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10209       return true;
10210     return false;
10211   case MVT::isVoid:
10212     // Note, we allow "void" uses (basically, uses that aren't loads or
10213     // stores), because arm allows folding a scale into many arithmetic
10214     // operations.  This should be made more precise and revisited later.
10215
10216     // Allow r << imm, but the imm has to be a multiple of two.
10217     if (Scale & 1) return false;
10218     return isPowerOf2_32(Scale);
10219   }
10220 }
10221
10222 /// isLegalAddressingMode - Return true if the addressing mode represented
10223 /// by AM is legal for this target, for a load/store of the specified type.
10224 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10225                                               Type *Ty) const {
10226   EVT VT = getValueType(Ty, true);
10227   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10228     return false;
10229
10230   // Can never fold addr of global into load/store.
10231   if (AM.BaseGV)
10232     return false;
10233
10234   switch (AM.Scale) {
10235   case 0:  // no scale reg, must be "r+i" or "r", or "i".
10236     break;
10237   case 1:
10238     if (Subtarget->isThumb1Only())
10239       return false;
10240     // FALL THROUGH.
10241   default:
10242     // ARM doesn't support any R+R*scale+imm addr modes.
10243     if (AM.BaseOffs)
10244       return false;
10245
10246     if (!VT.isSimple())
10247       return false;
10248
10249     if (Subtarget->isThumb2())
10250       return isLegalT2ScaledAddressingMode(AM, VT);
10251
10252     int Scale = AM.Scale;
10253     switch (VT.getSimpleVT().SimpleTy) {
10254     default: return false;
10255     case MVT::i1:
10256     case MVT::i8:
10257     case MVT::i32:
10258       if (Scale < 0) Scale = -Scale;
10259       if (Scale == 1)
10260         return true;
10261       // r + r << imm
10262       return isPowerOf2_32(Scale & ~1);
10263     case MVT::i16:
10264     case MVT::i64:
10265       // r + r
10266       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10267         return true;
10268       return false;
10269
10270     case MVT::isVoid:
10271       // Note, we allow "void" uses (basically, uses that aren't loads or
10272       // stores), because arm allows folding a scale into many arithmetic
10273       // operations.  This should be made more precise and revisited later.
10274
10275       // Allow r << imm, but the imm has to be a multiple of two.
10276       if (Scale & 1) return false;
10277       return isPowerOf2_32(Scale);
10278     }
10279   }
10280   return true;
10281 }
10282
10283 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10284 /// icmp immediate, that is the target has icmp instructions which can compare
10285 /// a register against the immediate without having to materialize the
10286 /// immediate into a register.
10287 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10288   // Thumb2 and ARM modes can use cmn for negative immediates.
10289   if (!Subtarget->isThumb())
10290     return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
10291   if (Subtarget->isThumb2())
10292     return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
10293   // Thumb1 doesn't have cmn, and only 8-bit immediates.
10294   return Imm >= 0 && Imm <= 255;
10295 }
10296
10297 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10298 /// *or sub* immediate, that is the target has add or sub instructions which can
10299 /// add a register with the immediate without having to materialize the
10300 /// immediate into a register.
10301 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10302   // Same encoding for add/sub, just flip the sign.
10303   int64_t AbsImm = std::abs(Imm);
10304   if (!Subtarget->isThumb())
10305     return ARM_AM::getSOImmVal(AbsImm) != -1;
10306   if (Subtarget->isThumb2())
10307     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10308   // Thumb1 only has 8-bit unsigned immediate.
10309   return AbsImm >= 0 && AbsImm <= 255;
10310 }
10311
10312 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10313                                       bool isSEXTLoad, SDValue &Base,
10314                                       SDValue &Offset, bool &isInc,
10315                                       SelectionDAG &DAG) {
10316   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10317     return false;
10318
10319   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10320     // AddressingMode 3
10321     Base = Ptr->getOperand(0);
10322     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10323       int RHSC = (int)RHS->getZExtValue();
10324       if (RHSC < 0 && RHSC > -256) {
10325         assert(Ptr->getOpcode() == ISD::ADD);
10326         isInc = false;
10327         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10328         return true;
10329       }
10330     }
10331     isInc = (Ptr->getOpcode() == ISD::ADD);
10332     Offset = Ptr->getOperand(1);
10333     return true;
10334   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10335     // AddressingMode 2
10336     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10337       int RHSC = (int)RHS->getZExtValue();
10338       if (RHSC < 0 && RHSC > -0x1000) {
10339         assert(Ptr->getOpcode() == ISD::ADD);
10340         isInc = false;
10341         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10342         Base = Ptr->getOperand(0);
10343         return true;
10344       }
10345     }
10346
10347     if (Ptr->getOpcode() == ISD::ADD) {
10348       isInc = true;
10349       ARM_AM::ShiftOpc ShOpcVal=
10350         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10351       if (ShOpcVal != ARM_AM::no_shift) {
10352         Base = Ptr->getOperand(1);
10353         Offset = Ptr->getOperand(0);
10354       } else {
10355         Base = Ptr->getOperand(0);
10356         Offset = Ptr->getOperand(1);
10357       }
10358       return true;
10359     }
10360
10361     isInc = (Ptr->getOpcode() == ISD::ADD);
10362     Base = Ptr->getOperand(0);
10363     Offset = Ptr->getOperand(1);
10364     return true;
10365   }
10366
10367   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10368   return false;
10369 }
10370
10371 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10372                                      bool isSEXTLoad, SDValue &Base,
10373                                      SDValue &Offset, bool &isInc,
10374                                      SelectionDAG &DAG) {
10375   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10376     return false;
10377
10378   Base = Ptr->getOperand(0);
10379   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10380     int RHSC = (int)RHS->getZExtValue();
10381     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10382       assert(Ptr->getOpcode() == ISD::ADD);
10383       isInc = false;
10384       Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10385       return true;
10386     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10387       isInc = Ptr->getOpcode() == ISD::ADD;
10388       Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
10389       return true;
10390     }
10391   }
10392
10393   return false;
10394 }
10395
10396 /// getPreIndexedAddressParts - returns true by value, base pointer and
10397 /// offset pointer and addressing mode by reference if the node's address
10398 /// can be legally represented as pre-indexed load / store address.
10399 bool
10400 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10401                                              SDValue &Offset,
10402                                              ISD::MemIndexedMode &AM,
10403                                              SelectionDAG &DAG) const {
10404   if (Subtarget->isThumb1Only())
10405     return false;
10406
10407   EVT VT;
10408   SDValue Ptr;
10409   bool isSEXTLoad = false;
10410   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10411     Ptr = LD->getBasePtr();
10412     VT  = LD->getMemoryVT();
10413     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10414   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10415     Ptr = ST->getBasePtr();
10416     VT  = ST->getMemoryVT();
10417   } else
10418     return false;
10419
10420   bool isInc;
10421   bool isLegal = false;
10422   if (Subtarget->isThumb2())
10423     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10424                                        Offset, isInc, DAG);
10425   else
10426     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10427                                         Offset, isInc, DAG);
10428   if (!isLegal)
10429     return false;
10430
10431   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10432   return true;
10433 }
10434
10435 /// getPostIndexedAddressParts - returns true by value, base pointer and
10436 /// offset pointer and addressing mode by reference if this node can be
10437 /// combined with a load / store to form a post-indexed load / store.
10438 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10439                                                    SDValue &Base,
10440                                                    SDValue &Offset,
10441                                                    ISD::MemIndexedMode &AM,
10442                                                    SelectionDAG &DAG) const {
10443   if (Subtarget->isThumb1Only())
10444     return false;
10445
10446   EVT VT;
10447   SDValue Ptr;
10448   bool isSEXTLoad = false;
10449   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10450     VT  = LD->getMemoryVT();
10451     Ptr = LD->getBasePtr();
10452     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10453   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10454     VT  = ST->getMemoryVT();
10455     Ptr = ST->getBasePtr();
10456   } else
10457     return false;
10458
10459   bool isInc;
10460   bool isLegal = false;
10461   if (Subtarget->isThumb2())
10462     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10463                                        isInc, DAG);
10464   else
10465     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10466                                         isInc, DAG);
10467   if (!isLegal)
10468     return false;
10469
10470   if (Ptr != Base) {
10471     // Swap base ptr and offset to catch more post-index load / store when
10472     // it's legal. In Thumb2 mode, offset must be an immediate.
10473     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10474         !Subtarget->isThumb2())
10475       std::swap(Base, Offset);
10476
10477     // Post-indexed load / store update the base pointer.
10478     if (Ptr != Base)
10479       return false;
10480   }
10481
10482   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10483   return true;
10484 }
10485
10486 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10487                                                       APInt &KnownZero,
10488                                                       APInt &KnownOne,
10489                                                       const SelectionDAG &DAG,
10490                                                       unsigned Depth) const {
10491   unsigned BitWidth = KnownOne.getBitWidth();
10492   KnownZero = KnownOne = APInt(BitWidth, 0);
10493   switch (Op.getOpcode()) {
10494   default: break;
10495   case ARMISD::ADDC:
10496   case ARMISD::ADDE:
10497   case ARMISD::SUBC:
10498   case ARMISD::SUBE:
10499     // These nodes' second result is a boolean
10500     if (Op.getResNo() == 0)
10501       break;
10502     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10503     break;
10504   case ARMISD::CMOV: {
10505     // Bits are known zero/one if known on the LHS and RHS.
10506     DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10507     if (KnownZero == 0 && KnownOne == 0) return;
10508
10509     APInt KnownZeroRHS, KnownOneRHS;
10510     DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10511     KnownZero &= KnownZeroRHS;
10512     KnownOne  &= KnownOneRHS;
10513     return;
10514   }
10515   case ISD::INTRINSIC_W_CHAIN: {
10516     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10517     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10518     switch (IntID) {
10519     default: return;
10520     case Intrinsic::arm_ldaex:
10521     case Intrinsic::arm_ldrex: {
10522       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10523       unsigned MemBits = VT.getScalarType().getSizeInBits();
10524       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10525       return;
10526     }
10527     }
10528   }
10529   }
10530 }
10531
10532 //===----------------------------------------------------------------------===//
10533 //                           ARM Inline Assembly Support
10534 //===----------------------------------------------------------------------===//
10535
10536 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10537   // Looking for "rev" which is V6+.
10538   if (!Subtarget->hasV6Ops())
10539     return false;
10540
10541   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10542   std::string AsmStr = IA->getAsmString();
10543   SmallVector<StringRef, 4> AsmPieces;
10544   SplitString(AsmStr, AsmPieces, ";\n");
10545
10546   switch (AsmPieces.size()) {
10547   default: return false;
10548   case 1:
10549     AsmStr = AsmPieces[0];
10550     AsmPieces.clear();
10551     SplitString(AsmStr, AsmPieces, " \t,");
10552
10553     // rev $0, $1
10554     if (AsmPieces.size() == 3 &&
10555         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10556         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10557       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10558       if (Ty && Ty->getBitWidth() == 32)
10559         return IntrinsicLowering::LowerToByteSwap(CI);
10560     }
10561     break;
10562   }
10563
10564   return false;
10565 }
10566
10567 /// getConstraintType - Given a constraint letter, return the type of
10568 /// constraint it is for this target.
10569 ARMTargetLowering::ConstraintType
10570 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10571   if (Constraint.size() == 1) {
10572     switch (Constraint[0]) {
10573     default:  break;
10574     case 'l': return C_RegisterClass;
10575     case 'w': return C_RegisterClass;
10576     case 'h': return C_RegisterClass;
10577     case 'x': return C_RegisterClass;
10578     case 't': return C_RegisterClass;
10579     case 'j': return C_Other; // Constant for movw.
10580       // An address with a single base register. Due to the way we
10581       // currently handle addresses it is the same as an 'r' memory constraint.
10582     case 'Q': return C_Memory;
10583     }
10584   } else if (Constraint.size() == 2) {
10585     switch (Constraint[0]) {
10586     default: break;
10587     // All 'U+' constraints are addresses.
10588     case 'U': return C_Memory;
10589     }
10590   }
10591   return TargetLowering::getConstraintType(Constraint);
10592 }
10593
10594 /// Examine constraint type and operand type and determine a weight value.
10595 /// This object must already have been set up with the operand type
10596 /// and the current alternative constraint selected.
10597 TargetLowering::ConstraintWeight
10598 ARMTargetLowering::getSingleConstraintMatchWeight(
10599     AsmOperandInfo &info, const char *constraint) const {
10600   ConstraintWeight weight = CW_Invalid;
10601   Value *CallOperandVal = info.CallOperandVal;
10602     // If we don't have a value, we can't do a match,
10603     // but allow it at the lowest weight.
10604   if (!CallOperandVal)
10605     return CW_Default;
10606   Type *type = CallOperandVal->getType();
10607   // Look at the constraint type.
10608   switch (*constraint) {
10609   default:
10610     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10611     break;
10612   case 'l':
10613     if (type->isIntegerTy()) {
10614       if (Subtarget->isThumb())
10615         weight = CW_SpecificReg;
10616       else
10617         weight = CW_Register;
10618     }
10619     break;
10620   case 'w':
10621     if (type->isFloatingPointTy())
10622       weight = CW_Register;
10623     break;
10624   }
10625   return weight;
10626 }
10627
10628 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10629 RCPair
10630 ARMTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
10631                                                 const std::string &Constraint,
10632                                                 MVT VT) const {
10633   if (Constraint.size() == 1) {
10634     // GCC ARM Constraint Letters
10635     switch (Constraint[0]) {
10636     case 'l': // Low regs or general regs.
10637       if (Subtarget->isThumb())
10638         return RCPair(0U, &ARM::tGPRRegClass);
10639       return RCPair(0U, &ARM::GPRRegClass);
10640     case 'h': // High regs or no regs.
10641       if (Subtarget->isThumb())
10642         return RCPair(0U, &ARM::hGPRRegClass);
10643       break;
10644     case 'r':
10645       if (Subtarget->isThumb1Only())
10646         return RCPair(0U, &ARM::tGPRRegClass);
10647       return RCPair(0U, &ARM::GPRRegClass);
10648     case 'w':
10649       if (VT == MVT::Other)
10650         break;
10651       if (VT == MVT::f32)
10652         return RCPair(0U, &ARM::SPRRegClass);
10653       if (VT.getSizeInBits() == 64)
10654         return RCPair(0U, &ARM::DPRRegClass);
10655       if (VT.getSizeInBits() == 128)
10656         return RCPair(0U, &ARM::QPRRegClass);
10657       break;
10658     case 'x':
10659       if (VT == MVT::Other)
10660         break;
10661       if (VT == MVT::f32)
10662         return RCPair(0U, &ARM::SPR_8RegClass);
10663       if (VT.getSizeInBits() == 64)
10664         return RCPair(0U, &ARM::DPR_8RegClass);
10665       if (VT.getSizeInBits() == 128)
10666         return RCPair(0U, &ARM::QPR_8RegClass);
10667       break;
10668     case 't':
10669       if (VT == MVT::f32)
10670         return RCPair(0U, &ARM::SPRRegClass);
10671       break;
10672     }
10673   }
10674   if (StringRef("{cc}").equals_lower(Constraint))
10675     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10676
10677   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10678 }
10679
10680 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10681 /// vector.  If it is invalid, don't add anything to Ops.
10682 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10683                                                      std::string &Constraint,
10684                                                      std::vector<SDValue>&Ops,
10685                                                      SelectionDAG &DAG) const {
10686   SDValue Result;
10687
10688   // Currently only support length 1 constraints.
10689   if (Constraint.length() != 1) return;
10690
10691   char ConstraintLetter = Constraint[0];
10692   switch (ConstraintLetter) {
10693   default: break;
10694   case 'j':
10695   case 'I': case 'J': case 'K': case 'L':
10696   case 'M': case 'N': case 'O':
10697     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10698     if (!C)
10699       return;
10700
10701     int64_t CVal64 = C->getSExtValue();
10702     int CVal = (int) CVal64;
10703     // None of these constraints allow values larger than 32 bits.  Check
10704     // that the value fits in an int.
10705     if (CVal != CVal64)
10706       return;
10707
10708     switch (ConstraintLetter) {
10709       case 'j':
10710         // Constant suitable for movw, must be between 0 and
10711         // 65535.
10712         if (Subtarget->hasV6T2Ops())
10713           if (CVal >= 0 && CVal <= 65535)
10714             break;
10715         return;
10716       case 'I':
10717         if (Subtarget->isThumb1Only()) {
10718           // This must be a constant between 0 and 255, for ADD
10719           // immediates.
10720           if (CVal >= 0 && CVal <= 255)
10721             break;
10722         } else if (Subtarget->isThumb2()) {
10723           // A constant that can be used as an immediate value in a
10724           // data-processing instruction.
10725           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10726             break;
10727         } else {
10728           // A constant that can be used as an immediate value in a
10729           // data-processing instruction.
10730           if (ARM_AM::getSOImmVal(CVal) != -1)
10731             break;
10732         }
10733         return;
10734
10735       case 'J':
10736         if (Subtarget->isThumb()) {  // FIXME thumb2
10737           // This must be a constant between -255 and -1, for negated ADD
10738           // immediates. This can be used in GCC with an "n" modifier that
10739           // prints the negated value, for use with SUB instructions. It is
10740           // not useful otherwise but is implemented for compatibility.
10741           if (CVal >= -255 && CVal <= -1)
10742             break;
10743         } else {
10744           // This must be a constant between -4095 and 4095. It is not clear
10745           // what this constraint is intended for. Implemented for
10746           // compatibility with GCC.
10747           if (CVal >= -4095 && CVal <= 4095)
10748             break;
10749         }
10750         return;
10751
10752       case 'K':
10753         if (Subtarget->isThumb1Only()) {
10754           // A 32-bit value where only one byte has a nonzero value. Exclude
10755           // zero to match GCC. This constraint is used by GCC internally for
10756           // constants that can be loaded with a move/shift combination.
10757           // It is not useful otherwise but is implemented for compatibility.
10758           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10759             break;
10760         } else if (Subtarget->isThumb2()) {
10761           // A constant whose bitwise inverse can be used as an immediate
10762           // value in a data-processing instruction. This can be used in GCC
10763           // with a "B" modifier that prints the inverted value, for use with
10764           // BIC and MVN instructions. It is not useful otherwise but is
10765           // implemented for compatibility.
10766           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10767             break;
10768         } else {
10769           // A constant whose bitwise inverse can be used as an immediate
10770           // value in a data-processing instruction. This can be used in GCC
10771           // with a "B" modifier that prints the inverted value, for use with
10772           // BIC and MVN instructions. It is not useful otherwise but is
10773           // implemented for compatibility.
10774           if (ARM_AM::getSOImmVal(~CVal) != -1)
10775             break;
10776         }
10777         return;
10778
10779       case 'L':
10780         if (Subtarget->isThumb1Only()) {
10781           // This must be a constant between -7 and 7,
10782           // for 3-operand ADD/SUB immediate instructions.
10783           if (CVal >= -7 && CVal < 7)
10784             break;
10785         } else if (Subtarget->isThumb2()) {
10786           // A constant whose negation can be used as an immediate value in a
10787           // data-processing instruction. This can be used in GCC with an "n"
10788           // modifier that prints the negated value, for use with SUB
10789           // instructions. It is not useful otherwise but is implemented for
10790           // compatibility.
10791           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10792             break;
10793         } else {
10794           // A constant whose negation can be used as an immediate value in a
10795           // data-processing instruction. This can be used in GCC with an "n"
10796           // modifier that prints the negated value, for use with SUB
10797           // instructions. It is not useful otherwise but is implemented for
10798           // compatibility.
10799           if (ARM_AM::getSOImmVal(-CVal) != -1)
10800             break;
10801         }
10802         return;
10803
10804       case 'M':
10805         if (Subtarget->isThumb()) { // FIXME thumb2
10806           // This must be a multiple of 4 between 0 and 1020, for
10807           // ADD sp + immediate.
10808           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10809             break;
10810         } else {
10811           // A power of two or a constant between 0 and 32.  This is used in
10812           // GCC for the shift amount on shifted register operands, but it is
10813           // useful in general for any shift amounts.
10814           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10815             break;
10816         }
10817         return;
10818
10819       case 'N':
10820         if (Subtarget->isThumb()) {  // FIXME thumb2
10821           // This must be a constant between 0 and 31, for shift amounts.
10822           if (CVal >= 0 && CVal <= 31)
10823             break;
10824         }
10825         return;
10826
10827       case 'O':
10828         if (Subtarget->isThumb()) {  // FIXME thumb2
10829           // This must be a multiple of 4 between -508 and 508, for
10830           // ADD/SUB sp = sp + immediate.
10831           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10832             break;
10833         }
10834         return;
10835     }
10836     Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
10837     break;
10838   }
10839
10840   if (Result.getNode()) {
10841     Ops.push_back(Result);
10842     return;
10843   }
10844   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10845 }
10846
10847 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10848   assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10849   unsigned Opcode = Op->getOpcode();
10850   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10851          "Invalid opcode for Div/Rem lowering");
10852   bool isSigned = (Opcode == ISD::SDIVREM);
10853   EVT VT = Op->getValueType(0);
10854   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10855
10856   RTLIB::Libcall LC;
10857   switch (VT.getSimpleVT().SimpleTy) {
10858   default: llvm_unreachable("Unexpected request for libcall!");
10859   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
10860   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10861   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10862   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10863   }
10864
10865   SDValue InChain = DAG.getEntryNode();
10866
10867   TargetLowering::ArgListTy Args;
10868   TargetLowering::ArgListEntry Entry;
10869   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
10870     EVT ArgVT = Op->getOperand(i).getValueType();
10871     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10872     Entry.Node = Op->getOperand(i);
10873     Entry.Ty = ArgTy;
10874     Entry.isSExt = isSigned;
10875     Entry.isZExt = !isSigned;
10876     Args.push_back(Entry);
10877   }
10878
10879   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
10880                                          getPointerTy());
10881
10882   Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
10883
10884   SDLoc dl(Op);
10885   TargetLowering::CallLoweringInfo CLI(DAG);
10886   CLI.setDebugLoc(dl).setChain(InChain)
10887     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
10888     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
10889
10890   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
10891   return CallInfo.first;
10892 }
10893
10894 SDValue
10895 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
10896   assert(Subtarget->isTargetWindows() && "unsupported target platform");
10897   SDLoc DL(Op);
10898
10899   // Get the inputs.
10900   SDValue Chain = Op.getOperand(0);
10901   SDValue Size  = Op.getOperand(1);
10902
10903   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
10904                               DAG.getConstant(2, DL, MVT::i32));
10905
10906   SDValue Flag;
10907   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
10908   Flag = Chain.getValue(1);
10909
10910   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10911   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
10912
10913   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
10914   Chain = NewSP.getValue(1);
10915
10916   SDValue Ops[2] = { NewSP, Chain };
10917   return DAG.getMergeValues(Ops, DL);
10918 }
10919
10920 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
10921   assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
10922          "Unexpected type for custom-lowering FP_EXTEND");
10923
10924   RTLIB::Libcall LC;
10925   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
10926
10927   SDValue SrcVal = Op.getOperand(0);
10928   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
10929                      /*isSigned*/ false, SDLoc(Op)).first;
10930 }
10931
10932 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
10933   assert(Op.getOperand(0).getValueType() == MVT::f64 &&
10934          Subtarget->isFPOnlySP() &&
10935          "Unexpected type for custom-lowering FP_ROUND");
10936
10937   RTLIB::Libcall LC;
10938   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
10939
10940   SDValue SrcVal = Op.getOperand(0);
10941   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
10942                      /*isSigned*/ false, SDLoc(Op)).first;
10943 }
10944
10945 bool
10946 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10947   // The ARM target isn't yet aware of offsets.
10948   return false;
10949 }
10950
10951 bool ARM::isBitFieldInvertedMask(unsigned v) {
10952   if (v == 0xffffffff)
10953     return false;
10954
10955   // there can be 1's on either or both "outsides", all the "inside"
10956   // bits must be 0's
10957   return isShiftedMask_32(~v);
10958 }
10959
10960 /// isFPImmLegal - Returns true if the target can instruction select the
10961 /// specified FP immediate natively. If false, the legalizer will
10962 /// materialize the FP immediate as a load from a constant pool.
10963 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10964   if (!Subtarget->hasVFP3())
10965     return false;
10966   if (VT == MVT::f32)
10967     return ARM_AM::getFP32Imm(Imm) != -1;
10968   if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
10969     return ARM_AM::getFP64Imm(Imm) != -1;
10970   return false;
10971 }
10972
10973 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10974 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
10975 /// specified in the intrinsic calls.
10976 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10977                                            const CallInst &I,
10978                                            unsigned Intrinsic) const {
10979   switch (Intrinsic) {
10980   case Intrinsic::arm_neon_vld1:
10981   case Intrinsic::arm_neon_vld2:
10982   case Intrinsic::arm_neon_vld3:
10983   case Intrinsic::arm_neon_vld4:
10984   case Intrinsic::arm_neon_vld2lane:
10985   case Intrinsic::arm_neon_vld3lane:
10986   case Intrinsic::arm_neon_vld4lane: {
10987     Info.opc = ISD::INTRINSIC_W_CHAIN;
10988     // Conservatively set memVT to the entire set of vectors loaded.
10989     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10990     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10991     Info.ptrVal = I.getArgOperand(0);
10992     Info.offset = 0;
10993     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10994     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10995     Info.vol = false; // volatile loads with NEON intrinsics not supported
10996     Info.readMem = true;
10997     Info.writeMem = false;
10998     return true;
10999   }
11000   case Intrinsic::arm_neon_vst1:
11001   case Intrinsic::arm_neon_vst2:
11002   case Intrinsic::arm_neon_vst3:
11003   case Intrinsic::arm_neon_vst4:
11004   case Intrinsic::arm_neon_vst2lane:
11005   case Intrinsic::arm_neon_vst3lane:
11006   case Intrinsic::arm_neon_vst4lane: {
11007     Info.opc = ISD::INTRINSIC_VOID;
11008     // Conservatively set memVT to the entire set of vectors stored.
11009     unsigned NumElts = 0;
11010     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11011       Type *ArgTy = I.getArgOperand(ArgI)->getType();
11012       if (!ArgTy->isVectorTy())
11013         break;
11014       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
11015     }
11016     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11017     Info.ptrVal = I.getArgOperand(0);
11018     Info.offset = 0;
11019     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11020     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11021     Info.vol = false; // volatile stores with NEON intrinsics not supported
11022     Info.readMem = false;
11023     Info.writeMem = true;
11024     return true;
11025   }
11026   case Intrinsic::arm_ldaex:
11027   case Intrinsic::arm_ldrex: {
11028     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11029     Info.opc = ISD::INTRINSIC_W_CHAIN;
11030     Info.memVT = MVT::getVT(PtrTy->getElementType());
11031     Info.ptrVal = I.getArgOperand(0);
11032     Info.offset = 0;
11033     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11034     Info.vol = true;
11035     Info.readMem = true;
11036     Info.writeMem = false;
11037     return true;
11038   }
11039   case Intrinsic::arm_stlex:
11040   case Intrinsic::arm_strex: {
11041     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11042     Info.opc = ISD::INTRINSIC_W_CHAIN;
11043     Info.memVT = MVT::getVT(PtrTy->getElementType());
11044     Info.ptrVal = I.getArgOperand(1);
11045     Info.offset = 0;
11046     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11047     Info.vol = true;
11048     Info.readMem = false;
11049     Info.writeMem = true;
11050     return true;
11051   }
11052   case Intrinsic::arm_stlexd:
11053   case Intrinsic::arm_strexd: {
11054     Info.opc = ISD::INTRINSIC_W_CHAIN;
11055     Info.memVT = MVT::i64;
11056     Info.ptrVal = I.getArgOperand(2);
11057     Info.offset = 0;
11058     Info.align = 8;
11059     Info.vol = true;
11060     Info.readMem = false;
11061     Info.writeMem = true;
11062     return true;
11063   }
11064   case Intrinsic::arm_ldaexd:
11065   case Intrinsic::arm_ldrexd: {
11066     Info.opc = ISD::INTRINSIC_W_CHAIN;
11067     Info.memVT = MVT::i64;
11068     Info.ptrVal = I.getArgOperand(0);
11069     Info.offset = 0;
11070     Info.align = 8;
11071     Info.vol = true;
11072     Info.readMem = true;
11073     Info.writeMem = false;
11074     return true;
11075   }
11076   default:
11077     break;
11078   }
11079
11080   return false;
11081 }
11082
11083 /// \brief Returns true if it is beneficial to convert a load of a constant
11084 /// to just the constant itself.
11085 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11086                                                           Type *Ty) const {
11087   assert(Ty->isIntegerTy());
11088
11089   unsigned Bits = Ty->getPrimitiveSizeInBits();
11090   if (Bits == 0 || Bits > 32)
11091     return false;
11092   return true;
11093 }
11094
11095 bool ARMTargetLowering::hasLoadLinkedStoreConditional() const { return true; }
11096
11097 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
11098                                         ARM_MB::MemBOpt Domain) const {
11099   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11100
11101   // First, if the target has no DMB, see what fallback we can use.
11102   if (!Subtarget->hasDataBarrier()) {
11103     // Some ARMv6 cpus can support data barriers with an mcr instruction.
11104     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
11105     // here.
11106     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
11107       Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
11108       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
11109                         Builder.getInt32(0), Builder.getInt32(7),
11110                         Builder.getInt32(10), Builder.getInt32(5)};
11111       return Builder.CreateCall(MCR, args);
11112     } else {
11113       // Instead of using barriers, atomic accesses on these subtargets use
11114       // libcalls.
11115       llvm_unreachable("makeDMB on a target so old that it has no barriers");
11116     }
11117   } else {
11118     Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
11119     // Only a full system barrier exists in the M-class architectures.
11120     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
11121     Constant *CDomain = Builder.getInt32(Domain);
11122     return Builder.CreateCall(DMB, CDomain);
11123   }
11124 }
11125
11126 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11127 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11128                                          AtomicOrdering Ord, bool IsStore,
11129                                          bool IsLoad) const {
11130   if (!getInsertFencesForAtomic())
11131     return nullptr;
11132
11133   switch (Ord) {
11134   case NotAtomic:
11135   case Unordered:
11136     llvm_unreachable("Invalid fence: unordered/non-atomic");
11137   case Monotonic:
11138   case Acquire:
11139     return nullptr; // Nothing to do
11140   case SequentiallyConsistent:
11141     if (!IsStore)
11142       return nullptr; // Nothing to do
11143     /*FALLTHROUGH*/
11144   case Release:
11145   case AcquireRelease:
11146     if (Subtarget->isSwift())
11147       return makeDMB(Builder, ARM_MB::ISHST);
11148     // FIXME: add a comment with a link to documentation justifying this.
11149     else
11150       return makeDMB(Builder, ARM_MB::ISH);
11151   }
11152   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
11153 }
11154
11155 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11156                                           AtomicOrdering Ord, bool IsStore,
11157                                           bool IsLoad) const {
11158   if (!getInsertFencesForAtomic())
11159     return nullptr;
11160
11161   switch (Ord) {
11162   case NotAtomic:
11163   case Unordered:
11164     llvm_unreachable("Invalid fence: unordered/not-atomic");
11165   case Monotonic:
11166   case Release:
11167     return nullptr; // Nothing to do
11168   case Acquire:
11169   case AcquireRelease:
11170   case SequentiallyConsistent:
11171     return makeDMB(Builder, ARM_MB::ISH);
11172   }
11173   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
11174 }
11175
11176 // Loads and stores less than 64-bits are already atomic; ones above that
11177 // are doomed anyway, so defer to the default libcall and blame the OS when
11178 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11179 // anything for those.
11180 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11181   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11182   return (Size == 64) && !Subtarget->isMClass();
11183 }
11184
11185 // Loads and stores less than 64-bits are already atomic; ones above that
11186 // are doomed anyway, so defer to the default libcall and blame the OS when
11187 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11188 // anything for those.
11189 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
11190 // guarantee, see DDI0406C ARM architecture reference manual,
11191 // sections A8.8.72-74 LDRD)
11192 bool ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11193   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11194   return (Size == 64) && !Subtarget->isMClass();
11195 }
11196
11197 // For the real atomic operations, we have ldrex/strex up to 32 bits,
11198 // and up to 64 bits on the non-M profiles
11199 TargetLoweringBase::AtomicRMWExpansionKind
11200 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11201   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11202   return (Size <= (Subtarget->isMClass() ? 32U : 64U))
11203              ? AtomicRMWExpansionKind::LLSC
11204              : AtomicRMWExpansionKind::None;
11205 }
11206
11207 // This has so far only been implemented for MachO.
11208 bool ARMTargetLowering::useLoadStackGuardNode() const {
11209   return Subtarget->isTargetMachO();
11210 }
11211
11212 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
11213                                                   unsigned &Cost) const {
11214   // If we do not have NEON, vector types are not natively supported.
11215   if (!Subtarget->hasNEON())
11216     return false;
11217
11218   // Floating point values and vector values map to the same register file.
11219   // Therefore, althought we could do a store extract of a vector type, this is
11220   // better to leave at float as we have more freedom in the addressing mode for
11221   // those.
11222   if (VectorTy->isFPOrFPVectorTy())
11223     return false;
11224
11225   // If the index is unknown at compile time, this is very expensive to lower
11226   // and it is not possible to combine the store with the extract.
11227   if (!isa<ConstantInt>(Idx))
11228     return false;
11229
11230   assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
11231   unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
11232   // We can do a store + vector extract on any vector that fits perfectly in a D
11233   // or Q register.
11234   if (BitWidth == 64 || BitWidth == 128) {
11235     Cost = 0;
11236     return true;
11237   }
11238   return false;
11239 }
11240
11241 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11242                                          AtomicOrdering Ord) const {
11243   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11244   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11245   bool IsAcquire = isAtLeastAcquire(Ord);
11246
11247   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
11248   // intrinsic must return {i32, i32} and we have to recombine them into a
11249   // single i64 here.
11250   if (ValTy->getPrimitiveSizeInBits() == 64) {
11251     Intrinsic::ID Int =
11252         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
11253     Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
11254
11255     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11256     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
11257
11258     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11259     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11260     if (!Subtarget->isLittle())
11261       std::swap (Lo, Hi);
11262     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11263     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11264     return Builder.CreateOr(
11265         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
11266   }
11267
11268   Type *Tys[] = { Addr->getType() };
11269   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
11270   Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
11271
11272   return Builder.CreateTruncOrBitCast(
11273       Builder.CreateCall(Ldrex, Addr),
11274       cast<PointerType>(Addr->getType())->getElementType());
11275 }
11276
11277 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
11278                                                Value *Addr,
11279                                                AtomicOrdering Ord) const {
11280   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11281   bool IsRelease = isAtLeastRelease(Ord);
11282
11283   // Since the intrinsics must have legal type, the i64 intrinsics take two
11284   // parameters: "i32, i32". We must marshal Val into the appropriate form
11285   // before the call.
11286   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
11287     Intrinsic::ID Int =
11288         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
11289     Function *Strex = Intrinsic::getDeclaration(M, Int);
11290     Type *Int32Ty = Type::getInt32Ty(M->getContext());
11291
11292     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
11293     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
11294     if (!Subtarget->isLittle())
11295       std::swap (Lo, Hi);
11296     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11297     return Builder.CreateCall(Strex, {Lo, Hi, Addr});
11298   }
11299
11300   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
11301   Type *Tys[] = { Addr->getType() };
11302   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
11303
11304   return Builder.CreateCall(
11305       Strex, {Builder.CreateZExtOrBitCast(
11306                   Val, Strex->getFunctionType()->getParamType(0)),
11307               Addr});
11308 }
11309
11310 enum HABaseType {
11311   HA_UNKNOWN = 0,
11312   HA_FLOAT,
11313   HA_DOUBLE,
11314   HA_VECT64,
11315   HA_VECT128
11316 };
11317
11318 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
11319                                    uint64_t &Members) {
11320   if (const StructType *ST = dyn_cast<StructType>(Ty)) {
11321     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
11322       uint64_t SubMembers = 0;
11323       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
11324         return false;
11325       Members += SubMembers;
11326     }
11327   } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
11328     uint64_t SubMembers = 0;
11329     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
11330       return false;
11331     Members += SubMembers * AT->getNumElements();
11332   } else if (Ty->isFloatTy()) {
11333     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
11334       return false;
11335     Members = 1;
11336     Base = HA_FLOAT;
11337   } else if (Ty->isDoubleTy()) {
11338     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
11339       return false;
11340     Members = 1;
11341     Base = HA_DOUBLE;
11342   } else if (const VectorType *VT = dyn_cast<VectorType>(Ty)) {
11343     Members = 1;
11344     switch (Base) {
11345     case HA_FLOAT:
11346     case HA_DOUBLE:
11347       return false;
11348     case HA_VECT64:
11349       return VT->getBitWidth() == 64;
11350     case HA_VECT128:
11351       return VT->getBitWidth() == 128;
11352     case HA_UNKNOWN:
11353       switch (VT->getBitWidth()) {
11354       case 64:
11355         Base = HA_VECT64;
11356         return true;
11357       case 128:
11358         Base = HA_VECT128;
11359         return true;
11360       default:
11361         return false;
11362       }
11363     }
11364   }
11365
11366   return (Members > 0 && Members <= 4);
11367 }
11368
11369 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
11370 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
11371 /// passing according to AAPCS rules.
11372 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
11373     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11374   if (getEffectiveCallingConv(CallConv, isVarArg) !=
11375       CallingConv::ARM_AAPCS_VFP)
11376     return false;
11377
11378   HABaseType Base = HA_UNKNOWN;
11379   uint64_t Members = 0;
11380   bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
11381   DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
11382
11383   bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
11384   return IsHA || IsIntArray;
11385 }