Make TargetLowering::getPointerTy() taking DataLayout as an argument
[oota-llvm.git] / lib / Target / ARM / ARMISelLowering.cpp
1 //===-- ARMISelLowering.cpp - ARM DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that ARM uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "ARMISelLowering.h"
16 #include "ARMCallingConv.h"
17 #include "ARMConstantPoolValue.h"
18 #include "ARMMachineFunctionInfo.h"
19 #include "ARMPerfectShuffle.h"
20 #include "ARMSubtarget.h"
21 #include "ARMTargetMachine.h"
22 #include "ARMTargetObjectFile.h"
23 #include "MCTargetDesc/ARMAddressingModes.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/ADT/StringSwitch.h"
27 #include "llvm/CodeGen/CallingConvLower.h"
28 #include "llvm/CodeGen/IntrinsicLowering.h"
29 #include "llvm/CodeGen/MachineBasicBlock.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineJumpTableInfo.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/SelectionDAG.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/GlobalValue.h"
41 #include "llvm/IR/IRBuilder.h"
42 #include "llvm/IR/Instruction.h"
43 #include "llvm/IR/Instructions.h"
44 #include "llvm/IR/IntrinsicInst.h"
45 #include "llvm/IR/Intrinsics.h"
46 #include "llvm/IR/Type.h"
47 #include "llvm/MC/MCSectionMachO.h"
48 #include "llvm/Support/CommandLine.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Support/raw_ostream.h"
53 #include "llvm/Target/TargetOptions.h"
54 #include <utility>
55 using namespace llvm;
56
57 #define DEBUG_TYPE "arm-isel"
58
59 STATISTIC(NumTailCalls, "Number of tail calls");
60 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
61 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
62
63 static cl::opt<bool>
64 ARMInterworking("arm-interworking", cl::Hidden,
65   cl::desc("Enable / disable ARM interworking (for debugging only)"),
66   cl::init(true));
67
68 namespace {
69   class ARMCCState : public CCState {
70   public:
71     ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
72                SmallVectorImpl<CCValAssign> &locs, LLVMContext &C,
73                ParmContext PC)
74         : CCState(CC, isVarArg, MF, locs, C) {
75       assert(((PC == Call) || (PC == Prologue)) &&
76              "ARMCCState users must specify whether their context is call"
77              "or prologue generation.");
78       CallOrPrologue = PC;
79     }
80   };
81 }
82
83 // The APCS parameter registers.
84 static const MCPhysReg GPRArgRegs[] = {
85   ARM::R0, ARM::R1, ARM::R2, ARM::R3
86 };
87
88 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
89                                        MVT PromotedBitwiseVT) {
90   if (VT != PromotedLdStVT) {
91     setOperationAction(ISD::LOAD, VT, Promote);
92     AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
93
94     setOperationAction(ISD::STORE, VT, Promote);
95     AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
96   }
97
98   MVT ElemTy = VT.getVectorElementType();
99   if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
100     setOperationAction(ISD::SETCC, VT, Custom);
101   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
102   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
103   if (ElemTy == MVT::i32) {
104     setOperationAction(ISD::SINT_TO_FP, VT, Custom);
105     setOperationAction(ISD::UINT_TO_FP, VT, Custom);
106     setOperationAction(ISD::FP_TO_SINT, VT, Custom);
107     setOperationAction(ISD::FP_TO_UINT, VT, Custom);
108   } else {
109     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
110     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
111     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
112     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
113   }
114   setOperationAction(ISD::BUILD_VECTOR,      VT, Custom);
115   setOperationAction(ISD::VECTOR_SHUFFLE,    VT, Custom);
116   setOperationAction(ISD::CONCAT_VECTORS,    VT, Legal);
117   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
118   setOperationAction(ISD::SELECT,            VT, Expand);
119   setOperationAction(ISD::SELECT_CC,         VT, Expand);
120   setOperationAction(ISD::VSELECT,           VT, Expand);
121   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
122   if (VT.isInteger()) {
123     setOperationAction(ISD::SHL, VT, Custom);
124     setOperationAction(ISD::SRA, VT, Custom);
125     setOperationAction(ISD::SRL, VT, Custom);
126   }
127
128   // Promote all bit-wise operations.
129   if (VT.isInteger() && VT != PromotedBitwiseVT) {
130     setOperationAction(ISD::AND, VT, Promote);
131     AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
132     setOperationAction(ISD::OR,  VT, Promote);
133     AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
134     setOperationAction(ISD::XOR, VT, Promote);
135     AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
136   }
137
138   // Neon does not support vector divide/remainder operations.
139   setOperationAction(ISD::SDIV, VT, Expand);
140   setOperationAction(ISD::UDIV, VT, Expand);
141   setOperationAction(ISD::FDIV, VT, Expand);
142   setOperationAction(ISD::SREM, VT, Expand);
143   setOperationAction(ISD::UREM, VT, Expand);
144   setOperationAction(ISD::FREM, VT, Expand);
145 }
146
147 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
148   addRegisterClass(VT, &ARM::DPRRegClass);
149   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
150 }
151
152 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
153   addRegisterClass(VT, &ARM::DPairRegClass);
154   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
155 }
156
157 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM,
158                                      const ARMSubtarget &STI)
159     : TargetLowering(TM), Subtarget(&STI) {
160   RegInfo = Subtarget->getRegisterInfo();
161   Itins = Subtarget->getInstrItineraryData();
162
163   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
164
165   if (Subtarget->isTargetMachO()) {
166     // Uses VFP for Thumb libfuncs if available.
167     if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
168         Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) {
169       // Single-precision floating-point arithmetic.
170       setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
171       setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
172       setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
173       setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
174
175       // Double-precision floating-point arithmetic.
176       setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
177       setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
178       setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
179       setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
180
181       // Single-precision comparisons.
182       setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
183       setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
184       setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
185       setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
186       setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
187       setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
188       setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
189       setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
190
191       setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
192       setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
193       setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
194       setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
195       setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
196       setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
197       setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
198       setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
199
200       // Double-precision comparisons.
201       setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
202       setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
203       setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
204       setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
205       setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
206       setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
207       setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
208       setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
209
210       setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
211       setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
212       setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
213       setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
214       setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
215       setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
216       setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
217       setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
218
219       // Floating-point to integer conversions.
220       // i64 conversions are done via library routines even when generating VFP
221       // instructions, so use the same ones.
222       setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
223       setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
224       setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
225       setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
226
227       // Conversions between floating types.
228       setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
229       setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
230
231       // Integer to floating-point conversions.
232       // i64 conversions are done via library routines even when generating VFP
233       // instructions, so use the same ones.
234       // FIXME: There appears to be some naming inconsistency in ARM libgcc:
235       // e.g., __floatunsidf vs. __floatunssidfvfp.
236       setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
237       setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
238       setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
239       setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
240     }
241   }
242
243   // These libcalls are not available in 32-bit.
244   setLibcallName(RTLIB::SHL_I128, nullptr);
245   setLibcallName(RTLIB::SRL_I128, nullptr);
246   setLibcallName(RTLIB::SRA_I128, nullptr);
247
248   if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO() &&
249       !Subtarget->isTargetWindows()) {
250     static const struct {
251       const RTLIB::Libcall Op;
252       const char * const Name;
253       const CallingConv::ID CC;
254       const ISD::CondCode Cond;
255     } LibraryCalls[] = {
256       // Double-precision floating-point arithmetic helper functions
257       // RTABI chapter 4.1.2, Table 2
258       { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
259       { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
260       { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
261       { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
262
263       // Double-precision floating-point comparison helper functions
264       // RTABI chapter 4.1.2, Table 3
265       { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
266       { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
267       { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
268       { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
269       { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
270       { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
271       { RTLIB::UO_F64,  "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
272       { RTLIB::O_F64,   "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
273
274       // Single-precision floating-point arithmetic helper functions
275       // RTABI chapter 4.1.2, Table 4
276       { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
277       { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
278       { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
279       { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
280
281       // Single-precision floating-point comparison helper functions
282       // RTABI chapter 4.1.2, Table 5
283       { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
284       { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
285       { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
286       { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
287       { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
288       { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
289       { RTLIB::UO_F32,  "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
290       { RTLIB::O_F32,   "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
291
292       // Floating-point to integer conversions.
293       // RTABI chapter 4.1.2, Table 6
294       { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
295       { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
296       { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
297       { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
298       { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
299       { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
300       { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
301       { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
302
303       // Conversions between floating types.
304       // RTABI chapter 4.1.2, Table 7
305       { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
306       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
307       { RTLIB::FPEXT_F32_F64,   "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
308
309       // Integer to floating-point conversions.
310       // RTABI chapter 4.1.2, Table 8
311       { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
312       { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
313       { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
314       { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
315       { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
316       { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
317       { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
318       { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
319
320       // Long long helper functions
321       // RTABI chapter 4.2, Table 9
322       { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
323       { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
324       { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
325       { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
326
327       // Integer division functions
328       // RTABI chapter 4.3.1
329       { RTLIB::SDIV_I8,  "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
330       { RTLIB::SDIV_I16, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
331       { RTLIB::SDIV_I32, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
332       { RTLIB::SDIV_I64, "__aeabi_ldivmod",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
333       { RTLIB::UDIV_I8,  "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
334       { RTLIB::UDIV_I16, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
335       { RTLIB::UDIV_I32, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
336       { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
337
338       // Memory operations
339       // RTABI chapter 4.3.4
340       { RTLIB::MEMCPY,  "__aeabi_memcpy",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
341       { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
342       { RTLIB::MEMSET,  "__aeabi_memset",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
343     };
344
345     for (const auto &LC : LibraryCalls) {
346       setLibcallName(LC.Op, LC.Name);
347       setLibcallCallingConv(LC.Op, LC.CC);
348       if (LC.Cond != ISD::SETCC_INVALID)
349         setCmpLibcallCC(LC.Op, LC.Cond);
350     }
351   }
352
353   if (Subtarget->isTargetWindows()) {
354     static const struct {
355       const RTLIB::Libcall Op;
356       const char * const Name;
357       const CallingConv::ID CC;
358     } LibraryCalls[] = {
359       { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
360       { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
361       { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
362       { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
363       { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
364       { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
365       { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
366       { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
367     };
368
369     for (const auto &LC : LibraryCalls) {
370       setLibcallName(LC.Op, LC.Name);
371       setLibcallCallingConv(LC.Op, LC.CC);
372     }
373   }
374
375   // Use divmod compiler-rt calls for iOS 5.0 and later.
376   if (Subtarget->getTargetTriple().isiOS() &&
377       !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
378     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
379     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
380   }
381
382   // The half <-> float conversion functions are always soft-float, but are
383   // needed for some targets which use a hard-float calling convention by
384   // default.
385   if (Subtarget->isAAPCS_ABI()) {
386     setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
387     setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
388     setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
389   } else {
390     setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
391     setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
392     setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
393   }
394
395   if (Subtarget->isThumb1Only())
396     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
397   else
398     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
399   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
400       !Subtarget->isThumb1Only()) {
401     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
402     addRegisterClass(MVT::f64, &ARM::DPRRegClass);
403   }
404
405   for (MVT VT : MVT::vector_valuetypes()) {
406     for (MVT InnerVT : MVT::vector_valuetypes()) {
407       setTruncStoreAction(VT, InnerVT, Expand);
408       setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
409       setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
410       setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
411     }
412
413     setOperationAction(ISD::MULHS, VT, Expand);
414     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
415     setOperationAction(ISD::MULHU, VT, Expand);
416     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
417
418     setOperationAction(ISD::BSWAP, VT, Expand);
419   }
420
421   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
422   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
423
424   setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
425   setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
426
427   if (Subtarget->hasNEON()) {
428     addDRTypeForNEON(MVT::v2f32);
429     addDRTypeForNEON(MVT::v8i8);
430     addDRTypeForNEON(MVT::v4i16);
431     addDRTypeForNEON(MVT::v2i32);
432     addDRTypeForNEON(MVT::v1i64);
433
434     addQRTypeForNEON(MVT::v4f32);
435     addQRTypeForNEON(MVT::v2f64);
436     addQRTypeForNEON(MVT::v16i8);
437     addQRTypeForNEON(MVT::v8i16);
438     addQRTypeForNEON(MVT::v4i32);
439     addQRTypeForNEON(MVT::v2i64);
440
441     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
442     // neither Neon nor VFP support any arithmetic operations on it.
443     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
444     // supported for v4f32.
445     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
446     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
447     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
448     // FIXME: Code duplication: FDIV and FREM are expanded always, see
449     // ARMTargetLowering::addTypeForNEON method for details.
450     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
451     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
452     // FIXME: Create unittest.
453     // In another words, find a way when "copysign" appears in DAG with vector
454     // operands.
455     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
456     // FIXME: Code duplication: SETCC has custom operation action, see
457     // ARMTargetLowering::addTypeForNEON method for details.
458     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
459     // FIXME: Create unittest for FNEG and for FABS.
460     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
461     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
462     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
463     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
464     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
465     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
466     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
467     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
468     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
469     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
470     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
471     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
472     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
473     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
474     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
475     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
476     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
477     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
478     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
479
480     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
481     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
482     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
483     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
484     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
485     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
486     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
487     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
488     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
489     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
490     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
491     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
492     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
493     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
494     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
495
496     // Mark v2f32 intrinsics.
497     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
498     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
499     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
500     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
501     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
502     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
503     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
504     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
505     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
506     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
507     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
508     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
509     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
510     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
511     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
512
513     // Neon does not support some operations on v1i64 and v2i64 types.
514     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
515     // Custom handling for some quad-vector types to detect VMULL.
516     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
517     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
518     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
519     // Custom handling for some vector types to avoid expensive expansions
520     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
521     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
522     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
523     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
524     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
525     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
526     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
527     // a destination type that is wider than the source, and nor does
528     // it have a FP_TO_[SU]INT instruction with a narrower destination than
529     // source.
530     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
531     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
532     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
533     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
534
535     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
536     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
537
538     // NEON does not have single instruction CTPOP for vectors with element
539     // types wider than 8-bits.  However, custom lowering can leverage the
540     // v8i8/v16i8 vcnt instruction.
541     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
542     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
543     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
544     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
545
546     // NEON only has FMA instructions as of VFP4.
547     if (!Subtarget->hasVFP4()) {
548       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
549       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
550     }
551
552     setTargetDAGCombine(ISD::INTRINSIC_VOID);
553     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
554     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
555     setTargetDAGCombine(ISD::SHL);
556     setTargetDAGCombine(ISD::SRL);
557     setTargetDAGCombine(ISD::SRA);
558     setTargetDAGCombine(ISD::SIGN_EXTEND);
559     setTargetDAGCombine(ISD::ZERO_EXTEND);
560     setTargetDAGCombine(ISD::ANY_EXTEND);
561     setTargetDAGCombine(ISD::SELECT_CC);
562     setTargetDAGCombine(ISD::BUILD_VECTOR);
563     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
564     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
565     setTargetDAGCombine(ISD::STORE);
566     setTargetDAGCombine(ISD::FP_TO_SINT);
567     setTargetDAGCombine(ISD::FP_TO_UINT);
568     setTargetDAGCombine(ISD::FDIV);
569     setTargetDAGCombine(ISD::LOAD);
570
571     // It is legal to extload from v4i8 to v4i16 or v4i32.
572     for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
573                    MVT::v2i32}) {
574       for (MVT VT : MVT::integer_vector_valuetypes()) {
575         setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
576         setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
577         setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
578       }
579     }
580   }
581
582   // ARM and Thumb2 support UMLAL/SMLAL.
583   if (!Subtarget->isThumb1Only())
584     setTargetDAGCombine(ISD::ADDC);
585
586   if (Subtarget->isFPOnlySP()) {
587     // When targetting a floating-point unit with only single-precision
588     // operations, f64 is legal for the few double-precision instructions which
589     // are present However, no double-precision operations other than moves,
590     // loads and stores are provided by the hardware.
591     setOperationAction(ISD::FADD,       MVT::f64, Expand);
592     setOperationAction(ISD::FSUB,       MVT::f64, Expand);
593     setOperationAction(ISD::FMUL,       MVT::f64, Expand);
594     setOperationAction(ISD::FMA,        MVT::f64, Expand);
595     setOperationAction(ISD::FDIV,       MVT::f64, Expand);
596     setOperationAction(ISD::FREM,       MVT::f64, Expand);
597     setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
598     setOperationAction(ISD::FGETSIGN,   MVT::f64, Expand);
599     setOperationAction(ISD::FNEG,       MVT::f64, Expand);
600     setOperationAction(ISD::FABS,       MVT::f64, Expand);
601     setOperationAction(ISD::FSQRT,      MVT::f64, Expand);
602     setOperationAction(ISD::FSIN,       MVT::f64, Expand);
603     setOperationAction(ISD::FCOS,       MVT::f64, Expand);
604     setOperationAction(ISD::FPOWI,      MVT::f64, Expand);
605     setOperationAction(ISD::FPOW,       MVT::f64, Expand);
606     setOperationAction(ISD::FLOG,       MVT::f64, Expand);
607     setOperationAction(ISD::FLOG2,      MVT::f64, Expand);
608     setOperationAction(ISD::FLOG10,     MVT::f64, Expand);
609     setOperationAction(ISD::FEXP,       MVT::f64, Expand);
610     setOperationAction(ISD::FEXP2,      MVT::f64, Expand);
611     setOperationAction(ISD::FCEIL,      MVT::f64, Expand);
612     setOperationAction(ISD::FTRUNC,     MVT::f64, Expand);
613     setOperationAction(ISD::FRINT,      MVT::f64, Expand);
614     setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
615     setOperationAction(ISD::FFLOOR,     MVT::f64, Expand);
616     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
617     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
618     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
619     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
620     setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
621     setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
622     setOperationAction(ISD::FP_ROUND,   MVT::f32, Custom);
623     setOperationAction(ISD::FP_EXTEND,  MVT::f64, Custom);
624   }
625
626   computeRegisterProperties(Subtarget->getRegisterInfo());
627
628   // ARM does not have floating-point extending loads.
629   for (MVT VT : MVT::fp_valuetypes()) {
630     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
631     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
632   }
633
634   // ... or truncating stores
635   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
636   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
637   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
638
639   // ARM does not have i1 sign extending load.
640   for (MVT VT : MVT::integer_valuetypes())
641     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
642
643   // ARM supports all 4 flavors of integer indexed load / store.
644   if (!Subtarget->isThumb1Only()) {
645     for (unsigned im = (unsigned)ISD::PRE_INC;
646          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
647       setIndexedLoadAction(im,  MVT::i1,  Legal);
648       setIndexedLoadAction(im,  MVT::i8,  Legal);
649       setIndexedLoadAction(im,  MVT::i16, Legal);
650       setIndexedLoadAction(im,  MVT::i32, Legal);
651       setIndexedStoreAction(im, MVT::i1,  Legal);
652       setIndexedStoreAction(im, MVT::i8,  Legal);
653       setIndexedStoreAction(im, MVT::i16, Legal);
654       setIndexedStoreAction(im, MVT::i32, Legal);
655     }
656   }
657
658   setOperationAction(ISD::SADDO, MVT::i32, Custom);
659   setOperationAction(ISD::UADDO, MVT::i32, Custom);
660   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
661   setOperationAction(ISD::USUBO, MVT::i32, Custom);
662
663   // i64 operation support.
664   setOperationAction(ISD::MUL,     MVT::i64, Expand);
665   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
666   if (Subtarget->isThumb1Only()) {
667     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
668     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
669   }
670   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
671       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
672     setOperationAction(ISD::MULHS, MVT::i32, Expand);
673
674   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
675   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
676   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
677   setOperationAction(ISD::SRL,       MVT::i64, Custom);
678   setOperationAction(ISD::SRA,       MVT::i64, Custom);
679
680   if (!Subtarget->isThumb1Only()) {
681     // FIXME: We should do this for Thumb1 as well.
682     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
683     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
684     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
685     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
686   }
687
688   // ARM does not have ROTL.
689   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
690   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
691   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
692   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
693     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
694
695   // These just redirect to CTTZ and CTLZ on ARM.
696   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
697   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
698
699   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
700
701   // Only ARMv6 has BSWAP.
702   if (!Subtarget->hasV6Ops())
703     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
704
705   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
706       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
707     // These are expanded into libcalls if the cpu doesn't have HW divider.
708     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
709     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
710   }
711
712   // FIXME: Also set divmod for SREM on EABI
713   setOperationAction(ISD::SREM,  MVT::i32, Expand);
714   setOperationAction(ISD::UREM,  MVT::i32, Expand);
715   // Register based DivRem for AEABI (RTABI 4.2)
716   if (Subtarget->isTargetAEABI()) {
717     setLibcallName(RTLIB::SDIVREM_I8,  "__aeabi_idivmod");
718     setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
719     setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
720     setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
721     setLibcallName(RTLIB::UDIVREM_I8,  "__aeabi_uidivmod");
722     setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
723     setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
724     setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
725
726     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
727     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
728     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
729     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
730     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
731     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
732     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
733     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
734
735     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
736     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
737   } else {
738     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
739     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
740   }
741
742   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
743   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
744   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
745   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
746   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
747
748   setOperationAction(ISD::TRAP, MVT::Other, Legal);
749
750   // Use the default implementation.
751   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
752   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
753   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
754   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
755   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
756   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
757
758   if (!Subtarget->isTargetMachO()) {
759     // Non-MachO platforms may return values in these registers via the
760     // personality function.
761     setExceptionPointerRegister(ARM::R0);
762     setExceptionSelectorRegister(ARM::R1);
763   }
764
765   if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
766     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
767   else
768     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
769
770   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
771   // the default expansion. If we are targeting a single threaded system,
772   // then set them all for expand so we can lower them later into their
773   // non-atomic form.
774   if (TM.Options.ThreadModel == ThreadModel::Single)
775     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
776   else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
777     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
778     // to ldrex/strex loops already.
779     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
780
781     // On v8, we have particularly efficient implementations of atomic fences
782     // if they can be combined with nearby atomic loads and stores.
783     if (!Subtarget->hasV8Ops()) {
784       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
785       setInsertFencesForAtomic(true);
786     }
787   } else {
788     // If there's anything we can use as a barrier, go through custom lowering
789     // for ATOMIC_FENCE.
790     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
791                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
792
793     // Set them all for expansion, which will force libcalls.
794     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
795     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
796     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
797     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
798     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
799     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
800     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
801     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
802     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
803     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
804     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
805     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
806     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
807     // Unordered/Monotonic case.
808     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
809     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
810   }
811
812   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
813
814   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
815   if (!Subtarget->hasV6Ops()) {
816     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
817     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
818   }
819   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
820
821   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
822       !Subtarget->isThumb1Only()) {
823     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
824     // iff target supports vfp2.
825     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
826     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
827   }
828
829   // We want to custom lower some of our intrinsics.
830   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
831   if (Subtarget->isTargetDarwin()) {
832     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
833     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
834     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
835   }
836
837   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
838   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
839   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
840   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
841   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
842   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
843   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
844   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
845   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
846
847   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
848   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
849   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
850   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
851   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
852
853   // We don't support sin/cos/fmod/copysign/pow
854   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
855   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
856   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
857   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
858   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
859   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
860   setOperationAction(ISD::FREM,      MVT::f64, Expand);
861   setOperationAction(ISD::FREM,      MVT::f32, Expand);
862   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
863       !Subtarget->isThumb1Only()) {
864     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
865     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
866   }
867   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
868   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
869
870   if (!Subtarget->hasVFP4()) {
871     setOperationAction(ISD::FMA, MVT::f64, Expand);
872     setOperationAction(ISD::FMA, MVT::f32, Expand);
873   }
874
875   // Various VFP goodness
876   if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
877     // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
878     if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
879       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
880       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
881     }
882
883     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
884     if (!Subtarget->hasFP16()) {
885       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
886       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
887     }
888   }
889
890   // Combine sin / cos into one node or libcall if possible.
891   if (Subtarget->hasSinCos()) {
892     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
893     setLibcallName(RTLIB::SINCOS_F64, "sincos");
894     if (Subtarget->getTargetTriple().isiOS()) {
895       // For iOS, we don't want to the normal expansion of a libcall to
896       // sincos. We want to issue a libcall to __sincos_stret.
897       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
898       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
899     }
900   }
901
902   // FP-ARMv8 implements a lot of rounding-like FP operations.
903   if (Subtarget->hasFPARMv8()) {
904     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
905     setOperationAction(ISD::FCEIL, MVT::f32, Legal);
906     setOperationAction(ISD::FROUND, MVT::f32, Legal);
907     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
908     setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
909     setOperationAction(ISD::FRINT, MVT::f32, Legal);
910     if (!Subtarget->isFPOnlySP()) {
911       setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
912       setOperationAction(ISD::FCEIL, MVT::f64, Legal);
913       setOperationAction(ISD::FROUND, MVT::f64, Legal);
914       setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
915       setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
916       setOperationAction(ISD::FRINT, MVT::f64, Legal);
917     }
918   }
919   // We have target-specific dag combine patterns for the following nodes:
920   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
921   setTargetDAGCombine(ISD::ADD);
922   setTargetDAGCombine(ISD::SUB);
923   setTargetDAGCombine(ISD::MUL);
924   setTargetDAGCombine(ISD::AND);
925   setTargetDAGCombine(ISD::OR);
926   setTargetDAGCombine(ISD::XOR);
927
928   if (Subtarget->hasV6Ops())
929     setTargetDAGCombine(ISD::SRL);
930
931   setStackPointerRegisterToSaveRestore(ARM::SP);
932
933   if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
934       !Subtarget->hasVFP2())
935     setSchedulingPreference(Sched::RegPressure);
936   else
937     setSchedulingPreference(Sched::Hybrid);
938
939   //// temporary - rewrite interface to use type
940   MaxStoresPerMemset = 8;
941   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
942   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
943   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
944   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
945   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
946
947   // On ARM arguments smaller than 4 bytes are extended, so all arguments
948   // are at least 4 bytes aligned.
949   setMinStackArgumentAlignment(4);
950
951   // Prefer likely predicted branches to selects on out-of-order cores.
952   PredictableSelectIsExpensive = Subtarget->isLikeA9();
953
954   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
955 }
956
957 bool ARMTargetLowering::useSoftFloat() const {
958   return Subtarget->useSoftFloat();
959 }
960
961 // FIXME: It might make sense to define the representative register class as the
962 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
963 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
964 // SPR's representative would be DPR_VFP2. This should work well if register
965 // pressure tracking were modified such that a register use would increment the
966 // pressure of the register class's representative and all of it's super
967 // classes' representatives transitively. We have not implemented this because
968 // of the difficulty prior to coalescing of modeling operand register classes
969 // due to the common occurrence of cross class copies and subregister insertions
970 // and extractions.
971 std::pair<const TargetRegisterClass *, uint8_t>
972 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
973                                            MVT VT) const {
974   const TargetRegisterClass *RRC = nullptr;
975   uint8_t Cost = 1;
976   switch (VT.SimpleTy) {
977   default:
978     return TargetLowering::findRepresentativeClass(TRI, VT);
979   // Use DPR as representative register class for all floating point
980   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
981   // the cost is 1 for both f32 and f64.
982   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
983   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
984     RRC = &ARM::DPRRegClass;
985     // When NEON is used for SP, only half of the register file is available
986     // because operations that define both SP and DP results will be constrained
987     // to the VFP2 class (D0-D15). We currently model this constraint prior to
988     // coalescing by double-counting the SP regs. See the FIXME above.
989     if (Subtarget->useNEONForSinglePrecisionFP())
990       Cost = 2;
991     break;
992   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
993   case MVT::v4f32: case MVT::v2f64:
994     RRC = &ARM::DPRRegClass;
995     Cost = 2;
996     break;
997   case MVT::v4i64:
998     RRC = &ARM::DPRRegClass;
999     Cost = 4;
1000     break;
1001   case MVT::v8i64:
1002     RRC = &ARM::DPRRegClass;
1003     Cost = 8;
1004     break;
1005   }
1006   return std::make_pair(RRC, Cost);
1007 }
1008
1009 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1010   switch ((ARMISD::NodeType)Opcode) {
1011   case ARMISD::FIRST_NUMBER:  break;
1012   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1013   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1014   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1015   case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1016   case ARMISD::CALL:          return "ARMISD::CALL";
1017   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1018   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1019   case ARMISD::tCALL:         return "ARMISD::tCALL";
1020   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1021   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1022   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1023   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1024   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1025   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1026   case ARMISD::CMP:           return "ARMISD::CMP";
1027   case ARMISD::CMN:           return "ARMISD::CMN";
1028   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1029   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1030   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1031   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1032   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1033
1034   case ARMISD::CMOV:          return "ARMISD::CMOV";
1035
1036   case ARMISD::RBIT:          return "ARMISD::RBIT";
1037
1038   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1039   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1040   case ARMISD::RRX:           return "ARMISD::RRX";
1041
1042   case ARMISD::ADDC:          return "ARMISD::ADDC";
1043   case ARMISD::ADDE:          return "ARMISD::ADDE";
1044   case ARMISD::SUBC:          return "ARMISD::SUBC";
1045   case ARMISD::SUBE:          return "ARMISD::SUBE";
1046
1047   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1048   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1049
1050   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1051   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
1052
1053   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1054
1055   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1056
1057   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1058
1059   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1060
1061   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1062
1063   case ARMISD::WIN__CHKSTK:   return "ARMISD:::WIN__CHKSTK";
1064
1065   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1066   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1067   case ARMISD::VCGE:          return "ARMISD::VCGE";
1068   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1069   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1070   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1071   case ARMISD::VCGT:          return "ARMISD::VCGT";
1072   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1073   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1074   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1075   case ARMISD::VTST:          return "ARMISD::VTST";
1076
1077   case ARMISD::VSHL:          return "ARMISD::VSHL";
1078   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1079   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1080   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1081   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1082   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1083   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1084   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1085   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1086   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1087   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1088   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1089   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1090   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1091   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1092   case ARMISD::VSLI:          return "ARMISD::VSLI";
1093   case ARMISD::VSRI:          return "ARMISD::VSRI";
1094   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1095   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1096   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1097   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1098   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1099   case ARMISD::VDUP:          return "ARMISD::VDUP";
1100   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1101   case ARMISD::VEXT:          return "ARMISD::VEXT";
1102   case ARMISD::VREV64:        return "ARMISD::VREV64";
1103   case ARMISD::VREV32:        return "ARMISD::VREV32";
1104   case ARMISD::VREV16:        return "ARMISD::VREV16";
1105   case ARMISD::VZIP:          return "ARMISD::VZIP";
1106   case ARMISD::VUZP:          return "ARMISD::VUZP";
1107   case ARMISD::VTRN:          return "ARMISD::VTRN";
1108   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1109   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1110   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1111   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1112   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1113   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1114   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1115   case ARMISD::FMAX:          return "ARMISD::FMAX";
1116   case ARMISD::FMIN:          return "ARMISD::FMIN";
1117   case ARMISD::VMAXNM:        return "ARMISD::VMAX";
1118   case ARMISD::VMINNM:        return "ARMISD::VMIN";
1119   case ARMISD::BFI:           return "ARMISD::BFI";
1120   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1121   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1122   case ARMISD::VBSL:          return "ARMISD::VBSL";
1123   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1124   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1125   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1126   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1127   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1128   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1129   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1130   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1131   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1132   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1133   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1134   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1135   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1136   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1137   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1138   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1139   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1140   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1141   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1142   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1143   }
1144   return nullptr;
1145 }
1146
1147 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1148                                           EVT VT) const {
1149   if (!VT.isVector())
1150     return getPointerTy(DL);
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(DAG.getDataLayout()),
1430                        StackPtr, PtrOff);
1431   return DAG.getStore(Chain, dl, Arg, PtrOff,
1432                       MachinePointerInfo::getStack(LocMemOffset),
1433                       false, false, 0);
1434 }
1435
1436 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1437                                          SDValue Chain, SDValue &Arg,
1438                                          RegsToPassVector &RegsToPass,
1439                                          CCValAssign &VA, CCValAssign &NextVA,
1440                                          SDValue &StackPtr,
1441                                          SmallVectorImpl<SDValue> &MemOpChains,
1442                                          ISD::ArgFlagsTy Flags) const {
1443
1444   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1445                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1446   unsigned id = Subtarget->isLittle() ? 0 : 1;
1447   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1448
1449   if (NextVA.isRegLoc())
1450     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1451   else {
1452     assert(NextVA.isMemLoc());
1453     if (!StackPtr.getNode())
1454       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
1455                                     getPointerTy(DAG.getDataLayout()));
1456
1457     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1458                                            dl, DAG, NextVA,
1459                                            Flags));
1460   }
1461 }
1462
1463 /// LowerCall - Lowering a call into a callseq_start <-
1464 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1465 /// nodes.
1466 SDValue
1467 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1468                              SmallVectorImpl<SDValue> &InVals) const {
1469   SelectionDAG &DAG                     = CLI.DAG;
1470   SDLoc &dl                             = CLI.DL;
1471   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1472   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1473   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1474   SDValue Chain                         = CLI.Chain;
1475   SDValue Callee                        = CLI.Callee;
1476   bool &isTailCall                      = CLI.IsTailCall;
1477   CallingConv::ID CallConv              = CLI.CallConv;
1478   bool doesNotRet                       = CLI.DoesNotReturn;
1479   bool isVarArg                         = CLI.IsVarArg;
1480
1481   MachineFunction &MF = DAG.getMachineFunction();
1482   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1483   bool isThisReturn   = false;
1484   bool isSibCall      = false;
1485   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
1486
1487   // Disable tail calls if they're not supported.
1488   if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
1489     isTailCall = false;
1490
1491   if (isTailCall) {
1492     // Check if it's really possible to do a tail call.
1493     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1494                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1495                                                    Outs, OutVals, Ins, DAG);
1496     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1497       report_fatal_error("failed to perform tail call elimination on a call "
1498                          "site marked musttail");
1499     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1500     // detected sibcalls.
1501     if (isTailCall) {
1502       ++NumTailCalls;
1503       isSibCall = true;
1504     }
1505   }
1506
1507   // Analyze operands of the call, assigning locations to each operand.
1508   SmallVector<CCValAssign, 16> ArgLocs;
1509   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1510                     *DAG.getContext(), Call);
1511   CCInfo.AnalyzeCallOperands(Outs,
1512                              CCAssignFnForNode(CallConv, /* Return*/ false,
1513                                                isVarArg));
1514
1515   // Get a count of how many bytes are to be pushed on the stack.
1516   unsigned NumBytes = CCInfo.getNextStackOffset();
1517
1518   // For tail calls, memory operands are available in our caller's stack.
1519   if (isSibCall)
1520     NumBytes = 0;
1521
1522   // Adjust the stack pointer for the new arguments...
1523   // These operations are automatically eliminated by the prolog/epilog pass
1524   if (!isSibCall)
1525     Chain = DAG.getCALLSEQ_START(Chain,
1526                                  DAG.getIntPtrConstant(NumBytes, dl, true), dl);
1527
1528   SDValue StackPtr =
1529       DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
1530
1531   RegsToPassVector RegsToPass;
1532   SmallVector<SDValue, 8> MemOpChains;
1533
1534   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1535   // of tail call optimization, arguments are handled later.
1536   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1537        i != e;
1538        ++i, ++realArgIdx) {
1539     CCValAssign &VA = ArgLocs[i];
1540     SDValue Arg = OutVals[realArgIdx];
1541     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1542     bool isByVal = Flags.isByVal();
1543
1544     // Promote the value if needed.
1545     switch (VA.getLocInfo()) {
1546     default: llvm_unreachable("Unknown loc info!");
1547     case CCValAssign::Full: break;
1548     case CCValAssign::SExt:
1549       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1550       break;
1551     case CCValAssign::ZExt:
1552       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1553       break;
1554     case CCValAssign::AExt:
1555       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1556       break;
1557     case CCValAssign::BCvt:
1558       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1559       break;
1560     }
1561
1562     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1563     if (VA.needsCustom()) {
1564       if (VA.getLocVT() == MVT::v2f64) {
1565         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1566                                   DAG.getConstant(0, dl, MVT::i32));
1567         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1568                                   DAG.getConstant(1, dl, MVT::i32));
1569
1570         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1571                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1572
1573         VA = ArgLocs[++i]; // skip ahead to next loc
1574         if (VA.isRegLoc()) {
1575           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1576                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1577         } else {
1578           assert(VA.isMemLoc());
1579
1580           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1581                                                  dl, DAG, VA, Flags));
1582         }
1583       } else {
1584         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1585                          StackPtr, MemOpChains, Flags);
1586       }
1587     } else if (VA.isRegLoc()) {
1588       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1589         assert(VA.getLocVT() == MVT::i32 &&
1590                "unexpected calling convention register assignment");
1591         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1592                "unexpected use of 'returned'");
1593         isThisReturn = true;
1594       }
1595       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1596     } else if (isByVal) {
1597       assert(VA.isMemLoc());
1598       unsigned offset = 0;
1599
1600       // True if this byval aggregate will be split between registers
1601       // and memory.
1602       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1603       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1604
1605       if (CurByValIdx < ByValArgsCount) {
1606
1607         unsigned RegBegin, RegEnd;
1608         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1609
1610         EVT PtrVT =
1611             DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
1612         unsigned int i, j;
1613         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1614           SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1615           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1616           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1617                                      MachinePointerInfo(),
1618                                      false, false, false,
1619                                      DAG.InferPtrAlignment(AddArg));
1620           MemOpChains.push_back(Load.getValue(1));
1621           RegsToPass.push_back(std::make_pair(j, Load));
1622         }
1623
1624         // If parameter size outsides register area, "offset" value
1625         // helps us to calculate stack slot for remained part properly.
1626         offset = RegEnd - RegBegin;
1627
1628         CCInfo.nextInRegsParam();
1629       }
1630
1631       if (Flags.getByValSize() > 4*offset) {
1632         auto PtrVT = getPointerTy(DAG.getDataLayout());
1633         unsigned LocMemOffset = VA.getLocMemOffset();
1634         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1635         SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
1636         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1637         SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
1638         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1639                                            MVT::i32);
1640         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1641                                             MVT::i32);
1642
1643         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1644         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1645         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1646                                           Ops));
1647       }
1648     } else if (!isSibCall) {
1649       assert(VA.isMemLoc());
1650
1651       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1652                                              dl, DAG, VA, Flags));
1653     }
1654   }
1655
1656   if (!MemOpChains.empty())
1657     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1658
1659   // Build a sequence of copy-to-reg nodes chained together with token chain
1660   // and flag operands which copy the outgoing args into the appropriate regs.
1661   SDValue InFlag;
1662   // Tail call byval lowering might overwrite argument registers so in case of
1663   // tail call optimization the copies to registers are lowered later.
1664   if (!isTailCall)
1665     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1666       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1667                                RegsToPass[i].second, InFlag);
1668       InFlag = Chain.getValue(1);
1669     }
1670
1671   // For tail calls lower the arguments to the 'real' stack slot.
1672   if (isTailCall) {
1673     // Force all the incoming stack arguments to be loaded from the stack
1674     // before any new outgoing arguments are stored to the stack, because the
1675     // outgoing stack slots may alias the incoming argument stack slots, and
1676     // the alias isn't otherwise explicit. This is slightly more conservative
1677     // than necessary, because it means that each store effectively depends
1678     // on every argument instead of just those arguments it would clobber.
1679
1680     // Do not flag preceding copytoreg stuff together with the following stuff.
1681     InFlag = SDValue();
1682     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1683       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1684                                RegsToPass[i].second, InFlag);
1685       InFlag = Chain.getValue(1);
1686     }
1687     InFlag = SDValue();
1688   }
1689
1690   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1691   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1692   // node so that legalize doesn't hack it.
1693   bool isDirect = false;
1694   bool isARMFunc = false;
1695   bool isLocalARMFunc = false;
1696   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1697   auto PtrVt = getPointerTy(DAG.getDataLayout());
1698
1699   if (Subtarget->genLongCalls()) {
1700     assert((Subtarget->isTargetWindows() ||
1701             getTargetMachine().getRelocationModel() == Reloc::Static) &&
1702            "long-calls with non-static relocation model!");
1703     // Handle a global address or an external symbol. If it's not one of
1704     // those, the target's already in a register, so we don't need to do
1705     // anything extra.
1706     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1707       const GlobalValue *GV = G->getGlobal();
1708       // Create a constant pool entry for the callee address
1709       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1710       ARMConstantPoolValue *CPV =
1711         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1712
1713       // Get the address of the callee into a register
1714       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1715       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1716       Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), CPAddr,
1717                            MachinePointerInfo::getConstantPool(), false, false,
1718                            false, 0);
1719     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1720       const char *Sym = S->getSymbol();
1721
1722       // Create a constant pool entry for the callee address
1723       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1724       ARMConstantPoolValue *CPV =
1725         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1726                                       ARMPCLabelIndex, 0);
1727       // Get the address of the callee into a register
1728       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1729       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1730       Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), CPAddr,
1731                            MachinePointerInfo::getConstantPool(), false, false,
1732                            false, 0);
1733     }
1734   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1735     const GlobalValue *GV = G->getGlobal();
1736     isDirect = true;
1737     bool isDef = GV->isStrongDefinitionForLinker();
1738     bool isStub = (!isDef && Subtarget->isTargetMachO()) &&
1739                    getTargetMachine().getRelocationModel() != Reloc::Static;
1740     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1741     // ARM call to a local ARM function is predicable.
1742     isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
1743     // tBX takes a register source operand.
1744     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1745       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1746       Callee = DAG.getNode(
1747           ARMISD::WrapperPIC, dl, PtrVt,
1748           DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
1749       Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), Callee,
1750                            MachinePointerInfo::getGOT(), false, false, true, 0);
1751     } else if (Subtarget->isTargetCOFF()) {
1752       assert(Subtarget->isTargetWindows() &&
1753              "Windows is the only supported COFF target");
1754       unsigned TargetFlags = GV->hasDLLImportStorageClass()
1755                                  ? ARMII::MO_DLLIMPORT
1756                                  : ARMII::MO_NO_FLAG;
1757       Callee =
1758           DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0, TargetFlags);
1759       if (GV->hasDLLImportStorageClass())
1760         Callee =
1761             DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
1762                         DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
1763                         MachinePointerInfo::getGOT(), false, false, false, 0);
1764     } else {
1765       // On ELF targets for PIC code, direct calls should go through the PLT
1766       unsigned OpFlags = 0;
1767       if (Subtarget->isTargetELF() &&
1768           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1769         OpFlags = ARMII::MO_PLT;
1770       Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, OpFlags);
1771     }
1772   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1773     isDirect = true;
1774     bool isStub = Subtarget->isTargetMachO() &&
1775                   getTargetMachine().getRelocationModel() != Reloc::Static;
1776     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1777     // tBX takes a register source operand.
1778     const char *Sym = S->getSymbol();
1779     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1780       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1781       ARMConstantPoolValue *CPV =
1782         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1783                                       ARMPCLabelIndex, 4);
1784       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1785       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1786       Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), CPAddr,
1787                            MachinePointerInfo::getConstantPool(), false, false,
1788                            false, 0);
1789       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
1790       Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
1791     } else {
1792       unsigned OpFlags = 0;
1793       // On ELF targets for PIC code, direct calls should go through the PLT
1794       if (Subtarget->isTargetELF() &&
1795                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1796         OpFlags = ARMII::MO_PLT;
1797       Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, OpFlags);
1798     }
1799   }
1800
1801   // FIXME: handle tail calls differently.
1802   unsigned CallOpc;
1803   bool HasMinSizeAttr = MF.getFunction()->hasFnAttribute(Attribute::MinSize);
1804   if (Subtarget->isThumb()) {
1805     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1806       CallOpc = ARMISD::CALL_NOLINK;
1807     else
1808       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1809   } else {
1810     if (!isDirect && !Subtarget->hasV5TOps())
1811       CallOpc = ARMISD::CALL_NOLINK;
1812     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1813                // Emit regular call when code size is the priority
1814                !HasMinSizeAttr)
1815       // "mov lr, pc; b _foo" to avoid confusing the RSP
1816       CallOpc = ARMISD::CALL_NOLINK;
1817     else
1818       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1819   }
1820
1821   std::vector<SDValue> Ops;
1822   Ops.push_back(Chain);
1823   Ops.push_back(Callee);
1824
1825   // Add argument registers to the end of the list so that they are known live
1826   // into the call.
1827   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1828     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1829                                   RegsToPass[i].second.getValueType()));
1830
1831   // Add a register mask operand representing the call-preserved registers.
1832   if (!isTailCall) {
1833     const uint32_t *Mask;
1834     const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
1835     if (isThisReturn) {
1836       // For 'this' returns, use the R0-preserving mask if applicable
1837       Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
1838       if (!Mask) {
1839         // Set isThisReturn to false if the calling convention is not one that
1840         // allows 'returned' to be modeled in this way, so LowerCallResult does
1841         // not try to pass 'this' straight through
1842         isThisReturn = false;
1843         Mask = ARI->getCallPreservedMask(MF, CallConv);
1844       }
1845     } else
1846       Mask = ARI->getCallPreservedMask(MF, CallConv);
1847
1848     assert(Mask && "Missing call preserved mask for calling convention");
1849     Ops.push_back(DAG.getRegisterMask(Mask));
1850   }
1851
1852   if (InFlag.getNode())
1853     Ops.push_back(InFlag);
1854
1855   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1856   if (isTailCall) {
1857     MF.getFrameInfo()->setHasTailCall();
1858     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1859   }
1860
1861   // Returns a chain and a flag for retval copy to use.
1862   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1863   InFlag = Chain.getValue(1);
1864
1865   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
1866                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
1867   if (!Ins.empty())
1868     InFlag = Chain.getValue(1);
1869
1870   // Handle result values, copying them out of physregs into vregs that we
1871   // return.
1872   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1873                          InVals, isThisReturn,
1874                          isThisReturn ? OutVals[0] : SDValue());
1875 }
1876
1877 /// HandleByVal - Every parameter *after* a byval parameter is passed
1878 /// on the stack.  Remember the next parameter register to allocate,
1879 /// and then confiscate the rest of the parameter registers to insure
1880 /// this.
1881 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
1882                                     unsigned Align) const {
1883   assert((State->getCallOrPrologue() == Prologue ||
1884           State->getCallOrPrologue() == Call) &&
1885          "unhandled ParmContext");
1886
1887   // Byval (as with any stack) slots are always at least 4 byte aligned.
1888   Align = std::max(Align, 4U);
1889
1890   unsigned Reg = State->AllocateReg(GPRArgRegs);
1891   if (!Reg)
1892     return;
1893
1894   unsigned AlignInRegs = Align / 4;
1895   unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
1896   for (unsigned i = 0; i < Waste; ++i)
1897     Reg = State->AllocateReg(GPRArgRegs);
1898
1899   if (!Reg)
1900     return;
1901
1902   unsigned Excess = 4 * (ARM::R4 - Reg);
1903
1904   // Special case when NSAA != SP and parameter size greater than size of
1905   // all remained GPR regs. In that case we can't split parameter, we must
1906   // send it to stack. We also must set NCRN to R4, so waste all
1907   // remained registers.
1908   const unsigned NSAAOffset = State->getNextStackOffset();
1909   if (NSAAOffset != 0 && Size > Excess) {
1910     while (State->AllocateReg(GPRArgRegs))
1911       ;
1912     return;
1913   }
1914
1915   // First register for byval parameter is the first register that wasn't
1916   // allocated before this method call, so it would be "reg".
1917   // If parameter is small enough to be saved in range [reg, r4), then
1918   // the end (first after last) register would be reg + param-size-in-regs,
1919   // else parameter would be splitted between registers and stack,
1920   // end register would be r4 in this case.
1921   unsigned ByValRegBegin = Reg;
1922   unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
1923   State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1924   // Note, first register is allocated in the beginning of function already,
1925   // allocate remained amount of registers we need.
1926   for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
1927     State->AllocateReg(GPRArgRegs);
1928   // A byval parameter that is split between registers and memory needs its
1929   // size truncated here.
1930   // In the case where the entire structure fits in registers, we set the
1931   // size in memory to zero.
1932   Size = std::max<int>(Size - Excess, 0);
1933 }
1934
1935 /// MatchingStackOffset - Return true if the given stack call argument is
1936 /// already available in the same position (relatively) of the caller's
1937 /// incoming argument stack.
1938 static
1939 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1940                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1941                          const TargetInstrInfo *TII) {
1942   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1943   int FI = INT_MAX;
1944   if (Arg.getOpcode() == ISD::CopyFromReg) {
1945     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1946     if (!TargetRegisterInfo::isVirtualRegister(VR))
1947       return false;
1948     MachineInstr *Def = MRI->getVRegDef(VR);
1949     if (!Def)
1950       return false;
1951     if (!Flags.isByVal()) {
1952       if (!TII->isLoadFromStackSlot(Def, FI))
1953         return false;
1954     } else {
1955       return false;
1956     }
1957   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1958     if (Flags.isByVal())
1959       // ByVal argument is passed in as a pointer but it's now being
1960       // dereferenced. e.g.
1961       // define @foo(%struct.X* %A) {
1962       //   tail call @bar(%struct.X* byval %A)
1963       // }
1964       return false;
1965     SDValue Ptr = Ld->getBasePtr();
1966     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1967     if (!FINode)
1968       return false;
1969     FI = FINode->getIndex();
1970   } else
1971     return false;
1972
1973   assert(FI != INT_MAX);
1974   if (!MFI->isFixedObjectIndex(FI))
1975     return false;
1976   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1977 }
1978
1979 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1980 /// for tail call optimization. Targets which want to do tail call
1981 /// optimization should implement this function.
1982 bool
1983 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1984                                                      CallingConv::ID CalleeCC,
1985                                                      bool isVarArg,
1986                                                      bool isCalleeStructRet,
1987                                                      bool isCallerStructRet,
1988                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1989                                     const SmallVectorImpl<SDValue> &OutVals,
1990                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1991                                                      SelectionDAG& DAG) const {
1992   const Function *CallerF = DAG.getMachineFunction().getFunction();
1993   CallingConv::ID CallerCC = CallerF->getCallingConv();
1994   bool CCMatch = CallerCC == CalleeCC;
1995
1996   // Look for obvious safe cases to perform tail call optimization that do not
1997   // require ABI changes. This is what gcc calls sibcall.
1998
1999   // Do not sibcall optimize vararg calls unless the call site is not passing
2000   // any arguments.
2001   if (isVarArg && !Outs.empty())
2002     return false;
2003
2004   // Exception-handling functions need a special set of instructions to indicate
2005   // a return to the hardware. Tail-calling another function would probably
2006   // break this.
2007   if (CallerF->hasFnAttribute("interrupt"))
2008     return false;
2009
2010   // Also avoid sibcall optimization if either caller or callee uses struct
2011   // return semantics.
2012   if (isCalleeStructRet || isCallerStructRet)
2013     return false;
2014
2015   // FIXME: Completely disable sibcall for Thumb1 since ThumbRegisterInfo::
2016   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
2017   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
2018   // support in the assembler and linker to be used. This would need to be
2019   // fixed to fully support tail calls in Thumb1.
2020   //
2021   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
2022   // LR.  This means if we need to reload LR, it takes an extra instructions,
2023   // which outweighs the value of the tail call; but here we don't know yet
2024   // whether LR is going to be used.  Probably the right approach is to
2025   // generate the tail call here and turn it back into CALL/RET in
2026   // emitEpilogue if LR is used.
2027
2028   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
2029   // but we need to make sure there are enough registers; the only valid
2030   // registers are the 4 used for parameters.  We don't currently do this
2031   // case.
2032   if (Subtarget->isThumb1Only())
2033     return false;
2034
2035   // Externally-defined functions with weak linkage should not be
2036   // tail-called on ARM when the OS does not support dynamic
2037   // pre-emption of symbols, as the AAELF spec requires normal calls
2038   // to undefined weak functions to be replaced with a NOP or jump to the
2039   // next instruction. The behaviour of branch instructions in this
2040   // situation (as used for tail calls) is implementation-defined, so we
2041   // cannot rely on the linker replacing the tail call with a return.
2042   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2043     const GlobalValue *GV = G->getGlobal();
2044     const Triple &TT = getTargetMachine().getTargetTriple();
2045     if (GV->hasExternalWeakLinkage() &&
2046         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2047       return false;
2048   }
2049
2050   // If the calling conventions do not match, then we'd better make sure the
2051   // results are returned in the same way as what the caller expects.
2052   if (!CCMatch) {
2053     SmallVector<CCValAssign, 16> RVLocs1;
2054     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2055                        *DAG.getContext(), Call);
2056     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2057
2058     SmallVector<CCValAssign, 16> RVLocs2;
2059     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2060                        *DAG.getContext(), Call);
2061     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2062
2063     if (RVLocs1.size() != RVLocs2.size())
2064       return false;
2065     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2066       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2067         return false;
2068       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2069         return false;
2070       if (RVLocs1[i].isRegLoc()) {
2071         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2072           return false;
2073       } else {
2074         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2075           return false;
2076       }
2077     }
2078   }
2079
2080   // If Caller's vararg or byval argument has been split between registers and
2081   // stack, do not perform tail call, since part of the argument is in caller's
2082   // local frame.
2083   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2084                                       getInfo<ARMFunctionInfo>();
2085   if (AFI_Caller->getArgRegsSaveSize())
2086     return false;
2087
2088   // If the callee takes no arguments then go on to check the results of the
2089   // call.
2090   if (!Outs.empty()) {
2091     // Check if stack adjustment is needed. For now, do not do this if any
2092     // argument is passed on the stack.
2093     SmallVector<CCValAssign, 16> ArgLocs;
2094     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2095                       *DAG.getContext(), Call);
2096     CCInfo.AnalyzeCallOperands(Outs,
2097                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2098     if (CCInfo.getNextStackOffset()) {
2099       MachineFunction &MF = DAG.getMachineFunction();
2100
2101       // Check if the arguments are already laid out in the right way as
2102       // the caller's fixed stack objects.
2103       MachineFrameInfo *MFI = MF.getFrameInfo();
2104       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2105       const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2106       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2107            i != e;
2108            ++i, ++realArgIdx) {
2109         CCValAssign &VA = ArgLocs[i];
2110         EVT RegVT = VA.getLocVT();
2111         SDValue Arg = OutVals[realArgIdx];
2112         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2113         if (VA.getLocInfo() == CCValAssign::Indirect)
2114           return false;
2115         if (VA.needsCustom()) {
2116           // f64 and vector types are split into multiple registers or
2117           // register/stack-slot combinations.  The types will not match
2118           // the registers; give up on memory f64 refs until we figure
2119           // out what to do about this.
2120           if (!VA.isRegLoc())
2121             return false;
2122           if (!ArgLocs[++i].isRegLoc())
2123             return false;
2124           if (RegVT == MVT::v2f64) {
2125             if (!ArgLocs[++i].isRegLoc())
2126               return false;
2127             if (!ArgLocs[++i].isRegLoc())
2128               return false;
2129           }
2130         } else if (!VA.isRegLoc()) {
2131           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2132                                    MFI, MRI, TII))
2133             return false;
2134         }
2135       }
2136     }
2137   }
2138
2139   return true;
2140 }
2141
2142 bool
2143 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2144                                   MachineFunction &MF, bool isVarArg,
2145                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2146                                   LLVMContext &Context) const {
2147   SmallVector<CCValAssign, 16> RVLocs;
2148   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2149   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2150                                                     isVarArg));
2151 }
2152
2153 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2154                                     SDLoc DL, SelectionDAG &DAG) {
2155   const MachineFunction &MF = DAG.getMachineFunction();
2156   const Function *F = MF.getFunction();
2157
2158   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2159
2160   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2161   // version of the "preferred return address". These offsets affect the return
2162   // instruction if this is a return from PL1 without hypervisor extensions.
2163   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2164   //    SWI:     0      "subs pc, lr, #0"
2165   //    ABORT:   +4     "subs pc, lr, #4"
2166   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2167   // UNDEF varies depending on where the exception came from ARM or Thumb
2168   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2169
2170   int64_t LROffset;
2171   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2172       IntKind == "ABORT")
2173     LROffset = 4;
2174   else if (IntKind == "SWI" || IntKind == "UNDEF")
2175     LROffset = 0;
2176   else
2177     report_fatal_error("Unsupported interrupt attribute. If present, value "
2178                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2179
2180   RetOps.insert(RetOps.begin() + 1,
2181                 DAG.getConstant(LROffset, DL, MVT::i32, false));
2182
2183   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2184 }
2185
2186 SDValue
2187 ARMTargetLowering::LowerReturn(SDValue Chain,
2188                                CallingConv::ID CallConv, bool isVarArg,
2189                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2190                                const SmallVectorImpl<SDValue> &OutVals,
2191                                SDLoc dl, SelectionDAG &DAG) const {
2192
2193   // CCValAssign - represent the assignment of the return value to a location.
2194   SmallVector<CCValAssign, 16> RVLocs;
2195
2196   // CCState - Info about the registers and stack slots.
2197   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2198                     *DAG.getContext(), Call);
2199
2200   // Analyze outgoing return values.
2201   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2202                                                isVarArg));
2203
2204   SDValue Flag;
2205   SmallVector<SDValue, 4> RetOps;
2206   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2207   bool isLittleEndian = Subtarget->isLittle();
2208
2209   MachineFunction &MF = DAG.getMachineFunction();
2210   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2211   AFI->setReturnRegsCount(RVLocs.size());
2212
2213   // Copy the result values into the output registers.
2214   for (unsigned i = 0, realRVLocIdx = 0;
2215        i != RVLocs.size();
2216        ++i, ++realRVLocIdx) {
2217     CCValAssign &VA = RVLocs[i];
2218     assert(VA.isRegLoc() && "Can only return in registers!");
2219
2220     SDValue Arg = OutVals[realRVLocIdx];
2221
2222     switch (VA.getLocInfo()) {
2223     default: llvm_unreachable("Unknown loc info!");
2224     case CCValAssign::Full: break;
2225     case CCValAssign::BCvt:
2226       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2227       break;
2228     }
2229
2230     if (VA.needsCustom()) {
2231       if (VA.getLocVT() == MVT::v2f64) {
2232         // Extract the first half and return it in two registers.
2233         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2234                                    DAG.getConstant(0, dl, MVT::i32));
2235         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2236                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2237
2238         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2239                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2240                                  Flag);
2241         Flag = Chain.getValue(1);
2242         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2243         VA = RVLocs[++i]; // skip ahead to next loc
2244         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2245                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2246                                  Flag);
2247         Flag = Chain.getValue(1);
2248         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2249         VA = RVLocs[++i]; // skip ahead to next loc
2250
2251         // Extract the 2nd half and fall through to handle it as an f64 value.
2252         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2253                           DAG.getConstant(1, dl, MVT::i32));
2254       }
2255       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2256       // available.
2257       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2258                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2259       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2260                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2261                                Flag);
2262       Flag = Chain.getValue(1);
2263       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2264       VA = RVLocs[++i]; // skip ahead to next loc
2265       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2266                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2267                                Flag);
2268     } else
2269       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2270
2271     // Guarantee that all emitted copies are
2272     // stuck together, avoiding something bad.
2273     Flag = Chain.getValue(1);
2274     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2275   }
2276
2277   // Update chain and glue.
2278   RetOps[0] = Chain;
2279   if (Flag.getNode())
2280     RetOps.push_back(Flag);
2281
2282   // CPUs which aren't M-class use a special sequence to return from
2283   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2284   // though we use "subs pc, lr, #N").
2285   //
2286   // M-class CPUs actually use a normal return sequence with a special
2287   // (hardware-provided) value in LR, so the normal code path works.
2288   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2289       !Subtarget->isMClass()) {
2290     if (Subtarget->isThumb1Only())
2291       report_fatal_error("interrupt attribute is not supported in Thumb1");
2292     return LowerInterruptReturn(RetOps, dl, DAG);
2293   }
2294
2295   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2296 }
2297
2298 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2299   if (N->getNumValues() != 1)
2300     return false;
2301   if (!N->hasNUsesOfValue(1, 0))
2302     return false;
2303
2304   SDValue TCChain = Chain;
2305   SDNode *Copy = *N->use_begin();
2306   if (Copy->getOpcode() == ISD::CopyToReg) {
2307     // If the copy has a glue operand, we conservatively assume it isn't safe to
2308     // perform a tail call.
2309     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2310       return false;
2311     TCChain = Copy->getOperand(0);
2312   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2313     SDNode *VMov = Copy;
2314     // f64 returned in a pair of GPRs.
2315     SmallPtrSet<SDNode*, 2> Copies;
2316     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2317          UI != UE; ++UI) {
2318       if (UI->getOpcode() != ISD::CopyToReg)
2319         return false;
2320       Copies.insert(*UI);
2321     }
2322     if (Copies.size() > 2)
2323       return false;
2324
2325     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2326          UI != UE; ++UI) {
2327       SDValue UseChain = UI->getOperand(0);
2328       if (Copies.count(UseChain.getNode()))
2329         // Second CopyToReg
2330         Copy = *UI;
2331       else {
2332         // We are at the top of this chain.
2333         // If the copy has a glue operand, we conservatively assume it
2334         // isn't safe to perform a tail call.
2335         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2336           return false;
2337         // First CopyToReg
2338         TCChain = UseChain;
2339       }
2340     }
2341   } else if (Copy->getOpcode() == ISD::BITCAST) {
2342     // f32 returned in a single GPR.
2343     if (!Copy->hasOneUse())
2344       return false;
2345     Copy = *Copy->use_begin();
2346     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2347       return false;
2348     // If the copy has a glue operand, we conservatively assume it isn't safe to
2349     // perform a tail call.
2350     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2351       return false;
2352     TCChain = Copy->getOperand(0);
2353   } else {
2354     return false;
2355   }
2356
2357   bool HasRet = false;
2358   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2359        UI != UE; ++UI) {
2360     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2361         UI->getOpcode() != ARMISD::INTRET_FLAG)
2362       return false;
2363     HasRet = true;
2364   }
2365
2366   if (!HasRet)
2367     return false;
2368
2369   Chain = TCChain;
2370   return true;
2371 }
2372
2373 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2374   if (!Subtarget->supportsTailCall())
2375     return false;
2376
2377   auto Attr =
2378       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2379   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2380     return false;
2381
2382   return !Subtarget->isThumb1Only();
2383 }
2384
2385 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2386 // and pass the lower and high parts through.
2387 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2388   SDLoc DL(Op);
2389   SDValue WriteValue = Op->getOperand(2);
2390
2391   // This function is only supposed to be called for i64 type argument.
2392   assert(WriteValue.getValueType() == MVT::i64
2393           && "LowerWRITE_REGISTER called for non-i64 type argument.");
2394
2395   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2396                            DAG.getConstant(0, DL, MVT::i32));
2397   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2398                            DAG.getConstant(1, DL, MVT::i32));
2399   SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2400   return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2401 }
2402
2403 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2404 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2405 // one of the above mentioned nodes. It has to be wrapped because otherwise
2406 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2407 // be used to form addressing mode. These wrapped nodes will be selected
2408 // into MOVi.
2409 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2410   EVT PtrVT = Op.getValueType();
2411   // FIXME there is no actual debug info here
2412   SDLoc dl(Op);
2413   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2414   SDValue Res;
2415   if (CP->isMachineConstantPoolEntry())
2416     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2417                                     CP->getAlignment());
2418   else
2419     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2420                                     CP->getAlignment());
2421   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2422 }
2423
2424 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2425   return MachineJumpTableInfo::EK_Inline;
2426 }
2427
2428 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2429                                              SelectionDAG &DAG) const {
2430   MachineFunction &MF = DAG.getMachineFunction();
2431   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2432   unsigned ARMPCLabelIndex = 0;
2433   SDLoc DL(Op);
2434   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2435   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2436   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2437   SDValue CPAddr;
2438   if (RelocM == Reloc::Static) {
2439     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2440   } else {
2441     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2442     ARMPCLabelIndex = AFI->createPICLabelUId();
2443     ARMConstantPoolValue *CPV =
2444       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2445                                       ARMCP::CPBlockAddress, PCAdj);
2446     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2447   }
2448   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2449   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2450                                MachinePointerInfo::getConstantPool(),
2451                                false, false, false, 0);
2452   if (RelocM == Reloc::Static)
2453     return Result;
2454   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2455   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2456 }
2457
2458 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2459 SDValue
2460 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2461                                                  SelectionDAG &DAG) const {
2462   SDLoc dl(GA);
2463   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2464   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2465   MachineFunction &MF = DAG.getMachineFunction();
2466   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2467   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2468   ARMConstantPoolValue *CPV =
2469     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2470                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2471   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2472   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2473   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2474                          MachinePointerInfo::getConstantPool(),
2475                          false, false, false, 0);
2476   SDValue Chain = Argument.getValue(1);
2477
2478   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2479   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2480
2481   // call __tls_get_addr.
2482   ArgListTy Args;
2483   ArgListEntry Entry;
2484   Entry.Node = Argument;
2485   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2486   Args.push_back(Entry);
2487
2488   // FIXME: is there useful debug info available here?
2489   TargetLowering::CallLoweringInfo CLI(DAG);
2490   CLI.setDebugLoc(dl).setChain(Chain)
2491     .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2492                DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2493                0);
2494
2495   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2496   return CallResult.first;
2497 }
2498
2499 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2500 // "local exec" model.
2501 SDValue
2502 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2503                                         SelectionDAG &DAG,
2504                                         TLSModel::Model model) const {
2505   const GlobalValue *GV = GA->getGlobal();
2506   SDLoc dl(GA);
2507   SDValue Offset;
2508   SDValue Chain = DAG.getEntryNode();
2509   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2510   // Get the Thread Pointer
2511   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2512
2513   if (model == TLSModel::InitialExec) {
2514     MachineFunction &MF = DAG.getMachineFunction();
2515     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2516     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2517     // Initial exec model.
2518     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2519     ARMConstantPoolValue *CPV =
2520       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2521                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2522                                       true);
2523     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2524     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2525     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2526                          MachinePointerInfo::getConstantPool(),
2527                          false, false, false, 0);
2528     Chain = Offset.getValue(1);
2529
2530     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2531     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2532
2533     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2534                          MachinePointerInfo::getConstantPool(),
2535                          false, false, false, 0);
2536   } else {
2537     // local exec model
2538     assert(model == TLSModel::LocalExec);
2539     ARMConstantPoolValue *CPV =
2540       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2541     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2542     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2543     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2544                          MachinePointerInfo::getConstantPool(),
2545                          false, false, false, 0);
2546   }
2547
2548   // The address of the thread local variable is the add of the thread
2549   // pointer with the offset of the variable.
2550   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2551 }
2552
2553 SDValue
2554 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2555   // TODO: implement the "local dynamic" model
2556   assert(Subtarget->isTargetELF() &&
2557          "TLS not implemented for non-ELF targets");
2558   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2559
2560   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2561
2562   switch (model) {
2563     case TLSModel::GeneralDynamic:
2564     case TLSModel::LocalDynamic:
2565       return LowerToTLSGeneralDynamicModel(GA, DAG);
2566     case TLSModel::InitialExec:
2567     case TLSModel::LocalExec:
2568       return LowerToTLSExecModels(GA, DAG, model);
2569   }
2570   llvm_unreachable("bogus TLS model");
2571 }
2572
2573 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2574                                                  SelectionDAG &DAG) const {
2575   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2576   SDLoc dl(Op);
2577   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2578   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2579     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2580     ARMConstantPoolValue *CPV =
2581       ARMConstantPoolConstant::Create(GV,
2582                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2583     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2584     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2585     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2586                                  CPAddr,
2587                                  MachinePointerInfo::getConstantPool(),
2588                                  false, false, false, 0);
2589     SDValue Chain = Result.getValue(1);
2590     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2591     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2592     if (!UseGOTOFF)
2593       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2594                            MachinePointerInfo::getGOT(),
2595                            false, false, false, 0);
2596     return Result;
2597   }
2598
2599   // If we have T2 ops, we can materialize the address directly via movt/movw
2600   // pair. This is always cheaper.
2601   if (Subtarget->useMovt(DAG.getMachineFunction())) {
2602     ++NumMovwMovt;
2603     // FIXME: Once remat is capable of dealing with instructions with register
2604     // operands, expand this into two nodes.
2605     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2606                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2607   } else {
2608     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2609     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2610     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2611                        MachinePointerInfo::getConstantPool(),
2612                        false, false, false, 0);
2613   }
2614 }
2615
2616 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2617                                                     SelectionDAG &DAG) const {
2618   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2619   SDLoc dl(Op);
2620   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2621   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2622
2623   if (Subtarget->useMovt(DAG.getMachineFunction()))
2624     ++NumMovwMovt;
2625
2626   // FIXME: Once remat is capable of dealing with instructions with register
2627   // operands, expand this into multiple nodes
2628   unsigned Wrapper =
2629       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2630
2631   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2632   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2633
2634   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2635     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2636                          MachinePointerInfo::getGOT(), false, false, false, 0);
2637   return Result;
2638 }
2639
2640 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2641                                                      SelectionDAG &DAG) const {
2642   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2643   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2644          "Windows on ARM expects to use movw/movt");
2645
2646   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2647   const ARMII::TOF TargetFlags =
2648     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2649   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2650   SDValue Result;
2651   SDLoc DL(Op);
2652
2653   ++NumMovwMovt;
2654
2655   // FIXME: Once remat is capable of dealing with instructions with register
2656   // operands, expand this into two nodes.
2657   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2658                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2659                                                   TargetFlags));
2660   if (GV->hasDLLImportStorageClass())
2661     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2662                          MachinePointerInfo::getGOT(), false, false, false, 0);
2663   return Result;
2664 }
2665
2666 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2667                                                     SelectionDAG &DAG) const {
2668   assert(Subtarget->isTargetELF() &&
2669          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2670   MachineFunction &MF = DAG.getMachineFunction();
2671   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2672   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2673   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2674   SDLoc dl(Op);
2675   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2676   ARMConstantPoolValue *CPV =
2677     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2678                                   ARMPCLabelIndex, PCAdj);
2679   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2680   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2681   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2682                                MachinePointerInfo::getConstantPool(),
2683                                false, false, false, 0);
2684   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2685   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2686 }
2687
2688 SDValue
2689 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2690   SDLoc dl(Op);
2691   SDValue Val = DAG.getConstant(0, dl, MVT::i32);
2692   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2693                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2694                      Op.getOperand(1), Val);
2695 }
2696
2697 SDValue
2698 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2699   SDLoc dl(Op);
2700   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2701                      Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
2702 }
2703
2704 SDValue
2705 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2706                                           const ARMSubtarget *Subtarget) const {
2707   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2708   SDLoc dl(Op);
2709   switch (IntNo) {
2710   default: return SDValue();    // Don't custom lower most intrinsics.
2711   case Intrinsic::arm_rbit: {
2712     assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2713            "RBIT intrinsic must have i32 type!");
2714     return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1));
2715   }
2716   case Intrinsic::arm_thread_pointer: {
2717     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2718     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2719   }
2720   case Intrinsic::eh_sjlj_lsda: {
2721     MachineFunction &MF = DAG.getMachineFunction();
2722     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2723     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2724     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2725     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2726     SDValue CPAddr;
2727     unsigned PCAdj = (RelocM != Reloc::PIC_)
2728       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2729     ARMConstantPoolValue *CPV =
2730       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2731                                       ARMCP::CPLSDA, PCAdj);
2732     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2733     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2734     SDValue Result =
2735       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2736                   MachinePointerInfo::getConstantPool(),
2737                   false, false, false, 0);
2738
2739     if (RelocM == Reloc::PIC_) {
2740       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2741       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2742     }
2743     return Result;
2744   }
2745   case Intrinsic::arm_neon_vmulls:
2746   case Intrinsic::arm_neon_vmullu: {
2747     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2748       ? ARMISD::VMULLs : ARMISD::VMULLu;
2749     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2750                        Op.getOperand(1), Op.getOperand(2));
2751   }
2752   }
2753 }
2754
2755 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2756                                  const ARMSubtarget *Subtarget) {
2757   // FIXME: handle "fence singlethread" more efficiently.
2758   SDLoc dl(Op);
2759   if (!Subtarget->hasDataBarrier()) {
2760     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2761     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2762     // here.
2763     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2764            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2765     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2766                        DAG.getConstant(0, dl, MVT::i32));
2767   }
2768
2769   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2770   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2771   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
2772   if (Subtarget->isMClass()) {
2773     // Only a full system barrier exists in the M-class architectures.
2774     Domain = ARM_MB::SY;
2775   } else if (Subtarget->isSwift() && Ord == Release) {
2776     // Swift happens to implement ISHST barriers in a way that's compatible with
2777     // Release semantics but weaker than ISH so we'd be fools not to use
2778     // it. Beware: other processors probably don't!
2779     Domain = ARM_MB::ISHST;
2780   }
2781
2782   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2783                      DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
2784                      DAG.getConstant(Domain, dl, MVT::i32));
2785 }
2786
2787 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2788                              const ARMSubtarget *Subtarget) {
2789   // ARM pre v5TE and Thumb1 does not have preload instructions.
2790   if (!(Subtarget->isThumb2() ||
2791         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2792     // Just preserve the chain.
2793     return Op.getOperand(0);
2794
2795   SDLoc dl(Op);
2796   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2797   if (!isRead &&
2798       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2799     // ARMv7 with MP extension has PLDW.
2800     return Op.getOperand(0);
2801
2802   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2803   if (Subtarget->isThumb()) {
2804     // Invert the bits.
2805     isRead = ~isRead & 1;
2806     isData = ~isData & 1;
2807   }
2808
2809   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2810                      Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
2811                      DAG.getConstant(isData, dl, MVT::i32));
2812 }
2813
2814 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2815   MachineFunction &MF = DAG.getMachineFunction();
2816   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2817
2818   // vastart just stores the address of the VarArgsFrameIndex slot into the
2819   // memory location argument.
2820   SDLoc dl(Op);
2821   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2822   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2823   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2824   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2825                       MachinePointerInfo(SV), false, false, 0);
2826 }
2827
2828 SDValue
2829 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2830                                         SDValue &Root, SelectionDAG &DAG,
2831                                         SDLoc dl) const {
2832   MachineFunction &MF = DAG.getMachineFunction();
2833   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2834
2835   const TargetRegisterClass *RC;
2836   if (AFI->isThumb1OnlyFunction())
2837     RC = &ARM::tGPRRegClass;
2838   else
2839     RC = &ARM::GPRRegClass;
2840
2841   // Transform the arguments stored in physical registers into virtual ones.
2842   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2843   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2844
2845   SDValue ArgValue2;
2846   if (NextVA.isMemLoc()) {
2847     MachineFrameInfo *MFI = MF.getFrameInfo();
2848     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2849
2850     // Create load node to retrieve arguments from the stack.
2851     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2852     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2853                             MachinePointerInfo::getFixedStack(FI),
2854                             false, false, false, 0);
2855   } else {
2856     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2857     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2858   }
2859   if (!Subtarget->isLittle())
2860     std::swap (ArgValue, ArgValue2);
2861   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2862 }
2863
2864 // The remaining GPRs hold either the beginning of variable-argument
2865 // data, or the beginning of an aggregate passed by value (usually
2866 // byval).  Either way, we allocate stack slots adjacent to the data
2867 // provided by our caller, and store the unallocated registers there.
2868 // If this is a variadic function, the va_list pointer will begin with
2869 // these values; otherwise, this reassembles a (byval) structure that
2870 // was split between registers and memory.
2871 // Return: The frame index registers were stored into.
2872 int
2873 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2874                                   SDLoc dl, SDValue &Chain,
2875                                   const Value *OrigArg,
2876                                   unsigned InRegsParamRecordIdx,
2877                                   int ArgOffset,
2878                                   unsigned ArgSize) const {
2879   // Currently, two use-cases possible:
2880   // Case #1. Non-var-args function, and we meet first byval parameter.
2881   //          Setup first unallocated register as first byval register;
2882   //          eat all remained registers
2883   //          (these two actions are performed by HandleByVal method).
2884   //          Then, here, we initialize stack frame with
2885   //          "store-reg" instructions.
2886   // Case #2. Var-args function, that doesn't contain byval parameters.
2887   //          The same: eat all remained unallocated registers,
2888   //          initialize stack frame.
2889
2890   MachineFunction &MF = DAG.getMachineFunction();
2891   MachineFrameInfo *MFI = MF.getFrameInfo();
2892   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2893   unsigned RBegin, REnd;
2894   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2895     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2896   } else {
2897     unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
2898     RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
2899     REnd = ARM::R4;
2900   }
2901
2902   if (REnd != RBegin)
2903     ArgOffset = -4 * (ARM::R4 - RBegin);
2904
2905   auto PtrVT = getPointerTy(DAG.getDataLayout());
2906   int FrameIndex = MFI->CreateFixedObject(ArgSize, ArgOffset, false);
2907   SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
2908
2909   SmallVector<SDValue, 4> MemOps;
2910   const TargetRegisterClass *RC =
2911       AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
2912
2913   for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
2914     unsigned VReg = MF.addLiveIn(Reg, RC);
2915     SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2916     SDValue Store =
2917         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2918                      MachinePointerInfo(OrigArg, 4 * i), false, false, 0);
2919     MemOps.push_back(Store);
2920     FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
2921   }
2922
2923   if (!MemOps.empty())
2924     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2925   return FrameIndex;
2926 }
2927
2928 // Setup stack frame, the va_list pointer will start from.
2929 void
2930 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2931                                         SDLoc dl, SDValue &Chain,
2932                                         unsigned ArgOffset,
2933                                         unsigned TotalArgRegsSaveSize,
2934                                         bool ForceMutable) const {
2935   MachineFunction &MF = DAG.getMachineFunction();
2936   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2937
2938   // Try to store any remaining integer argument regs
2939   // to their spots on the stack so that they may be loaded by deferencing
2940   // the result of va_next.
2941   // If there is no regs to be stored, just point address after last
2942   // argument passed via stack.
2943   int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
2944                                   CCInfo.getInRegsParamsCount(),
2945                                   CCInfo.getNextStackOffset(), 4);
2946   AFI->setVarArgsFrameIndex(FrameIndex);
2947 }
2948
2949 SDValue
2950 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2951                                         CallingConv::ID CallConv, bool isVarArg,
2952                                         const SmallVectorImpl<ISD::InputArg>
2953                                           &Ins,
2954                                         SDLoc dl, SelectionDAG &DAG,
2955                                         SmallVectorImpl<SDValue> &InVals)
2956                                           const {
2957   MachineFunction &MF = DAG.getMachineFunction();
2958   MachineFrameInfo *MFI = MF.getFrameInfo();
2959
2960   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2961
2962   // Assign locations to all of the incoming arguments.
2963   SmallVector<CCValAssign, 16> ArgLocs;
2964   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2965                     *DAG.getContext(), Prologue);
2966   CCInfo.AnalyzeFormalArguments(Ins,
2967                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2968                                                   isVarArg));
2969
2970   SmallVector<SDValue, 16> ArgValues;
2971   SDValue ArgValue;
2972   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2973   unsigned CurArgIdx = 0;
2974
2975   // Initially ArgRegsSaveSize is zero.
2976   // Then we increase this value each time we meet byval parameter.
2977   // We also increase this value in case of varargs function.
2978   AFI->setArgRegsSaveSize(0);
2979
2980   // Calculate the amount of stack space that we need to allocate to store
2981   // byval and variadic arguments that are passed in registers.
2982   // We need to know this before we allocate the first byval or variadic
2983   // argument, as they will be allocated a stack slot below the CFA (Canonical
2984   // Frame Address, the stack pointer at entry to the function).
2985   unsigned ArgRegBegin = ARM::R4;
2986   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2987     if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
2988       break;
2989
2990     CCValAssign &VA = ArgLocs[i];
2991     unsigned Index = VA.getValNo();
2992     ISD::ArgFlagsTy Flags = Ins[Index].Flags;
2993     if (!Flags.isByVal())
2994       continue;
2995
2996     assert(VA.isMemLoc() && "unexpected byval pointer in reg");
2997     unsigned RBegin, REnd;
2998     CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
2999     ArgRegBegin = std::min(ArgRegBegin, RBegin);
3000
3001     CCInfo.nextInRegsParam();
3002   }
3003   CCInfo.rewindByValRegsInfo();
3004
3005   int lastInsIndex = -1;
3006   if (isVarArg && MFI->hasVAStart()) {
3007     unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3008     if (RegIdx != array_lengthof(GPRArgRegs))
3009       ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3010   }
3011
3012   unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3013   AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3014   auto PtrVT = getPointerTy(DAG.getDataLayout());
3015
3016   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3017     CCValAssign &VA = ArgLocs[i];
3018     if (Ins[VA.getValNo()].isOrigArg()) {
3019       std::advance(CurOrigArg,
3020                    Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3021       CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3022     }
3023     // Arguments stored in registers.
3024     if (VA.isRegLoc()) {
3025       EVT RegVT = VA.getLocVT();
3026
3027       if (VA.needsCustom()) {
3028         // f64 and vector types are split up into multiple registers or
3029         // combinations of registers and stack slots.
3030         if (VA.getLocVT() == MVT::v2f64) {
3031           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3032                                                    Chain, DAG, dl);
3033           VA = ArgLocs[++i]; // skip ahead to next loc
3034           SDValue ArgValue2;
3035           if (VA.isMemLoc()) {
3036             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3037             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3038             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3039                                     MachinePointerInfo::getFixedStack(FI),
3040                                     false, false, false, 0);
3041           } else {
3042             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3043                                              Chain, DAG, dl);
3044           }
3045           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3046           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3047                                  ArgValue, ArgValue1,
3048                                  DAG.getIntPtrConstant(0, dl));
3049           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3050                                  ArgValue, ArgValue2,
3051                                  DAG.getIntPtrConstant(1, dl));
3052         } else
3053           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3054
3055       } else {
3056         const TargetRegisterClass *RC;
3057
3058         if (RegVT == MVT::f32)
3059           RC = &ARM::SPRRegClass;
3060         else if (RegVT == MVT::f64)
3061           RC = &ARM::DPRRegClass;
3062         else if (RegVT == MVT::v2f64)
3063           RC = &ARM::QPRRegClass;
3064         else if (RegVT == MVT::i32)
3065           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3066                                            : &ARM::GPRRegClass;
3067         else
3068           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3069
3070         // Transform the arguments in physical registers into virtual ones.
3071         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3072         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3073       }
3074
3075       // If this is an 8 or 16-bit value, it is really passed promoted
3076       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3077       // truncate to the right size.
3078       switch (VA.getLocInfo()) {
3079       default: llvm_unreachable("Unknown loc info!");
3080       case CCValAssign::Full: break;
3081       case CCValAssign::BCvt:
3082         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3083         break;
3084       case CCValAssign::SExt:
3085         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3086                                DAG.getValueType(VA.getValVT()));
3087         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3088         break;
3089       case CCValAssign::ZExt:
3090         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3091                                DAG.getValueType(VA.getValVT()));
3092         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3093         break;
3094       }
3095
3096       InVals.push_back(ArgValue);
3097
3098     } else { // VA.isRegLoc()
3099
3100       // sanity check
3101       assert(VA.isMemLoc());
3102       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3103
3104       int index = VA.getValNo();
3105
3106       // Some Ins[] entries become multiple ArgLoc[] entries.
3107       // Process them only once.
3108       if (index != lastInsIndex)
3109         {
3110           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3111           // FIXME: For now, all byval parameter objects are marked mutable.
3112           // This can be changed with more analysis.
3113           // In case of tail call optimization mark all arguments mutable.
3114           // Since they could be overwritten by lowering of arguments in case of
3115           // a tail call.
3116           if (Flags.isByVal()) {
3117             assert(Ins[index].isOrigArg() &&
3118                    "Byval arguments cannot be implicit");
3119             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3120
3121             int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, CurOrigArg,
3122                                             CurByValIndex, VA.getLocMemOffset(),
3123                                             Flags.getByValSize());
3124             InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
3125             CCInfo.nextInRegsParam();
3126           } else {
3127             unsigned FIOffset = VA.getLocMemOffset();
3128             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3129                                             FIOffset, true);
3130
3131             // Create load nodes to retrieve arguments from the stack.
3132             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3133             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3134                                          MachinePointerInfo::getFixedStack(FI),
3135                                          false, false, false, 0));
3136           }
3137           lastInsIndex = index;
3138         }
3139     }
3140   }
3141
3142   // varargs
3143   if (isVarArg && MFI->hasVAStart())
3144     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3145                          CCInfo.getNextStackOffset(),
3146                          TotalArgRegsSaveSize);
3147
3148   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3149
3150   return Chain;
3151 }
3152
3153 /// isFloatingPointZero - Return true if this is +0.0.
3154 static bool isFloatingPointZero(SDValue Op) {
3155   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3156     return CFP->getValueAPF().isPosZero();
3157   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3158     // Maybe this has already been legalized into the constant pool?
3159     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3160       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3161       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3162         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3163           return CFP->getValueAPF().isPosZero();
3164     }
3165   } else if (Op->getOpcode() == ISD::BITCAST &&
3166              Op->getValueType(0) == MVT::f64) {
3167     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3168     // created by LowerConstantFP().
3169     SDValue BitcastOp = Op->getOperand(0);
3170     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM) {
3171       SDValue MoveOp = BitcastOp->getOperand(0);
3172       if (MoveOp->getOpcode() == ISD::TargetConstant &&
3173           cast<ConstantSDNode>(MoveOp)->getZExtValue() == 0) {
3174         return true;
3175       }
3176     }
3177   }
3178   return false;
3179 }
3180
3181 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3182 /// the given operands.
3183 SDValue
3184 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3185                              SDValue &ARMcc, SelectionDAG &DAG,
3186                              SDLoc dl) const {
3187   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3188     unsigned C = RHSC->getZExtValue();
3189     if (!isLegalICmpImmediate(C)) {
3190       // Constant does not fit, try adjusting it by one?
3191       switch (CC) {
3192       default: break;
3193       case ISD::SETLT:
3194       case ISD::SETGE:
3195         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3196           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3197           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3198         }
3199         break;
3200       case ISD::SETULT:
3201       case ISD::SETUGE:
3202         if (C != 0 && isLegalICmpImmediate(C-1)) {
3203           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3204           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3205         }
3206         break;
3207       case ISD::SETLE:
3208       case ISD::SETGT:
3209         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3210           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3211           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3212         }
3213         break;
3214       case ISD::SETULE:
3215       case ISD::SETUGT:
3216         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3217           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3218           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3219         }
3220         break;
3221       }
3222     }
3223   }
3224
3225   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3226   ARMISD::NodeType CompareType;
3227   switch (CondCode) {
3228   default:
3229     CompareType = ARMISD::CMP;
3230     break;
3231   case ARMCC::EQ:
3232   case ARMCC::NE:
3233     // Uses only Z Flag
3234     CompareType = ARMISD::CMPZ;
3235     break;
3236   }
3237   ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3238   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3239 }
3240
3241 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3242 SDValue
3243 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3244                              SDLoc dl) const {
3245   assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3246   SDValue Cmp;
3247   if (!isFloatingPointZero(RHS))
3248     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3249   else
3250     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3251   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3252 }
3253
3254 /// duplicateCmp - Glue values can have only one use, so this function
3255 /// duplicates a comparison node.
3256 SDValue
3257 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3258   unsigned Opc = Cmp.getOpcode();
3259   SDLoc DL(Cmp);
3260   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3261     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3262
3263   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3264   Cmp = Cmp.getOperand(0);
3265   Opc = Cmp.getOpcode();
3266   if (Opc == ARMISD::CMPFP)
3267     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3268   else {
3269     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3270     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3271   }
3272   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3273 }
3274
3275 std::pair<SDValue, SDValue>
3276 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3277                                  SDValue &ARMcc) const {
3278   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3279
3280   SDValue Value, OverflowCmp;
3281   SDValue LHS = Op.getOperand(0);
3282   SDValue RHS = Op.getOperand(1);
3283   SDLoc dl(Op);
3284
3285   // FIXME: We are currently always generating CMPs because we don't support
3286   // generating CMN through the backend. This is not as good as the natural
3287   // CMP case because it causes a register dependency and cannot be folded
3288   // later.
3289
3290   switch (Op.getOpcode()) {
3291   default:
3292     llvm_unreachable("Unknown overflow instruction!");
3293   case ISD::SADDO:
3294     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3295     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3296     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3297     break;
3298   case ISD::UADDO:
3299     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3300     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3301     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3302     break;
3303   case ISD::SSUBO:
3304     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3305     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3306     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3307     break;
3308   case ISD::USUBO:
3309     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3310     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3311     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3312     break;
3313   } // switch (...)
3314
3315   return std::make_pair(Value, OverflowCmp);
3316 }
3317
3318
3319 SDValue
3320 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3321   // Let legalize expand this if it isn't a legal type yet.
3322   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3323     return SDValue();
3324
3325   SDValue Value, OverflowCmp;
3326   SDValue ARMcc;
3327   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3328   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3329   SDLoc dl(Op);
3330   // We use 0 and 1 as false and true values.
3331   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3332   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3333   EVT VT = Op.getValueType();
3334
3335   SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
3336                                  ARMcc, CCR, OverflowCmp);
3337
3338   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3339   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
3340 }
3341
3342
3343 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3344   SDValue Cond = Op.getOperand(0);
3345   SDValue SelectTrue = Op.getOperand(1);
3346   SDValue SelectFalse = Op.getOperand(2);
3347   SDLoc dl(Op);
3348   unsigned Opc = Cond.getOpcode();
3349
3350   if (Cond.getResNo() == 1 &&
3351       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3352        Opc == ISD::USUBO)) {
3353     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3354       return SDValue();
3355
3356     SDValue Value, OverflowCmp;
3357     SDValue ARMcc;
3358     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3359     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3360     EVT VT = Op.getValueType();
3361
3362     return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
3363                    OverflowCmp, DAG);
3364   }
3365
3366   // Convert:
3367   //
3368   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3369   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3370   //
3371   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3372     const ConstantSDNode *CMOVTrue =
3373       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3374     const ConstantSDNode *CMOVFalse =
3375       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3376
3377     if (CMOVTrue && CMOVFalse) {
3378       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3379       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3380
3381       SDValue True;
3382       SDValue False;
3383       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3384         True = SelectTrue;
3385         False = SelectFalse;
3386       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3387         True = SelectFalse;
3388         False = SelectTrue;
3389       }
3390
3391       if (True.getNode() && False.getNode()) {
3392         EVT VT = Op.getValueType();
3393         SDValue ARMcc = Cond.getOperand(2);
3394         SDValue CCR = Cond.getOperand(3);
3395         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3396         assert(True.getValueType() == VT);
3397         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3398       }
3399     }
3400   }
3401
3402   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3403   // undefined bits before doing a full-word comparison with zero.
3404   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3405                      DAG.getConstant(1, dl, Cond.getValueType()));
3406
3407   return DAG.getSelectCC(dl, Cond,
3408                          DAG.getConstant(0, dl, Cond.getValueType()),
3409                          SelectTrue, SelectFalse, ISD::SETNE);
3410 }
3411
3412 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3413                                  bool &swpCmpOps, bool &swpVselOps) {
3414   // Start by selecting the GE condition code for opcodes that return true for
3415   // 'equality'
3416   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3417       CC == ISD::SETULE)
3418     CondCode = ARMCC::GE;
3419
3420   // and GT for opcodes that return false for 'equality'.
3421   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3422            CC == ISD::SETULT)
3423     CondCode = ARMCC::GT;
3424
3425   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3426   // to swap the compare operands.
3427   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3428       CC == ISD::SETULT)
3429     swpCmpOps = true;
3430
3431   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3432   // If we have an unordered opcode, we need to swap the operands to the VSEL
3433   // instruction (effectively negating the condition).
3434   //
3435   // This also has the effect of swapping which one of 'less' or 'greater'
3436   // returns true, so we also swap the compare operands. It also switches
3437   // whether we return true for 'equality', so we compensate by picking the
3438   // opposite condition code to our original choice.
3439   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3440       CC == ISD::SETUGT) {
3441     swpCmpOps = !swpCmpOps;
3442     swpVselOps = !swpVselOps;
3443     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3444   }
3445
3446   // 'ordered' is 'anything but unordered', so use the VS condition code and
3447   // swap the VSEL operands.
3448   if (CC == ISD::SETO) {
3449     CondCode = ARMCC::VS;
3450     swpVselOps = true;
3451   }
3452
3453   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3454   // code and swap the VSEL operands.
3455   if (CC == ISD::SETUNE) {
3456     CondCode = ARMCC::EQ;
3457     swpVselOps = true;
3458   }
3459 }
3460
3461 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3462                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3463                                    SDValue Cmp, SelectionDAG &DAG) const {
3464   if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3465     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3466                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3467     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3468                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3469
3470     SDValue TrueLow = TrueVal.getValue(0);
3471     SDValue TrueHigh = TrueVal.getValue(1);
3472     SDValue FalseLow = FalseVal.getValue(0);
3473     SDValue FalseHigh = FalseVal.getValue(1);
3474
3475     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3476                               ARMcc, CCR, Cmp);
3477     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3478                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
3479
3480     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3481   } else {
3482     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3483                        Cmp);
3484   }
3485 }
3486
3487 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3488   EVT VT = Op.getValueType();
3489   SDValue LHS = Op.getOperand(0);
3490   SDValue RHS = Op.getOperand(1);
3491   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3492   SDValue TrueVal = Op.getOperand(2);
3493   SDValue FalseVal = Op.getOperand(3);
3494   SDLoc dl(Op);
3495
3496   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3497     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3498                                                     dl);
3499
3500     // If softenSetCCOperands only returned one value, we should compare it to
3501     // zero.
3502     if (!RHS.getNode()) {
3503       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3504       CC = ISD::SETNE;
3505     }
3506   }
3507
3508   if (LHS.getValueType() == MVT::i32) {
3509     // Try to generate VSEL on ARMv8.
3510     // The VSEL instruction can't use all the usual ARM condition
3511     // codes: it only has two bits to select the condition code, so it's
3512     // constrained to use only GE, GT, VS and EQ.
3513     //
3514     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3515     // swap the operands of the previous compare instruction (effectively
3516     // inverting the compare condition, swapping 'less' and 'greater') and
3517     // sometimes need to swap the operands to the VSEL (which inverts the
3518     // condition in the sense of firing whenever the previous condition didn't)
3519     if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3520                                     TrueVal.getValueType() == MVT::f64)) {
3521       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3522       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3523           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3524         CC = ISD::getSetCCInverse(CC, true);
3525         std::swap(TrueVal, FalseVal);
3526       }
3527     }
3528
3529     SDValue ARMcc;
3530     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3531     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3532     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3533   }
3534
3535   ARMCC::CondCodes CondCode, CondCode2;
3536   FPCCToARMCC(CC, CondCode, CondCode2);
3537
3538   // Try to generate VMAXNM/VMINNM on ARMv8.
3539   if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3540                                   TrueVal.getValueType() == MVT::f64)) {
3541     // We can use VMAXNM/VMINNM for a compare followed by a select with the
3542     // same operands, as follows:
3543     //   c = fcmp [?gt, ?ge, ?lt, ?le] a, b
3544     //   select c, a, b
3545     // In NoNaNsFPMath the CC will have been changed from, e.g., 'ogt' to 'gt'.
3546     bool swapSides = false;
3547     if (!getTargetMachine().Options.NoNaNsFPMath) {
3548       // transformability may depend on which way around we compare
3549       switch (CC) {
3550       default:
3551         break;
3552       case ISD::SETOGT:
3553       case ISD::SETOGE:
3554       case ISD::SETOLT:
3555       case ISD::SETOLE:
3556         // the non-NaN should be RHS
3557         swapSides = DAG.isKnownNeverNaN(LHS) && !DAG.isKnownNeverNaN(RHS);
3558         break;
3559       case ISD::SETUGT:
3560       case ISD::SETUGE:
3561       case ISD::SETULT:
3562       case ISD::SETULE:
3563         // the non-NaN should be LHS
3564         swapSides = DAG.isKnownNeverNaN(RHS) && !DAG.isKnownNeverNaN(LHS);
3565         break;
3566       }
3567     }
3568     swapSides = swapSides || (LHS == FalseVal && RHS == TrueVal);
3569     if (swapSides) {
3570       CC = ISD::getSetCCSwappedOperands(CC);
3571       std::swap(LHS, RHS);
3572     }
3573     if (LHS == TrueVal && RHS == FalseVal) {
3574       bool canTransform = true;
3575       // FIXME: FastMathFlags::noSignedZeros() doesn't appear reachable from here
3576       if (!getTargetMachine().Options.UnsafeFPMath &&
3577           !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
3578         const ConstantFPSDNode *Zero;
3579         switch (CC) {
3580         default:
3581           break;
3582         case ISD::SETOGT:
3583         case ISD::SETUGT:
3584         case ISD::SETGT:
3585           // RHS must not be -0
3586           canTransform = (Zero = dyn_cast<ConstantFPSDNode>(RHS)) &&
3587                          !Zero->isNegative();
3588           break;
3589         case ISD::SETOGE:
3590         case ISD::SETUGE:
3591         case ISD::SETGE:
3592           // LHS must not be -0
3593           canTransform = (Zero = dyn_cast<ConstantFPSDNode>(LHS)) &&
3594                          !Zero->isNegative();
3595           break;
3596         case ISD::SETOLT:
3597         case ISD::SETULT:
3598         case ISD::SETLT:
3599           // RHS must not be +0
3600           canTransform = (Zero = dyn_cast<ConstantFPSDNode>(RHS)) &&
3601                           Zero->isNegative();
3602           break;
3603         case ISD::SETOLE:
3604         case ISD::SETULE:
3605         case ISD::SETLE:
3606           // LHS must not be +0
3607           canTransform = (Zero = dyn_cast<ConstantFPSDNode>(LHS)) &&
3608                           Zero->isNegative();
3609           break;
3610         }
3611       }
3612       if (canTransform) {
3613         // Note: If one of the elements in a pair is a number and the other
3614         // element is NaN, the corresponding result element is the number.
3615         // This is consistent with the IEEE 754-2008 standard.
3616         // Therefore, a > b ? a : b <=> vmax(a,b), if b is constant and a is NaN
3617         switch (CC) {
3618         default:
3619           break;
3620         case ISD::SETOGT:
3621         case ISD::SETOGE:
3622           if (!DAG.isKnownNeverNaN(RHS))
3623             break;
3624           return DAG.getNode(ARMISD::VMAXNM, dl, VT, LHS, RHS);
3625         case ISD::SETUGT:
3626         case ISD::SETUGE:
3627           if (!DAG.isKnownNeverNaN(LHS))
3628             break;
3629         case ISD::SETGT:
3630         case ISD::SETGE:
3631           return DAG.getNode(ARMISD::VMAXNM, dl, VT, LHS, RHS);
3632         case ISD::SETOLT:
3633         case ISD::SETOLE:
3634           if (!DAG.isKnownNeverNaN(RHS))
3635             break;
3636           return DAG.getNode(ARMISD::VMINNM, dl, VT, LHS, RHS);
3637         case ISD::SETULT:
3638         case ISD::SETULE:
3639           if (!DAG.isKnownNeverNaN(LHS))
3640             break;
3641         case ISD::SETLT:
3642         case ISD::SETLE:
3643           return DAG.getNode(ARMISD::VMINNM, dl, VT, LHS, RHS);
3644         }
3645       }
3646     }
3647
3648     bool swpCmpOps = false;
3649     bool swpVselOps = false;
3650     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3651
3652     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3653         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3654       if (swpCmpOps)
3655         std::swap(LHS, RHS);
3656       if (swpVselOps)
3657         std::swap(TrueVal, FalseVal);
3658     }
3659   }
3660
3661   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3662   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3663   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3664   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3665   if (CondCode2 != ARMCC::AL) {
3666     SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
3667     // FIXME: Needs another CMP because flag can have but one use.
3668     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3669     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3670   }
3671   return Result;
3672 }
3673
3674 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3675 /// to morph to an integer compare sequence.
3676 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3677                            const ARMSubtarget *Subtarget) {
3678   SDNode *N = Op.getNode();
3679   if (!N->hasOneUse())
3680     // Otherwise it requires moving the value from fp to integer registers.
3681     return false;
3682   if (!N->getNumValues())
3683     return false;
3684   EVT VT = Op.getValueType();
3685   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3686     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3687     // vmrs are very slow, e.g. cortex-a8.
3688     return false;
3689
3690   if (isFloatingPointZero(Op)) {
3691     SeenZero = true;
3692     return true;
3693   }
3694   return ISD::isNormalLoad(N);
3695 }
3696
3697 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3698   if (isFloatingPointZero(Op))
3699     return DAG.getConstant(0, SDLoc(Op), MVT::i32);
3700
3701   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3702     return DAG.getLoad(MVT::i32, SDLoc(Op),
3703                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3704                        Ld->isVolatile(), Ld->isNonTemporal(),
3705                        Ld->isInvariant(), Ld->getAlignment());
3706
3707   llvm_unreachable("Unknown VFP cmp argument!");
3708 }
3709
3710 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3711                            SDValue &RetVal1, SDValue &RetVal2) {
3712   SDLoc dl(Op);
3713
3714   if (isFloatingPointZero(Op)) {
3715     RetVal1 = DAG.getConstant(0, dl, MVT::i32);
3716     RetVal2 = DAG.getConstant(0, dl, MVT::i32);
3717     return;
3718   }
3719
3720   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3721     SDValue Ptr = Ld->getBasePtr();
3722     RetVal1 = DAG.getLoad(MVT::i32, dl,
3723                           Ld->getChain(), Ptr,
3724                           Ld->getPointerInfo(),
3725                           Ld->isVolatile(), Ld->isNonTemporal(),
3726                           Ld->isInvariant(), Ld->getAlignment());
3727
3728     EVT PtrType = Ptr.getValueType();
3729     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3730     SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
3731                                  PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
3732     RetVal2 = DAG.getLoad(MVT::i32, dl,
3733                           Ld->getChain(), NewPtr,
3734                           Ld->getPointerInfo().getWithOffset(4),
3735                           Ld->isVolatile(), Ld->isNonTemporal(),
3736                           Ld->isInvariant(), NewAlign);
3737     return;
3738   }
3739
3740   llvm_unreachable("Unknown VFP cmp argument!");
3741 }
3742
3743 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3744 /// f32 and even f64 comparisons to integer ones.
3745 SDValue
3746 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3747   SDValue Chain = Op.getOperand(0);
3748   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3749   SDValue LHS = Op.getOperand(2);
3750   SDValue RHS = Op.getOperand(3);
3751   SDValue Dest = Op.getOperand(4);
3752   SDLoc dl(Op);
3753
3754   bool LHSSeenZero = false;
3755   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3756   bool RHSSeenZero = false;
3757   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3758   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3759     // If unsafe fp math optimization is enabled and there are no other uses of
3760     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3761     // to an integer comparison.
3762     if (CC == ISD::SETOEQ)
3763       CC = ISD::SETEQ;
3764     else if (CC == ISD::SETUNE)
3765       CC = ISD::SETNE;
3766
3767     SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
3768     SDValue ARMcc;
3769     if (LHS.getValueType() == MVT::f32) {
3770       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3771                         bitcastf32Toi32(LHS, DAG), Mask);
3772       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3773                         bitcastf32Toi32(RHS, DAG), Mask);
3774       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3775       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3776       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3777                          Chain, Dest, ARMcc, CCR, Cmp);
3778     }
3779
3780     SDValue LHS1, LHS2;
3781     SDValue RHS1, RHS2;
3782     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3783     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3784     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3785     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3786     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3787     ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3788     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3789     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3790     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3791   }
3792
3793   return SDValue();
3794 }
3795
3796 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3797   SDValue Chain = Op.getOperand(0);
3798   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3799   SDValue LHS = Op.getOperand(2);
3800   SDValue RHS = Op.getOperand(3);
3801   SDValue Dest = Op.getOperand(4);
3802   SDLoc dl(Op);
3803
3804   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3805     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3806                                                     dl);
3807
3808     // If softenSetCCOperands only returned one value, we should compare it to
3809     // zero.
3810     if (!RHS.getNode()) {
3811       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3812       CC = ISD::SETNE;
3813     }
3814   }
3815
3816   if (LHS.getValueType() == MVT::i32) {
3817     SDValue ARMcc;
3818     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3819     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3820     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3821                        Chain, Dest, ARMcc, CCR, Cmp);
3822   }
3823
3824   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3825
3826   if (getTargetMachine().Options.UnsafeFPMath &&
3827       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3828        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3829     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3830     if (Result.getNode())
3831       return Result;
3832   }
3833
3834   ARMCC::CondCodes CondCode, CondCode2;
3835   FPCCToARMCC(CC, CondCode, CondCode2);
3836
3837   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3838   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3839   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3840   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3841   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3842   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3843   if (CondCode2 != ARMCC::AL) {
3844     ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
3845     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3846     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3847   }
3848   return Res;
3849 }
3850
3851 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3852   SDValue Chain = Op.getOperand(0);
3853   SDValue Table = Op.getOperand(1);
3854   SDValue Index = Op.getOperand(2);
3855   SDLoc dl(Op);
3856
3857   EVT PTy = getPointerTy(DAG.getDataLayout());
3858   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3859   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3860   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
3861   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
3862   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3863   if (Subtarget->isThumb2()) {
3864     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3865     // which does another jump to the destination. This also makes it easier
3866     // to translate it to TBB / TBH later.
3867     // FIXME: This might not work if the function is extremely large.
3868     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3869                        Addr, Op.getOperand(2), JTI);
3870   }
3871   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3872     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3873                        MachinePointerInfo::getJumpTable(),
3874                        false, false, false, 0);
3875     Chain = Addr.getValue(1);
3876     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3877     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3878   } else {
3879     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3880                        MachinePointerInfo::getJumpTable(),
3881                        false, false, false, 0);
3882     Chain = Addr.getValue(1);
3883     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3884   }
3885 }
3886
3887 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3888   EVT VT = Op.getValueType();
3889   SDLoc dl(Op);
3890
3891   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3892     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3893       return Op;
3894     return DAG.UnrollVectorOp(Op.getNode());
3895   }
3896
3897   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3898          "Invalid type for custom lowering!");
3899   if (VT != MVT::v4i16)
3900     return DAG.UnrollVectorOp(Op.getNode());
3901
3902   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3903   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3904 }
3905
3906 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3907   EVT VT = Op.getValueType();
3908   if (VT.isVector())
3909     return LowerVectorFP_TO_INT(Op, DAG);
3910   if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3911     RTLIB::Libcall LC;
3912     if (Op.getOpcode() == ISD::FP_TO_SINT)
3913       LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
3914                               Op.getValueType());
3915     else
3916       LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
3917                               Op.getValueType());
3918     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3919                        /*isSigned*/ false, SDLoc(Op)).first;
3920   }
3921
3922   return Op;
3923 }
3924
3925 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3926   EVT VT = Op.getValueType();
3927   SDLoc dl(Op);
3928
3929   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3930     if (VT.getVectorElementType() == MVT::f32)
3931       return Op;
3932     return DAG.UnrollVectorOp(Op.getNode());
3933   }
3934
3935   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3936          "Invalid type for custom lowering!");
3937   if (VT != MVT::v4f32)
3938     return DAG.UnrollVectorOp(Op.getNode());
3939
3940   unsigned CastOpc;
3941   unsigned Opc;
3942   switch (Op.getOpcode()) {
3943   default: llvm_unreachable("Invalid opcode!");
3944   case ISD::SINT_TO_FP:
3945     CastOpc = ISD::SIGN_EXTEND;
3946     Opc = ISD::SINT_TO_FP;
3947     break;
3948   case ISD::UINT_TO_FP:
3949     CastOpc = ISD::ZERO_EXTEND;
3950     Opc = ISD::UINT_TO_FP;
3951     break;
3952   }
3953
3954   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3955   return DAG.getNode(Opc, dl, VT, Op);
3956 }
3957
3958 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
3959   EVT VT = Op.getValueType();
3960   if (VT.isVector())
3961     return LowerVectorINT_TO_FP(Op, DAG);
3962   if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
3963     RTLIB::Libcall LC;
3964     if (Op.getOpcode() == ISD::SINT_TO_FP)
3965       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
3966                               Op.getValueType());
3967     else
3968       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
3969                               Op.getValueType());
3970     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3971                        /*isSigned*/ false, SDLoc(Op)).first;
3972   }
3973
3974   return Op;
3975 }
3976
3977 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3978   // Implement fcopysign with a fabs and a conditional fneg.
3979   SDValue Tmp0 = Op.getOperand(0);
3980   SDValue Tmp1 = Op.getOperand(1);
3981   SDLoc dl(Op);
3982   EVT VT = Op.getValueType();
3983   EVT SrcVT = Tmp1.getValueType();
3984   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3985     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3986   bool UseNEON = !InGPR && Subtarget->hasNEON();
3987
3988   if (UseNEON) {
3989     // Use VBSL to copy the sign bit.
3990     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3991     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3992                                DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
3993     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3994     if (VT == MVT::f64)
3995       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3996                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3997                          DAG.getConstant(32, dl, MVT::i32));
3998     else /*if (VT == MVT::f32)*/
3999       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
4000     if (SrcVT == MVT::f32) {
4001       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4002       if (VT == MVT::f64)
4003         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4004                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4005                            DAG.getConstant(32, dl, MVT::i32));
4006     } else if (VT == MVT::f32)
4007       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4008                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4009                          DAG.getConstant(32, dl, MVT::i32));
4010     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4011     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4012
4013     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4014                                             dl, MVT::i32);
4015     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4016     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4017                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4018
4019     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4020                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4021                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4022     if (VT == MVT::f32) {
4023       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4024       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4025                         DAG.getConstant(0, dl, MVT::i32));
4026     } else {
4027       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4028     }
4029
4030     return Res;
4031   }
4032
4033   // Bitcast operand 1 to i32.
4034   if (SrcVT == MVT::f64)
4035     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4036                        Tmp1).getValue(1);
4037   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4038
4039   // Or in the signbit with integer operations.
4040   SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
4041   SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4042   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4043   if (VT == MVT::f32) {
4044     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4045                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4046     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4047                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4048   }
4049
4050   // f64: Or the high part with signbit and then combine two parts.
4051   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4052                      Tmp0);
4053   SDValue Lo = Tmp0.getValue(0);
4054   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4055   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4056   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4057 }
4058
4059 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4060   MachineFunction &MF = DAG.getMachineFunction();
4061   MachineFrameInfo *MFI = MF.getFrameInfo();
4062   MFI->setReturnAddressIsTaken(true);
4063
4064   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4065     return SDValue();
4066
4067   EVT VT = Op.getValueType();
4068   SDLoc dl(Op);
4069   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4070   if (Depth) {
4071     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4072     SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
4073     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4074                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4075                        MachinePointerInfo(), false, false, false, 0);
4076   }
4077
4078   // Return LR, which contains the return address. Mark it an implicit live-in.
4079   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4080   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4081 }
4082
4083 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4084   const ARMBaseRegisterInfo &ARI =
4085     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4086   MachineFunction &MF = DAG.getMachineFunction();
4087   MachineFrameInfo *MFI = MF.getFrameInfo();
4088   MFI->setFrameAddressIsTaken(true);
4089
4090   EVT VT = Op.getValueType();
4091   SDLoc dl(Op);  // FIXME probably not meaningful
4092   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4093   unsigned FrameReg = ARI.getFrameRegister(MF);
4094   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4095   while (Depth--)
4096     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4097                             MachinePointerInfo(),
4098                             false, false, false, 0);
4099   return FrameAddr;
4100 }
4101
4102 // FIXME? Maybe this could be a TableGen attribute on some registers and
4103 // this table could be generated automatically from RegInfo.
4104 unsigned ARMTargetLowering::getRegisterByName(const char* RegName,
4105                                               EVT VT) const {
4106   unsigned Reg = StringSwitch<unsigned>(RegName)
4107                        .Case("sp", ARM::SP)
4108                        .Default(0);
4109   if (Reg)
4110     return Reg;
4111   report_fatal_error(Twine("Invalid register name \""
4112                               + StringRef(RegName)  + "\"."));
4113 }
4114
4115 // Result is 64 bit value so split into two 32 bit values and return as a
4116 // pair of values.
4117 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
4118                                 SelectionDAG &DAG) {
4119   SDLoc DL(N);
4120
4121   // This function is only supposed to be called for i64 type destination.
4122   assert(N->getValueType(0) == MVT::i64
4123           && "ExpandREAD_REGISTER called for non-i64 type result.");
4124
4125   SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
4126                              DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
4127                              N->getOperand(0),
4128                              N->getOperand(1));
4129
4130   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
4131                     Read.getValue(1)));
4132   Results.push_back(Read.getOperand(0));
4133 }
4134
4135 /// ExpandBITCAST - If the target supports VFP, this function is called to
4136 /// expand a bit convert where either the source or destination type is i64 to
4137 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
4138 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4139 /// vectors), since the legalizer won't know what to do with that.
4140 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4141   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4142   SDLoc dl(N);
4143   SDValue Op = N->getOperand(0);
4144
4145   // This function is only supposed to be called for i64 types, either as the
4146   // source or destination of the bit convert.
4147   EVT SrcVT = Op.getValueType();
4148   EVT DstVT = N->getValueType(0);
4149   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4150          "ExpandBITCAST called for non-i64 type");
4151
4152   // Turn i64->f64 into VMOVDRR.
4153   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4154     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4155                              DAG.getConstant(0, dl, MVT::i32));
4156     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4157                              DAG.getConstant(1, dl, MVT::i32));
4158     return DAG.getNode(ISD::BITCAST, dl, DstVT,
4159                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4160   }
4161
4162   // Turn f64->i64 into VMOVRRD.
4163   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4164     SDValue Cvt;
4165     if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
4166         SrcVT.getVectorNumElements() > 1)
4167       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4168                         DAG.getVTList(MVT::i32, MVT::i32),
4169                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4170     else
4171       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4172                         DAG.getVTList(MVT::i32, MVT::i32), Op);
4173     // Merge the pieces into a single i64 value.
4174     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4175   }
4176
4177   return SDValue();
4178 }
4179
4180 /// getZeroVector - Returns a vector of specified type with all zero elements.
4181 /// Zero vectors are used to represent vector negation and in those cases
4182 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
4183 /// not support i64 elements, so sometimes the zero vectors will need to be
4184 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
4185 /// zero vector.
4186 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4187   assert(VT.isVector() && "Expected a vector type");
4188   // The canonical modified immediate encoding of a zero vector is....0!
4189   SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
4190   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4191   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4192   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4193 }
4194
4195 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4196 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4197 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4198                                                 SelectionDAG &DAG) const {
4199   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4200   EVT VT = Op.getValueType();
4201   unsigned VTBits = VT.getSizeInBits();
4202   SDLoc dl(Op);
4203   SDValue ShOpLo = Op.getOperand(0);
4204   SDValue ShOpHi = Op.getOperand(1);
4205   SDValue ShAmt  = Op.getOperand(2);
4206   SDValue ARMcc;
4207   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4208
4209   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4210
4211   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4212                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4213   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4214   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4215                                    DAG.getConstant(VTBits, dl, MVT::i32));
4216   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4217   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4218   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4219
4220   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4221   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4222                           ISD::SETGE, ARMcc, DAG, dl);
4223   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4224   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4225                            CCR, Cmp);
4226
4227   SDValue Ops[2] = { Lo, Hi };
4228   return DAG.getMergeValues(Ops, dl);
4229 }
4230
4231 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4232 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4233 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4234                                                SelectionDAG &DAG) const {
4235   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4236   EVT VT = Op.getValueType();
4237   unsigned VTBits = VT.getSizeInBits();
4238   SDLoc dl(Op);
4239   SDValue ShOpLo = Op.getOperand(0);
4240   SDValue ShOpHi = Op.getOperand(1);
4241   SDValue ShAmt  = Op.getOperand(2);
4242   SDValue ARMcc;
4243
4244   assert(Op.getOpcode() == ISD::SHL_PARTS);
4245   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4246                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4247   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4248   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4249                                    DAG.getConstant(VTBits, dl, MVT::i32));
4250   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4251   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4252
4253   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4254   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4255   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4256                           ISD::SETGE, ARMcc, DAG, dl);
4257   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4258   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4259                            CCR, Cmp);
4260
4261   SDValue Ops[2] = { Lo, Hi };
4262   return DAG.getMergeValues(Ops, dl);
4263 }
4264
4265 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4266                                             SelectionDAG &DAG) const {
4267   // The rounding mode is in bits 23:22 of the FPSCR.
4268   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4269   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4270   // so that the shift + and get folded into a bitfield extract.
4271   SDLoc dl(Op);
4272   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4273                               DAG.getConstant(Intrinsic::arm_get_fpscr, dl,
4274                                               MVT::i32));
4275   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4276                                   DAG.getConstant(1U << 22, dl, MVT::i32));
4277   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4278                               DAG.getConstant(22, dl, MVT::i32));
4279   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4280                      DAG.getConstant(3, dl, MVT::i32));
4281 }
4282
4283 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4284                          const ARMSubtarget *ST) {
4285   EVT VT = N->getValueType(0);
4286   SDLoc dl(N);
4287
4288   if (!ST->hasV6T2Ops())
4289     return SDValue();
4290
4291   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4292   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4293 }
4294
4295 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4296 /// for each 16-bit element from operand, repeated.  The basic idea is to
4297 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4298 ///
4299 /// Trace for v4i16:
4300 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
4301 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4302 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4303 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4304 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
4305 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
4306 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4307 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
4308 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4309   EVT VT = N->getValueType(0);
4310   SDLoc DL(N);
4311
4312   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4313   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4314   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4315   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4316   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4317   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4318 }
4319
4320 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4321 /// bit-count for each 16-bit element from the operand.  We need slightly
4322 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4323 /// 64/128-bit registers.
4324 ///
4325 /// Trace for v4i16:
4326 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
4327 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4328 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
4329 /// v4i16:Extracted = [k0    k1    k2    k3    ]
4330 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4331   EVT VT = N->getValueType(0);
4332   SDLoc DL(N);
4333
4334   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4335   if (VT.is64BitVector()) {
4336     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4337     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4338                        DAG.getIntPtrConstant(0, DL));
4339   } else {
4340     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4341                                     BitCounts, DAG.getIntPtrConstant(0, DL));
4342     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4343   }
4344 }
4345
4346 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4347 /// bit-count for each 32-bit element from the operand.  The idea here is
4348 /// to split the vector into 16-bit elements, leverage the 16-bit count
4349 /// routine, and then combine the results.
4350 ///
4351 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4352 /// input    = [v0    v1    ] (vi: 32-bit elements)
4353 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4354 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4355 /// vrev: N0 = [k1 k0 k3 k2 ]
4356 ///            [k0 k1 k2 k3 ]
4357 ///       N1 =+[k1 k0 k3 k2 ]
4358 ///            [k0 k2 k1 k3 ]
4359 ///       N2 =+[k1 k3 k0 k2 ]
4360 ///            [k0    k2    k1    k3    ]
4361 /// Extended =+[k1    k3    k0    k2    ]
4362 ///            [k0    k2    ]
4363 /// Extracted=+[k1    k3    ]
4364 ///
4365 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4366   EVT VT = N->getValueType(0);
4367   SDLoc DL(N);
4368
4369   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4370
4371   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4372   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4373   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4374   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4375   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4376
4377   if (VT.is64BitVector()) {
4378     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4379     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4380                        DAG.getIntPtrConstant(0, DL));
4381   } else {
4382     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4383                                     DAG.getIntPtrConstant(0, DL));
4384     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4385   }
4386 }
4387
4388 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4389                           const ARMSubtarget *ST) {
4390   EVT VT = N->getValueType(0);
4391
4392   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4393   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4394           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4395          "Unexpected type for custom ctpop lowering");
4396
4397   if (VT.getVectorElementType() == MVT::i32)
4398     return lowerCTPOP32BitElements(N, DAG);
4399   else
4400     return lowerCTPOP16BitElements(N, DAG);
4401 }
4402
4403 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4404                           const ARMSubtarget *ST) {
4405   EVT VT = N->getValueType(0);
4406   SDLoc dl(N);
4407
4408   if (!VT.isVector())
4409     return SDValue();
4410
4411   // Lower vector shifts on NEON to use VSHL.
4412   assert(ST->hasNEON() && "unexpected vector shift");
4413
4414   // Left shifts translate directly to the vshiftu intrinsic.
4415   if (N->getOpcode() == ISD::SHL)
4416     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4417                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
4418                                        MVT::i32),
4419                        N->getOperand(0), N->getOperand(1));
4420
4421   assert((N->getOpcode() == ISD::SRA ||
4422           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4423
4424   // NEON uses the same intrinsics for both left and right shifts.  For
4425   // right shifts, the shift amounts are negative, so negate the vector of
4426   // shift amounts.
4427   EVT ShiftVT = N->getOperand(1).getValueType();
4428   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4429                                      getZeroVector(ShiftVT, DAG, dl),
4430                                      N->getOperand(1));
4431   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4432                              Intrinsic::arm_neon_vshifts :
4433                              Intrinsic::arm_neon_vshiftu);
4434   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4435                      DAG.getConstant(vshiftInt, dl, MVT::i32),
4436                      N->getOperand(0), NegatedCount);
4437 }
4438
4439 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4440                                 const ARMSubtarget *ST) {
4441   EVT VT = N->getValueType(0);
4442   SDLoc dl(N);
4443
4444   // We can get here for a node like i32 = ISD::SHL i32, i64
4445   if (VT != MVT::i64)
4446     return SDValue();
4447
4448   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4449          "Unknown shift to lower!");
4450
4451   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4452   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4453       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4454     return SDValue();
4455
4456   // If we are in thumb mode, we don't have RRX.
4457   if (ST->isThumb1Only()) return SDValue();
4458
4459   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4460   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4461                            DAG.getConstant(0, dl, MVT::i32));
4462   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4463                            DAG.getConstant(1, dl, MVT::i32));
4464
4465   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4466   // captures the result into a carry flag.
4467   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4468   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4469
4470   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4471   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4472
4473   // Merge the pieces into a single i64 value.
4474  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4475 }
4476
4477 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4478   SDValue TmpOp0, TmpOp1;
4479   bool Invert = false;
4480   bool Swap = false;
4481   unsigned Opc = 0;
4482
4483   SDValue Op0 = Op.getOperand(0);
4484   SDValue Op1 = Op.getOperand(1);
4485   SDValue CC = Op.getOperand(2);
4486   EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
4487   EVT VT = Op.getValueType();
4488   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4489   SDLoc dl(Op);
4490
4491   if (Op1.getValueType().isFloatingPoint()) {
4492     switch (SetCCOpcode) {
4493     default: llvm_unreachable("Illegal FP comparison");
4494     case ISD::SETUNE:
4495     case ISD::SETNE:  Invert = true; // Fallthrough
4496     case ISD::SETOEQ:
4497     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4498     case ISD::SETOLT:
4499     case ISD::SETLT: Swap = true; // Fallthrough
4500     case ISD::SETOGT:
4501     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4502     case ISD::SETOLE:
4503     case ISD::SETLE:  Swap = true; // Fallthrough
4504     case ISD::SETOGE:
4505     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4506     case ISD::SETUGE: Swap = true; // Fallthrough
4507     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4508     case ISD::SETUGT: Swap = true; // Fallthrough
4509     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4510     case ISD::SETUEQ: Invert = true; // Fallthrough
4511     case ISD::SETONE:
4512       // Expand this to (OLT | OGT).
4513       TmpOp0 = Op0;
4514       TmpOp1 = Op1;
4515       Opc = ISD::OR;
4516       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4517       Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
4518       break;
4519     case ISD::SETUO: Invert = true; // Fallthrough
4520     case ISD::SETO:
4521       // Expand this to (OLT | OGE).
4522       TmpOp0 = Op0;
4523       TmpOp1 = Op1;
4524       Opc = ISD::OR;
4525       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4526       Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
4527       break;
4528     }
4529   } else {
4530     // Integer comparisons.
4531     switch (SetCCOpcode) {
4532     default: llvm_unreachable("Illegal integer comparison");
4533     case ISD::SETNE:  Invert = true;
4534     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4535     case ISD::SETLT:  Swap = true;
4536     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4537     case ISD::SETLE:  Swap = true;
4538     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4539     case ISD::SETULT: Swap = true;
4540     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4541     case ISD::SETULE: Swap = true;
4542     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4543     }
4544
4545     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4546     if (Opc == ARMISD::VCEQ) {
4547
4548       SDValue AndOp;
4549       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4550         AndOp = Op0;
4551       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4552         AndOp = Op1;
4553
4554       // Ignore bitconvert.
4555       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4556         AndOp = AndOp.getOperand(0);
4557
4558       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4559         Opc = ARMISD::VTST;
4560         Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
4561         Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
4562         Invert = !Invert;
4563       }
4564     }
4565   }
4566
4567   if (Swap)
4568     std::swap(Op0, Op1);
4569
4570   // If one of the operands is a constant vector zero, attempt to fold the
4571   // comparison to a specialized compare-against-zero form.
4572   SDValue SingleOp;
4573   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4574     SingleOp = Op0;
4575   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4576     if (Opc == ARMISD::VCGE)
4577       Opc = ARMISD::VCLEZ;
4578     else if (Opc == ARMISD::VCGT)
4579       Opc = ARMISD::VCLTZ;
4580     SingleOp = Op1;
4581   }
4582
4583   SDValue Result;
4584   if (SingleOp.getNode()) {
4585     switch (Opc) {
4586     case ARMISD::VCEQ:
4587       Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
4588     case ARMISD::VCGE:
4589       Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
4590     case ARMISD::VCLEZ:
4591       Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
4592     case ARMISD::VCGT:
4593       Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
4594     case ARMISD::VCLTZ:
4595       Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
4596     default:
4597       Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4598     }
4599   } else {
4600      Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4601   }
4602
4603   Result = DAG.getSExtOrTrunc(Result, dl, VT);
4604
4605   if (Invert)
4606     Result = DAG.getNOT(dl, Result, VT);
4607
4608   return Result;
4609 }
4610
4611 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4612 /// valid vector constant for a NEON instruction with a "modified immediate"
4613 /// operand (e.g., VMOV).  If so, return the encoded value.
4614 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4615                                  unsigned SplatBitSize, SelectionDAG &DAG,
4616                                  SDLoc dl, EVT &VT, bool is128Bits,
4617                                  NEONModImmType type) {
4618   unsigned OpCmode, Imm;
4619
4620   // SplatBitSize is set to the smallest size that splats the vector, so a
4621   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4622   // immediate instructions others than VMOV do not support the 8-bit encoding
4623   // of a zero vector, and the default encoding of zero is supposed to be the
4624   // 32-bit version.
4625   if (SplatBits == 0)
4626     SplatBitSize = 32;
4627
4628   switch (SplatBitSize) {
4629   case 8:
4630     if (type != VMOVModImm)
4631       return SDValue();
4632     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4633     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4634     OpCmode = 0xe;
4635     Imm = SplatBits;
4636     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4637     break;
4638
4639   case 16:
4640     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4641     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4642     if ((SplatBits & ~0xff) == 0) {
4643       // Value = 0x00nn: Op=x, Cmode=100x.
4644       OpCmode = 0x8;
4645       Imm = SplatBits;
4646       break;
4647     }
4648     if ((SplatBits & ~0xff00) == 0) {
4649       // Value = 0xnn00: Op=x, Cmode=101x.
4650       OpCmode = 0xa;
4651       Imm = SplatBits >> 8;
4652       break;
4653     }
4654     return SDValue();
4655
4656   case 32:
4657     // NEON's 32-bit VMOV supports splat values where:
4658     // * only one byte is nonzero, or
4659     // * the least significant byte is 0xff and the second byte is nonzero, or
4660     // * the least significant 2 bytes are 0xff and the third is nonzero.
4661     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4662     if ((SplatBits & ~0xff) == 0) {
4663       // Value = 0x000000nn: Op=x, Cmode=000x.
4664       OpCmode = 0;
4665       Imm = SplatBits;
4666       break;
4667     }
4668     if ((SplatBits & ~0xff00) == 0) {
4669       // Value = 0x0000nn00: Op=x, Cmode=001x.
4670       OpCmode = 0x2;
4671       Imm = SplatBits >> 8;
4672       break;
4673     }
4674     if ((SplatBits & ~0xff0000) == 0) {
4675       // Value = 0x00nn0000: Op=x, Cmode=010x.
4676       OpCmode = 0x4;
4677       Imm = SplatBits >> 16;
4678       break;
4679     }
4680     if ((SplatBits & ~0xff000000) == 0) {
4681       // Value = 0xnn000000: Op=x, Cmode=011x.
4682       OpCmode = 0x6;
4683       Imm = SplatBits >> 24;
4684       break;
4685     }
4686
4687     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4688     if (type == OtherModImm) return SDValue();
4689
4690     if ((SplatBits & ~0xffff) == 0 &&
4691         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4692       // Value = 0x0000nnff: Op=x, Cmode=1100.
4693       OpCmode = 0xc;
4694       Imm = SplatBits >> 8;
4695       break;
4696     }
4697
4698     if ((SplatBits & ~0xffffff) == 0 &&
4699         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4700       // Value = 0x00nnffff: Op=x, Cmode=1101.
4701       OpCmode = 0xd;
4702       Imm = SplatBits >> 16;
4703       break;
4704     }
4705
4706     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4707     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4708     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4709     // and fall through here to test for a valid 64-bit splat.  But, then the
4710     // caller would also need to check and handle the change in size.
4711     return SDValue();
4712
4713   case 64: {
4714     if (type != VMOVModImm)
4715       return SDValue();
4716     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4717     uint64_t BitMask = 0xff;
4718     uint64_t Val = 0;
4719     unsigned ImmMask = 1;
4720     Imm = 0;
4721     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4722       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4723         Val |= BitMask;
4724         Imm |= ImmMask;
4725       } else if ((SplatBits & BitMask) != 0) {
4726         return SDValue();
4727       }
4728       BitMask <<= 8;
4729       ImmMask <<= 1;
4730     }
4731
4732     if (DAG.getDataLayout().isBigEndian())
4733       // swap higher and lower 32 bit word
4734       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4735
4736     // Op=1, Cmode=1110.
4737     OpCmode = 0x1e;
4738     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4739     break;
4740   }
4741
4742   default:
4743     llvm_unreachable("unexpected size for isNEONModifiedImm");
4744   }
4745
4746   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4747   return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
4748 }
4749
4750 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4751                                            const ARMSubtarget *ST) const {
4752   if (!ST->hasVFP3())
4753     return SDValue();
4754
4755   bool IsDouble = Op.getValueType() == MVT::f64;
4756   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4757
4758   // Use the default (constant pool) lowering for double constants when we have
4759   // an SP-only FPU
4760   if (IsDouble && Subtarget->isFPOnlySP())
4761     return SDValue();
4762
4763   // Try splatting with a VMOV.f32...
4764   APFloat FPVal = CFP->getValueAPF();
4765   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4766
4767   if (ImmVal != -1) {
4768     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4769       // We have code in place to select a valid ConstantFP already, no need to
4770       // do any mangling.
4771       return Op;
4772     }
4773
4774     // It's a float and we are trying to use NEON operations where
4775     // possible. Lower it to a splat followed by an extract.
4776     SDLoc DL(Op);
4777     SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
4778     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4779                                       NewVal);
4780     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4781                        DAG.getConstant(0, DL, MVT::i32));
4782   }
4783
4784   // The rest of our options are NEON only, make sure that's allowed before
4785   // proceeding..
4786   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4787     return SDValue();
4788
4789   EVT VMovVT;
4790   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4791
4792   // It wouldn't really be worth bothering for doubles except for one very
4793   // important value, which does happen to match: 0.0. So make sure we don't do
4794   // anything stupid.
4795   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4796     return SDValue();
4797
4798   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4799   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
4800                                      VMovVT, false, VMOVModImm);
4801   if (NewVal != SDValue()) {
4802     SDLoc DL(Op);
4803     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4804                                       NewVal);
4805     if (IsDouble)
4806       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4807
4808     // It's a float: cast and extract a vector element.
4809     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4810                                        VecConstant);
4811     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4812                        DAG.getConstant(0, DL, MVT::i32));
4813   }
4814
4815   // Finally, try a VMVN.i32
4816   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
4817                              false, VMVNModImm);
4818   if (NewVal != SDValue()) {
4819     SDLoc DL(Op);
4820     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4821
4822     if (IsDouble)
4823       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4824
4825     // It's a float: cast and extract a vector element.
4826     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4827                                        VecConstant);
4828     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4829                        DAG.getConstant(0, DL, MVT::i32));
4830   }
4831
4832   return SDValue();
4833 }
4834
4835 // check if an VEXT instruction can handle the shuffle mask when the
4836 // vector sources of the shuffle are the same.
4837 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4838   unsigned NumElts = VT.getVectorNumElements();
4839
4840   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4841   if (M[0] < 0)
4842     return false;
4843
4844   Imm = M[0];
4845
4846   // If this is a VEXT shuffle, the immediate value is the index of the first
4847   // element.  The other shuffle indices must be the successive elements after
4848   // the first one.
4849   unsigned ExpectedElt = Imm;
4850   for (unsigned i = 1; i < NumElts; ++i) {
4851     // Increment the expected index.  If it wraps around, just follow it
4852     // back to index zero and keep going.
4853     ++ExpectedElt;
4854     if (ExpectedElt == NumElts)
4855       ExpectedElt = 0;
4856
4857     if (M[i] < 0) continue; // ignore UNDEF indices
4858     if (ExpectedElt != static_cast<unsigned>(M[i]))
4859       return false;
4860   }
4861
4862   return true;
4863 }
4864
4865
4866 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4867                        bool &ReverseVEXT, unsigned &Imm) {
4868   unsigned NumElts = VT.getVectorNumElements();
4869   ReverseVEXT = false;
4870
4871   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4872   if (M[0] < 0)
4873     return false;
4874
4875   Imm = M[0];
4876
4877   // If this is a VEXT shuffle, the immediate value is the index of the first
4878   // element.  The other shuffle indices must be the successive elements after
4879   // the first one.
4880   unsigned ExpectedElt = Imm;
4881   for (unsigned i = 1; i < NumElts; ++i) {
4882     // Increment the expected index.  If it wraps around, it may still be
4883     // a VEXT but the source vectors must be swapped.
4884     ExpectedElt += 1;
4885     if (ExpectedElt == NumElts * 2) {
4886       ExpectedElt = 0;
4887       ReverseVEXT = true;
4888     }
4889
4890     if (M[i] < 0) continue; // ignore UNDEF indices
4891     if (ExpectedElt != static_cast<unsigned>(M[i]))
4892       return false;
4893   }
4894
4895   // Adjust the index value if the source operands will be swapped.
4896   if (ReverseVEXT)
4897     Imm -= NumElts;
4898
4899   return true;
4900 }
4901
4902 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4903 /// instruction with the specified blocksize.  (The order of the elements
4904 /// within each block of the vector is reversed.)
4905 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4906   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4907          "Only possible block sizes for VREV are: 16, 32, 64");
4908
4909   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4910   if (EltSz == 64)
4911     return false;
4912
4913   unsigned NumElts = VT.getVectorNumElements();
4914   unsigned BlockElts = M[0] + 1;
4915   // If the first shuffle index is UNDEF, be optimistic.
4916   if (M[0] < 0)
4917     BlockElts = BlockSize / EltSz;
4918
4919   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4920     return false;
4921
4922   for (unsigned i = 0; i < NumElts; ++i) {
4923     if (M[i] < 0) continue; // ignore UNDEF indices
4924     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4925       return false;
4926   }
4927
4928   return true;
4929 }
4930
4931 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4932   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4933   // range, then 0 is placed into the resulting vector. So pretty much any mask
4934   // of 8 elements can work here.
4935   return VT == MVT::v8i8 && M.size() == 8;
4936 }
4937
4938 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4939   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4940   if (EltSz == 64)
4941     return false;
4942
4943   unsigned NumElts = VT.getVectorNumElements();
4944   WhichResult = (M[0] == 0 ? 0 : 1);
4945   for (unsigned i = 0; i < NumElts; i += 2) {
4946     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4947         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4948       return false;
4949   }
4950   return true;
4951 }
4952
4953 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4954 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4955 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4956 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4957   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4958   if (EltSz == 64)
4959     return false;
4960
4961   unsigned NumElts = VT.getVectorNumElements();
4962   WhichResult = (M[0] == 0 ? 0 : 1);
4963   for (unsigned i = 0; i < NumElts; i += 2) {
4964     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4965         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4966       return false;
4967   }
4968   return true;
4969 }
4970
4971 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4972   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4973   if (EltSz == 64)
4974     return false;
4975
4976   unsigned NumElts = VT.getVectorNumElements();
4977   WhichResult = (M[0] == 0 ? 0 : 1);
4978   for (unsigned i = 0; i != NumElts; ++i) {
4979     if (M[i] < 0) continue; // ignore UNDEF indices
4980     if ((unsigned) M[i] != 2 * i + WhichResult)
4981       return false;
4982   }
4983
4984   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4985   if (VT.is64BitVector() && EltSz == 32)
4986     return false;
4987
4988   return true;
4989 }
4990
4991 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4992 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4993 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4994 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4995   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4996   if (EltSz == 64)
4997     return false;
4998
4999   unsigned Half = VT.getVectorNumElements() / 2;
5000   WhichResult = (M[0] == 0 ? 0 : 1);
5001   for (unsigned j = 0; j != 2; ++j) {
5002     unsigned Idx = WhichResult;
5003     for (unsigned i = 0; i != Half; ++i) {
5004       int MIdx = M[i + j * Half];
5005       if (MIdx >= 0 && (unsigned) MIdx != Idx)
5006         return false;
5007       Idx += 2;
5008     }
5009   }
5010
5011   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5012   if (VT.is64BitVector() && EltSz == 32)
5013     return false;
5014
5015   return true;
5016 }
5017
5018 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5019   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5020   if (EltSz == 64)
5021     return false;
5022
5023   unsigned NumElts = VT.getVectorNumElements();
5024   WhichResult = (M[0] == 0 ? 0 : 1);
5025   unsigned Idx = WhichResult * NumElts / 2;
5026   for (unsigned i = 0; i != NumElts; i += 2) {
5027     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
5028         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
5029       return false;
5030     Idx += 1;
5031   }
5032
5033   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5034   if (VT.is64BitVector() && EltSz == 32)
5035     return false;
5036
5037   return true;
5038 }
5039
5040 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5041 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5042 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5043 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5044   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5045   if (EltSz == 64)
5046     return false;
5047
5048   unsigned NumElts = VT.getVectorNumElements();
5049   WhichResult = (M[0] == 0 ? 0 : 1);
5050   unsigned Idx = WhichResult * NumElts / 2;
5051   for (unsigned i = 0; i != NumElts; i += 2) {
5052     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
5053         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
5054       return false;
5055     Idx += 1;
5056   }
5057
5058   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5059   if (VT.is64BitVector() && EltSz == 32)
5060     return false;
5061
5062   return true;
5063 }
5064
5065 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
5066 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
5067 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
5068                                            unsigned &WhichResult,
5069                                            bool &isV_UNDEF) {
5070   isV_UNDEF = false;
5071   if (isVTRNMask(ShuffleMask, VT, WhichResult))
5072     return ARMISD::VTRN;
5073   if (isVUZPMask(ShuffleMask, VT, WhichResult))
5074     return ARMISD::VUZP;
5075   if (isVZIPMask(ShuffleMask, VT, WhichResult))
5076     return ARMISD::VZIP;
5077
5078   isV_UNDEF = true;
5079   if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5080     return ARMISD::VTRN;
5081   if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5082     return ARMISD::VUZP;
5083   if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5084     return ARMISD::VZIP;
5085
5086   return 0;
5087 }
5088
5089 /// \return true if this is a reverse operation on an vector.
5090 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5091   unsigned NumElts = VT.getVectorNumElements();
5092   // Make sure the mask has the right size.
5093   if (NumElts != M.size())
5094       return false;
5095
5096   // Look for <15, ..., 3, -1, 1, 0>.
5097   for (unsigned i = 0; i != NumElts; ++i)
5098     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5099       return false;
5100
5101   return true;
5102 }
5103
5104 // If N is an integer constant that can be moved into a register in one
5105 // instruction, return an SDValue of such a constant (will become a MOV
5106 // instruction).  Otherwise return null.
5107 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5108                                      const ARMSubtarget *ST, SDLoc dl) {
5109   uint64_t Val;
5110   if (!isa<ConstantSDNode>(N))
5111     return SDValue();
5112   Val = cast<ConstantSDNode>(N)->getZExtValue();
5113
5114   if (ST->isThumb1Only()) {
5115     if (Val <= 255 || ~Val <= 255)
5116       return DAG.getConstant(Val, dl, MVT::i32);
5117   } else {
5118     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5119       return DAG.getConstant(Val, dl, MVT::i32);
5120   }
5121   return SDValue();
5122 }
5123
5124 // If this is a case we can't handle, return null and let the default
5125 // expansion code take care of it.
5126 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5127                                              const ARMSubtarget *ST) const {
5128   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5129   SDLoc dl(Op);
5130   EVT VT = Op.getValueType();
5131
5132   APInt SplatBits, SplatUndef;
5133   unsigned SplatBitSize;
5134   bool HasAnyUndefs;
5135   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5136     if (SplatBitSize <= 64) {
5137       // Check if an immediate VMOV works.
5138       EVT VmovVT;
5139       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5140                                       SplatUndef.getZExtValue(), SplatBitSize,
5141                                       DAG, dl, VmovVT, VT.is128BitVector(),
5142                                       VMOVModImm);
5143       if (Val.getNode()) {
5144         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5145         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5146       }
5147
5148       // Try an immediate VMVN.
5149       uint64_t NegatedImm = (~SplatBits).getZExtValue();
5150       Val = isNEONModifiedImm(NegatedImm,
5151                                       SplatUndef.getZExtValue(), SplatBitSize,
5152                                       DAG, dl, VmovVT, VT.is128BitVector(),
5153                                       VMVNModImm);
5154       if (Val.getNode()) {
5155         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5156         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5157       }
5158
5159       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5160       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5161         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5162         if (ImmVal != -1) {
5163           SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
5164           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5165         }
5166       }
5167     }
5168   }
5169
5170   // Scan through the operands to see if only one value is used.
5171   //
5172   // As an optimisation, even if more than one value is used it may be more
5173   // profitable to splat with one value then change some lanes.
5174   //
5175   // Heuristically we decide to do this if the vector has a "dominant" value,
5176   // defined as splatted to more than half of the lanes.
5177   unsigned NumElts = VT.getVectorNumElements();
5178   bool isOnlyLowElement = true;
5179   bool usesOnlyOneValue = true;
5180   bool hasDominantValue = false;
5181   bool isConstant = true;
5182
5183   // Map of the number of times a particular SDValue appears in the
5184   // element list.
5185   DenseMap<SDValue, unsigned> ValueCounts;
5186   SDValue Value;
5187   for (unsigned i = 0; i < NumElts; ++i) {
5188     SDValue V = Op.getOperand(i);
5189     if (V.getOpcode() == ISD::UNDEF)
5190       continue;
5191     if (i > 0)
5192       isOnlyLowElement = false;
5193     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5194       isConstant = false;
5195
5196     ValueCounts.insert(std::make_pair(V, 0));
5197     unsigned &Count = ValueCounts[V];
5198
5199     // Is this value dominant? (takes up more than half of the lanes)
5200     if (++Count > (NumElts / 2)) {
5201       hasDominantValue = true;
5202       Value = V;
5203     }
5204   }
5205   if (ValueCounts.size() != 1)
5206     usesOnlyOneValue = false;
5207   if (!Value.getNode() && ValueCounts.size() > 0)
5208     Value = ValueCounts.begin()->first;
5209
5210   if (ValueCounts.size() == 0)
5211     return DAG.getUNDEF(VT);
5212
5213   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5214   // Keep going if we are hitting this case.
5215   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5216     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5217
5218   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5219
5220   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
5221   // i32 and try again.
5222   if (hasDominantValue && EltSize <= 32) {
5223     if (!isConstant) {
5224       SDValue N;
5225
5226       // If we are VDUPing a value that comes directly from a vector, that will
5227       // cause an unnecessary move to and from a GPR, where instead we could
5228       // just use VDUPLANE. We can only do this if the lane being extracted
5229       // is at a constant index, as the VDUP from lane instructions only have
5230       // constant-index forms.
5231       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5232           isa<ConstantSDNode>(Value->getOperand(1))) {
5233         // We need to create a new undef vector to use for the VDUPLANE if the
5234         // size of the vector from which we get the value is different than the
5235         // size of the vector that we need to create. We will insert the element
5236         // such that the register coalescer will remove unnecessary copies.
5237         if (VT != Value->getOperand(0).getValueType()) {
5238           ConstantSDNode *constIndex;
5239           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5240           assert(constIndex && "The index is not a constant!");
5241           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5242                              VT.getVectorNumElements();
5243           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5244                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5245                         Value, DAG.getConstant(index, dl, MVT::i32)),
5246                            DAG.getConstant(index, dl, MVT::i32));
5247         } else
5248           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5249                         Value->getOperand(0), Value->getOperand(1));
5250       } else
5251         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5252
5253       if (!usesOnlyOneValue) {
5254         // The dominant value was splatted as 'N', but we now have to insert
5255         // all differing elements.
5256         for (unsigned I = 0; I < NumElts; ++I) {
5257           if (Op.getOperand(I) == Value)
5258             continue;
5259           SmallVector<SDValue, 3> Ops;
5260           Ops.push_back(N);
5261           Ops.push_back(Op.getOperand(I));
5262           Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
5263           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5264         }
5265       }
5266       return N;
5267     }
5268     if (VT.getVectorElementType().isFloatingPoint()) {
5269       SmallVector<SDValue, 8> Ops;
5270       for (unsigned i = 0; i < NumElts; ++i)
5271         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5272                                   Op.getOperand(i)));
5273       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5274       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5275       Val = LowerBUILD_VECTOR(Val, DAG, ST);
5276       if (Val.getNode())
5277         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5278     }
5279     if (usesOnlyOneValue) {
5280       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5281       if (isConstant && Val.getNode())
5282         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5283     }
5284   }
5285
5286   // If all elements are constants and the case above didn't get hit, fall back
5287   // to the default expansion, which will generate a load from the constant
5288   // pool.
5289   if (isConstant)
5290     return SDValue();
5291
5292   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5293   if (NumElts >= 4) {
5294     SDValue shuffle = ReconstructShuffle(Op, DAG);
5295     if (shuffle != SDValue())
5296       return shuffle;
5297   }
5298
5299   // Vectors with 32- or 64-bit elements can be built by directly assigning
5300   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
5301   // will be legalized.
5302   if (EltSize >= 32) {
5303     // Do the expansion with floating-point types, since that is what the VFP
5304     // registers are defined to use, and since i64 is not legal.
5305     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5306     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5307     SmallVector<SDValue, 8> Ops;
5308     for (unsigned i = 0; i < NumElts; ++i)
5309       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5310     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5311     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5312   }
5313
5314   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5315   // know the default expansion would otherwise fall back on something even
5316   // worse. For a vector with one or two non-undef values, that's
5317   // scalar_to_vector for the elements followed by a shuffle (provided the
5318   // shuffle is valid for the target) and materialization element by element
5319   // on the stack followed by a load for everything else.
5320   if (!isConstant && !usesOnlyOneValue) {
5321     SDValue Vec = DAG.getUNDEF(VT);
5322     for (unsigned i = 0 ; i < NumElts; ++i) {
5323       SDValue V = Op.getOperand(i);
5324       if (V.getOpcode() == ISD::UNDEF)
5325         continue;
5326       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
5327       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5328     }
5329     return Vec;
5330   }
5331
5332   return SDValue();
5333 }
5334
5335 // Gather data to see if the operation can be modelled as a
5336 // shuffle in combination with VEXTs.
5337 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5338                                               SelectionDAG &DAG) const {
5339   SDLoc dl(Op);
5340   EVT VT = Op.getValueType();
5341   unsigned NumElts = VT.getVectorNumElements();
5342
5343   SmallVector<SDValue, 2> SourceVecs;
5344   SmallVector<unsigned, 2> MinElts;
5345   SmallVector<unsigned, 2> MaxElts;
5346
5347   for (unsigned i = 0; i < NumElts; ++i) {
5348     SDValue V = Op.getOperand(i);
5349     if (V.getOpcode() == ISD::UNDEF)
5350       continue;
5351     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5352       // A shuffle can only come from building a vector from various
5353       // elements of other vectors.
5354       return SDValue();
5355     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5356                VT.getVectorElementType()) {
5357       // This code doesn't know how to handle shuffles where the vector
5358       // element types do not match (this happens because type legalization
5359       // promotes the return type of EXTRACT_VECTOR_ELT).
5360       // FIXME: It might be appropriate to extend this code to handle
5361       // mismatched types.
5362       return SDValue();
5363     }
5364
5365     // Record this extraction against the appropriate vector if possible...
5366     SDValue SourceVec = V.getOperand(0);
5367     // If the element number isn't a constant, we can't effectively
5368     // analyze what's going on.
5369     if (!isa<ConstantSDNode>(V.getOperand(1)))
5370       return SDValue();
5371     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5372     bool FoundSource = false;
5373     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5374       if (SourceVecs[j] == SourceVec) {
5375         if (MinElts[j] > EltNo)
5376           MinElts[j] = EltNo;
5377         if (MaxElts[j] < EltNo)
5378           MaxElts[j] = EltNo;
5379         FoundSource = true;
5380         break;
5381       }
5382     }
5383
5384     // Or record a new source if not...
5385     if (!FoundSource) {
5386       SourceVecs.push_back(SourceVec);
5387       MinElts.push_back(EltNo);
5388       MaxElts.push_back(EltNo);
5389     }
5390   }
5391
5392   // Currently only do something sane when at most two source vectors
5393   // involved.
5394   if (SourceVecs.size() > 2)
5395     return SDValue();
5396
5397   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5398   int VEXTOffsets[2] = {0, 0};
5399
5400   // This loop extracts the usage patterns of the source vectors
5401   // and prepares appropriate SDValues for a shuffle if possible.
5402   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5403     if (SourceVecs[i].getValueType() == VT) {
5404       // No VEXT necessary
5405       ShuffleSrcs[i] = SourceVecs[i];
5406       VEXTOffsets[i] = 0;
5407       continue;
5408     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5409       // It probably isn't worth padding out a smaller vector just to
5410       // break it down again in a shuffle.
5411       return SDValue();
5412     }
5413
5414     // Since only 64-bit and 128-bit vectors are legal on ARM and
5415     // we've eliminated the other cases...
5416     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5417            "unexpected vector sizes in ReconstructShuffle");
5418
5419     if (MaxElts[i] - MinElts[i] >= NumElts) {
5420       // Span too large for a VEXT to cope
5421       return SDValue();
5422     }
5423
5424     if (MinElts[i] >= NumElts) {
5425       // The extraction can just take the second half
5426       VEXTOffsets[i] = NumElts;
5427       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5428                                    SourceVecs[i],
5429                                    DAG.getIntPtrConstant(NumElts, dl));
5430     } else if (MaxElts[i] < NumElts) {
5431       // The extraction can just take the first half
5432       VEXTOffsets[i] = 0;
5433       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5434                                    SourceVecs[i],
5435                                    DAG.getIntPtrConstant(0, dl));
5436     } else {
5437       // An actual VEXT is needed
5438       VEXTOffsets[i] = MinElts[i];
5439       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5440                                      SourceVecs[i],
5441                                      DAG.getIntPtrConstant(0, dl));
5442       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5443                                      SourceVecs[i],
5444                                      DAG.getIntPtrConstant(NumElts, dl));
5445       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5446                                    DAG.getConstant(VEXTOffsets[i], dl,
5447                                                    MVT::i32));
5448     }
5449   }
5450
5451   SmallVector<int, 8> Mask;
5452
5453   for (unsigned i = 0; i < NumElts; ++i) {
5454     SDValue Entry = Op.getOperand(i);
5455     if (Entry.getOpcode() == ISD::UNDEF) {
5456       Mask.push_back(-1);
5457       continue;
5458     }
5459
5460     SDValue ExtractVec = Entry.getOperand(0);
5461     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5462                                           .getOperand(1))->getSExtValue();
5463     if (ExtractVec == SourceVecs[0]) {
5464       Mask.push_back(ExtractElt - VEXTOffsets[0]);
5465     } else {
5466       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5467     }
5468   }
5469
5470   // Final check before we try to produce nonsense...
5471   if (isShuffleMaskLegal(Mask, VT))
5472     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5473                                 &Mask[0]);
5474
5475   return SDValue();
5476 }
5477
5478 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5479 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5480 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5481 /// are assumed to be legal.
5482 bool
5483 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5484                                       EVT VT) const {
5485   if (VT.getVectorNumElements() == 4 &&
5486       (VT.is128BitVector() || VT.is64BitVector())) {
5487     unsigned PFIndexes[4];
5488     for (unsigned i = 0; i != 4; ++i) {
5489       if (M[i] < 0)
5490         PFIndexes[i] = 8;
5491       else
5492         PFIndexes[i] = M[i];
5493     }
5494
5495     // Compute the index in the perfect shuffle table.
5496     unsigned PFTableIndex =
5497       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5498     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5499     unsigned Cost = (PFEntry >> 30);
5500
5501     if (Cost <= 4)
5502       return true;
5503   }
5504
5505   bool ReverseVEXT, isV_UNDEF;
5506   unsigned Imm, WhichResult;
5507
5508   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5509   return (EltSize >= 32 ||
5510           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5511           isVREVMask(M, VT, 64) ||
5512           isVREVMask(M, VT, 32) ||
5513           isVREVMask(M, VT, 16) ||
5514           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5515           isVTBLMask(M, VT) ||
5516           isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) ||
5517           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5518 }
5519
5520 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5521 /// the specified operations to build the shuffle.
5522 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5523                                       SDValue RHS, SelectionDAG &DAG,
5524                                       SDLoc dl) {
5525   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5526   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5527   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5528
5529   enum {
5530     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5531     OP_VREV,
5532     OP_VDUP0,
5533     OP_VDUP1,
5534     OP_VDUP2,
5535     OP_VDUP3,
5536     OP_VEXT1,
5537     OP_VEXT2,
5538     OP_VEXT3,
5539     OP_VUZPL, // VUZP, left result
5540     OP_VUZPR, // VUZP, right result
5541     OP_VZIPL, // VZIP, left result
5542     OP_VZIPR, // VZIP, right result
5543     OP_VTRNL, // VTRN, left result
5544     OP_VTRNR  // VTRN, right result
5545   };
5546
5547   if (OpNum == OP_COPY) {
5548     if (LHSID == (1*9+2)*9+3) return LHS;
5549     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5550     return RHS;
5551   }
5552
5553   SDValue OpLHS, OpRHS;
5554   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5555   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5556   EVT VT = OpLHS.getValueType();
5557
5558   switch (OpNum) {
5559   default: llvm_unreachable("Unknown shuffle opcode!");
5560   case OP_VREV:
5561     // VREV divides the vector in half and swaps within the half.
5562     if (VT.getVectorElementType() == MVT::i32 ||
5563         VT.getVectorElementType() == MVT::f32)
5564       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5565     // vrev <4 x i16> -> VREV32
5566     if (VT.getVectorElementType() == MVT::i16)
5567       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5568     // vrev <4 x i8> -> VREV16
5569     assert(VT.getVectorElementType() == MVT::i8);
5570     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5571   case OP_VDUP0:
5572   case OP_VDUP1:
5573   case OP_VDUP2:
5574   case OP_VDUP3:
5575     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5576                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
5577   case OP_VEXT1:
5578   case OP_VEXT2:
5579   case OP_VEXT3:
5580     return DAG.getNode(ARMISD::VEXT, dl, VT,
5581                        OpLHS, OpRHS,
5582                        DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
5583   case OP_VUZPL:
5584   case OP_VUZPR:
5585     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5586                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5587   case OP_VZIPL:
5588   case OP_VZIPR:
5589     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5590                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5591   case OP_VTRNL:
5592   case OP_VTRNR:
5593     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5594                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5595   }
5596 }
5597
5598 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5599                                        ArrayRef<int> ShuffleMask,
5600                                        SelectionDAG &DAG) {
5601   // Check to see if we can use the VTBL instruction.
5602   SDValue V1 = Op.getOperand(0);
5603   SDValue V2 = Op.getOperand(1);
5604   SDLoc DL(Op);
5605
5606   SmallVector<SDValue, 8> VTBLMask;
5607   for (ArrayRef<int>::iterator
5608          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5609     VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
5610
5611   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5612     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5613                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5614
5615   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5616                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5617 }
5618
5619 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5620                                                       SelectionDAG &DAG) {
5621   SDLoc DL(Op);
5622   SDValue OpLHS = Op.getOperand(0);
5623   EVT VT = OpLHS.getValueType();
5624
5625   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5626          "Expect an v8i16/v16i8 type");
5627   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5628   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5629   // extract the first 8 bytes into the top double word and the last 8 bytes
5630   // into the bottom double word. The v8i16 case is similar.
5631   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5632   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5633                      DAG.getConstant(ExtractNum, DL, MVT::i32));
5634 }
5635
5636 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5637   SDValue V1 = Op.getOperand(0);
5638   SDValue V2 = Op.getOperand(1);
5639   SDLoc dl(Op);
5640   EVT VT = Op.getValueType();
5641   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5642
5643   // Convert shuffles that are directly supported on NEON to target-specific
5644   // DAG nodes, instead of keeping them as shuffles and matching them again
5645   // during code selection.  This is more efficient and avoids the possibility
5646   // of inconsistencies between legalization and selection.
5647   // FIXME: floating-point vectors should be canonicalized to integer vectors
5648   // of the same time so that they get CSEd properly.
5649   ArrayRef<int> ShuffleMask = SVN->getMask();
5650
5651   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5652   if (EltSize <= 32) {
5653     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5654       int Lane = SVN->getSplatIndex();
5655       // If this is undef splat, generate it via "just" vdup, if possible.
5656       if (Lane == -1) Lane = 0;
5657
5658       // Test if V1 is a SCALAR_TO_VECTOR.
5659       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5660         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5661       }
5662       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5663       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5664       // reaches it).
5665       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5666           !isa<ConstantSDNode>(V1.getOperand(0))) {
5667         bool IsScalarToVector = true;
5668         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5669           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5670             IsScalarToVector = false;
5671             break;
5672           }
5673         if (IsScalarToVector)
5674           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5675       }
5676       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5677                          DAG.getConstant(Lane, dl, MVT::i32));
5678     }
5679
5680     bool ReverseVEXT;
5681     unsigned Imm;
5682     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5683       if (ReverseVEXT)
5684         std::swap(V1, V2);
5685       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5686                          DAG.getConstant(Imm, dl, MVT::i32));
5687     }
5688
5689     if (isVREVMask(ShuffleMask, VT, 64))
5690       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5691     if (isVREVMask(ShuffleMask, VT, 32))
5692       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5693     if (isVREVMask(ShuffleMask, VT, 16))
5694       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5695
5696     if (V2->getOpcode() == ISD::UNDEF &&
5697         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5698       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5699                          DAG.getConstant(Imm, dl, MVT::i32));
5700     }
5701
5702     // Check for Neon shuffles that modify both input vectors in place.
5703     // If both results are used, i.e., if there are two shuffles with the same
5704     // source operands and with masks corresponding to both results of one of
5705     // these operations, DAG memoization will ensure that a single node is
5706     // used for both shuffles.
5707     unsigned WhichResult;
5708     bool isV_UNDEF;
5709     if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
5710             ShuffleMask, VT, WhichResult, isV_UNDEF)) {
5711       if (isV_UNDEF)
5712         V2 = V1;
5713       return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
5714           .getValue(WhichResult);
5715     }
5716
5717     // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
5718     // shuffles that produce a result larger than their operands with:
5719     //   shuffle(concat(v1, undef), concat(v2, undef))
5720     // ->
5721     //   shuffle(concat(v1, v2), undef)
5722     // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
5723     //
5724     // This is useful in the general case, but there are special cases where
5725     // native shuffles produce larger results: the two-result ops.
5726     //
5727     // Look through the concat when lowering them:
5728     //   shuffle(concat(v1, v2), undef)
5729     // ->
5730     //   concat(VZIP(v1, v2):0, :1)
5731     //
5732     if (V1->getOpcode() == ISD::CONCAT_VECTORS &&
5733         V2->getOpcode() == ISD::UNDEF) {
5734       SDValue SubV1 = V1->getOperand(0);
5735       SDValue SubV2 = V1->getOperand(1);
5736       EVT SubVT = SubV1.getValueType();
5737
5738       // We expect these to have been canonicalized to -1.
5739       assert(std::all_of(ShuffleMask.begin(), ShuffleMask.end(), [&](int i) {
5740         return i < (int)VT.getVectorNumElements();
5741       }) && "Unexpected shuffle index into UNDEF operand!");
5742
5743       if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
5744               ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
5745         if (isV_UNDEF)
5746           SubV2 = SubV1;
5747         assert((WhichResult == 0) &&
5748                "In-place shuffle of concat can only have one result!");
5749         SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
5750                                   SubV1, SubV2);
5751         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
5752                            Res.getValue(1));
5753       }
5754     }
5755   }
5756
5757   // If the shuffle is not directly supported and it has 4 elements, use
5758   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5759   unsigned NumElts = VT.getVectorNumElements();
5760   if (NumElts == 4) {
5761     unsigned PFIndexes[4];
5762     for (unsigned i = 0; i != 4; ++i) {
5763       if (ShuffleMask[i] < 0)
5764         PFIndexes[i] = 8;
5765       else
5766         PFIndexes[i] = ShuffleMask[i];
5767     }
5768
5769     // Compute the index in the perfect shuffle table.
5770     unsigned PFTableIndex =
5771       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5772     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5773     unsigned Cost = (PFEntry >> 30);
5774
5775     if (Cost <= 4)
5776       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5777   }
5778
5779   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5780   if (EltSize >= 32) {
5781     // Do the expansion with floating-point types, since that is what the VFP
5782     // registers are defined to use, and since i64 is not legal.
5783     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5784     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5785     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5786     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5787     SmallVector<SDValue, 8> Ops;
5788     for (unsigned i = 0; i < NumElts; ++i) {
5789       if (ShuffleMask[i] < 0)
5790         Ops.push_back(DAG.getUNDEF(EltVT));
5791       else
5792         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5793                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
5794                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5795                                                   dl, MVT::i32)));
5796     }
5797     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5798     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5799   }
5800
5801   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5802     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5803
5804   if (VT == MVT::v8i8) {
5805     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5806     if (NewOp.getNode())
5807       return NewOp;
5808   }
5809
5810   return SDValue();
5811 }
5812
5813 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5814   // INSERT_VECTOR_ELT is legal only for immediate indexes.
5815   SDValue Lane = Op.getOperand(2);
5816   if (!isa<ConstantSDNode>(Lane))
5817     return SDValue();
5818
5819   return Op;
5820 }
5821
5822 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5823   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5824   SDValue Lane = Op.getOperand(1);
5825   if (!isa<ConstantSDNode>(Lane))
5826     return SDValue();
5827
5828   SDValue Vec = Op.getOperand(0);
5829   if (Op.getValueType() == MVT::i32 &&
5830       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5831     SDLoc dl(Op);
5832     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5833   }
5834
5835   return Op;
5836 }
5837
5838 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5839   // The only time a CONCAT_VECTORS operation can have legal types is when
5840   // two 64-bit vectors are concatenated to a 128-bit vector.
5841   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5842          "unexpected CONCAT_VECTORS");
5843   SDLoc dl(Op);
5844   SDValue Val = DAG.getUNDEF(MVT::v2f64);
5845   SDValue Op0 = Op.getOperand(0);
5846   SDValue Op1 = Op.getOperand(1);
5847   if (Op0.getOpcode() != ISD::UNDEF)
5848     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5849                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5850                       DAG.getIntPtrConstant(0, dl));
5851   if (Op1.getOpcode() != ISD::UNDEF)
5852     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5853                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5854                       DAG.getIntPtrConstant(1, dl));
5855   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5856 }
5857
5858 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5859 /// element has been zero/sign-extended, depending on the isSigned parameter,
5860 /// from an integer type half its size.
5861 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5862                                    bool isSigned) {
5863   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5864   EVT VT = N->getValueType(0);
5865   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5866     SDNode *BVN = N->getOperand(0).getNode();
5867     if (BVN->getValueType(0) != MVT::v4i32 ||
5868         BVN->getOpcode() != ISD::BUILD_VECTOR)
5869       return false;
5870     unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
5871     unsigned HiElt = 1 - LoElt;
5872     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5873     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5874     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5875     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5876     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5877       return false;
5878     if (isSigned) {
5879       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5880           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5881         return true;
5882     } else {
5883       if (Hi0->isNullValue() && Hi1->isNullValue())
5884         return true;
5885     }
5886     return false;
5887   }
5888
5889   if (N->getOpcode() != ISD::BUILD_VECTOR)
5890     return false;
5891
5892   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5893     SDNode *Elt = N->getOperand(i).getNode();
5894     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5895       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5896       unsigned HalfSize = EltSize / 2;
5897       if (isSigned) {
5898         if (!isIntN(HalfSize, C->getSExtValue()))
5899           return false;
5900       } else {
5901         if (!isUIntN(HalfSize, C->getZExtValue()))
5902           return false;
5903       }
5904       continue;
5905     }
5906     return false;
5907   }
5908
5909   return true;
5910 }
5911
5912 /// isSignExtended - Check if a node is a vector value that is sign-extended
5913 /// or a constant BUILD_VECTOR with sign-extended elements.
5914 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5915   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5916     return true;
5917   if (isExtendedBUILD_VECTOR(N, DAG, true))
5918     return true;
5919   return false;
5920 }
5921
5922 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5923 /// or a constant BUILD_VECTOR with zero-extended elements.
5924 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5925   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5926     return true;
5927   if (isExtendedBUILD_VECTOR(N, DAG, false))
5928     return true;
5929   return false;
5930 }
5931
5932 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5933   if (OrigVT.getSizeInBits() >= 64)
5934     return OrigVT;
5935
5936   assert(OrigVT.isSimple() && "Expecting a simple value type");
5937
5938   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5939   switch (OrigSimpleTy) {
5940   default: llvm_unreachable("Unexpected Vector Type");
5941   case MVT::v2i8:
5942   case MVT::v2i16:
5943      return MVT::v2i32;
5944   case MVT::v4i8:
5945     return  MVT::v4i16;
5946   }
5947 }
5948
5949 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5950 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5951 /// We insert the required extension here to get the vector to fill a D register.
5952 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5953                                             const EVT &OrigTy,
5954                                             const EVT &ExtTy,
5955                                             unsigned ExtOpcode) {
5956   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5957   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5958   // 64-bits we need to insert a new extension so that it will be 64-bits.
5959   assert(ExtTy.is128BitVector() && "Unexpected extension size");
5960   if (OrigTy.getSizeInBits() >= 64)
5961     return N;
5962
5963   // Must extend size to at least 64 bits to be used as an operand for VMULL.
5964   EVT NewVT = getExtensionTo64Bits(OrigTy);
5965
5966   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5967 }
5968
5969 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5970 /// does not do any sign/zero extension. If the original vector is less
5971 /// than 64 bits, an appropriate extension will be added after the load to
5972 /// reach a total size of 64 bits. We have to add the extension separately
5973 /// because ARM does not have a sign/zero extending load for vectors.
5974 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5975   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5976
5977   // The load already has the right type.
5978   if (ExtendedTy == LD->getMemoryVT())
5979     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5980                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5981                 LD->isNonTemporal(), LD->isInvariant(),
5982                 LD->getAlignment());
5983
5984   // We need to create a zextload/sextload. We cannot just create a load
5985   // followed by a zext/zext node because LowerMUL is also run during normal
5986   // operation legalization where we can't create illegal types.
5987   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5988                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5989                         LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
5990                         LD->isNonTemporal(), LD->getAlignment());
5991 }
5992
5993 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5994 /// extending load, or BUILD_VECTOR with extended elements, return the
5995 /// unextended value. The unextended vector should be 64 bits so that it can
5996 /// be used as an operand to a VMULL instruction. If the original vector size
5997 /// before extension is less than 64 bits we add a an extension to resize
5998 /// the vector to 64 bits.
5999 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
6000   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
6001     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
6002                                         N->getOperand(0)->getValueType(0),
6003                                         N->getValueType(0),
6004                                         N->getOpcode());
6005
6006   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
6007     return SkipLoadExtensionForVMULL(LD, DAG);
6008
6009   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
6010   // have been legalized as a BITCAST from v4i32.
6011   if (N->getOpcode() == ISD::BITCAST) {
6012     SDNode *BVN = N->getOperand(0).getNode();
6013     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
6014            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
6015     unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6016     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
6017                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
6018   }
6019   // Construct a new BUILD_VECTOR with elements truncated to half the size.
6020   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
6021   EVT VT = N->getValueType(0);
6022   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
6023   unsigned NumElts = VT.getVectorNumElements();
6024   MVT TruncVT = MVT::getIntegerVT(EltSize);
6025   SmallVector<SDValue, 8> Ops;
6026   SDLoc dl(N);
6027   for (unsigned i = 0; i != NumElts; ++i) {
6028     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
6029     const APInt &CInt = C->getAPIntValue();
6030     // Element types smaller than 32 bits are not legal, so use i32 elements.
6031     // The values are implicitly truncated so sext vs. zext doesn't matter.
6032     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
6033   }
6034   return DAG.getNode(ISD::BUILD_VECTOR, dl,
6035                      MVT::getVectorVT(TruncVT, NumElts), Ops);
6036 }
6037
6038 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
6039   unsigned Opcode = N->getOpcode();
6040   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6041     SDNode *N0 = N->getOperand(0).getNode();
6042     SDNode *N1 = N->getOperand(1).getNode();
6043     return N0->hasOneUse() && N1->hasOneUse() &&
6044       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
6045   }
6046   return false;
6047 }
6048
6049 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
6050   unsigned Opcode = N->getOpcode();
6051   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6052     SDNode *N0 = N->getOperand(0).getNode();
6053     SDNode *N1 = N->getOperand(1).getNode();
6054     return N0->hasOneUse() && N1->hasOneUse() &&
6055       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
6056   }
6057   return false;
6058 }
6059
6060 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
6061   // Multiplications are only custom-lowered for 128-bit vectors so that
6062   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
6063   EVT VT = Op.getValueType();
6064   assert(VT.is128BitVector() && VT.isInteger() &&
6065          "unexpected type for custom-lowering ISD::MUL");
6066   SDNode *N0 = Op.getOperand(0).getNode();
6067   SDNode *N1 = Op.getOperand(1).getNode();
6068   unsigned NewOpc = 0;
6069   bool isMLA = false;
6070   bool isN0SExt = isSignExtended(N0, DAG);
6071   bool isN1SExt = isSignExtended(N1, DAG);
6072   if (isN0SExt && isN1SExt)
6073     NewOpc = ARMISD::VMULLs;
6074   else {
6075     bool isN0ZExt = isZeroExtended(N0, DAG);
6076     bool isN1ZExt = isZeroExtended(N1, DAG);
6077     if (isN0ZExt && isN1ZExt)
6078       NewOpc = ARMISD::VMULLu;
6079     else if (isN1SExt || isN1ZExt) {
6080       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
6081       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
6082       if (isN1SExt && isAddSubSExt(N0, DAG)) {
6083         NewOpc = ARMISD::VMULLs;
6084         isMLA = true;
6085       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
6086         NewOpc = ARMISD::VMULLu;
6087         isMLA = true;
6088       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
6089         std::swap(N0, N1);
6090         NewOpc = ARMISD::VMULLu;
6091         isMLA = true;
6092       }
6093     }
6094
6095     if (!NewOpc) {
6096       if (VT == MVT::v2i64)
6097         // Fall through to expand this.  It is not legal.
6098         return SDValue();
6099       else
6100         // Other vector multiplications are legal.
6101         return Op;
6102     }
6103   }
6104
6105   // Legalize to a VMULL instruction.
6106   SDLoc DL(Op);
6107   SDValue Op0;
6108   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
6109   if (!isMLA) {
6110     Op0 = SkipExtensionForVMULL(N0, DAG);
6111     assert(Op0.getValueType().is64BitVector() &&
6112            Op1.getValueType().is64BitVector() &&
6113            "unexpected types for extended operands to VMULL");
6114     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
6115   }
6116
6117   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
6118   // isel lowering to take advantage of no-stall back to back vmul + vmla.
6119   //   vmull q0, d4, d6
6120   //   vmlal q0, d5, d6
6121   // is faster than
6122   //   vaddl q0, d4, d5
6123   //   vmovl q1, d6
6124   //   vmul  q0, q0, q1
6125   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
6126   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
6127   EVT Op1VT = Op1.getValueType();
6128   return DAG.getNode(N0->getOpcode(), DL, VT,
6129                      DAG.getNode(NewOpc, DL, VT,
6130                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
6131                      DAG.getNode(NewOpc, DL, VT,
6132                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
6133 }
6134
6135 static SDValue
6136 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
6137   // Convert to float
6138   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
6139   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
6140   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
6141   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
6142   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
6143   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
6144   // Get reciprocal estimate.
6145   // float4 recip = vrecpeq_f32(yf);
6146   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6147                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6148                    Y);
6149   // Because char has a smaller range than uchar, we can actually get away
6150   // without any newton steps.  This requires that we use a weird bias
6151   // of 0xb000, however (again, this has been exhaustively tested).
6152   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
6153   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
6154   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
6155   Y = DAG.getConstant(0xb000, dl, MVT::i32);
6156   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
6157   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6158   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6159   // Convert back to short.
6160   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6161   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6162   return X;
6163 }
6164
6165 static SDValue
6166 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
6167   SDValue N2;
6168   // Convert to float.
6169   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6170   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6171   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6172   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6173   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6174   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6175
6176   // Use reciprocal estimate and one refinement step.
6177   // float4 recip = vrecpeq_f32(yf);
6178   // recip *= vrecpsq_f32(yf, recip);
6179   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6180                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6181                    N1);
6182   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6183                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6184                    N1, N2);
6185   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6186   // Because short has a smaller range than ushort, we can actually get away
6187   // with only a single newton step.  This requires that we use a weird bias
6188   // of 89, however (again, this has been exhaustively tested).
6189   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6190   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6191   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6192   N1 = DAG.getConstant(0x89, dl, MVT::i32);
6193   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6194   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6195   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6196   // Convert back to integer and return.
6197   // return vmovn_s32(vcvt_s32_f32(result));
6198   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6199   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6200   return N0;
6201 }
6202
6203 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6204   EVT VT = Op.getValueType();
6205   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6206          "unexpected type for custom-lowering ISD::SDIV");
6207
6208   SDLoc dl(Op);
6209   SDValue N0 = Op.getOperand(0);
6210   SDValue N1 = Op.getOperand(1);
6211   SDValue N2, N3;
6212
6213   if (VT == MVT::v8i8) {
6214     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6215     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6216
6217     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6218                      DAG.getIntPtrConstant(4, dl));
6219     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6220                      DAG.getIntPtrConstant(4, dl));
6221     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6222                      DAG.getIntPtrConstant(0, dl));
6223     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6224                      DAG.getIntPtrConstant(0, dl));
6225
6226     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6227     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6228
6229     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6230     N0 = LowerCONCAT_VECTORS(N0, DAG);
6231
6232     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6233     return N0;
6234   }
6235   return LowerSDIV_v4i16(N0, N1, dl, DAG);
6236 }
6237
6238 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6239   EVT VT = Op.getValueType();
6240   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6241          "unexpected type for custom-lowering ISD::UDIV");
6242
6243   SDLoc dl(Op);
6244   SDValue N0 = Op.getOperand(0);
6245   SDValue N1 = Op.getOperand(1);
6246   SDValue N2, N3;
6247
6248   if (VT == MVT::v8i8) {
6249     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6250     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6251
6252     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6253                      DAG.getIntPtrConstant(4, dl));
6254     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6255                      DAG.getIntPtrConstant(4, dl));
6256     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6257                      DAG.getIntPtrConstant(0, dl));
6258     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6259                      DAG.getIntPtrConstant(0, dl));
6260
6261     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6262     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6263
6264     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6265     N0 = LowerCONCAT_VECTORS(N0, DAG);
6266
6267     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6268                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
6269                                      MVT::i32),
6270                      N0);
6271     return N0;
6272   }
6273
6274   // v4i16 sdiv ... Convert to float.
6275   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6276   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6277   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6278   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6279   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6280   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6281
6282   // Use reciprocal estimate and two refinement steps.
6283   // float4 recip = vrecpeq_f32(yf);
6284   // recip *= vrecpsq_f32(yf, recip);
6285   // recip *= vrecpsq_f32(yf, recip);
6286   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6287                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6288                    BN1);
6289   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6290                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6291                    BN1, N2);
6292   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6293   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6294                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6295                    BN1, N2);
6296   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6297   // Simply multiplying by the reciprocal estimate can leave us a few ulps
6298   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6299   // and that it will never cause us to return an answer too large).
6300   // float4 result = as_float4(as_int4(xf*recip) + 2);
6301   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6302   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6303   N1 = DAG.getConstant(2, dl, MVT::i32);
6304   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6305   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6306   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6307   // Convert back to integer and return.
6308   // return vmovn_u32(vcvt_s32_f32(result));
6309   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6310   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6311   return N0;
6312 }
6313
6314 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6315   EVT VT = Op.getNode()->getValueType(0);
6316   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6317
6318   unsigned Opc;
6319   bool ExtraOp = false;
6320   switch (Op.getOpcode()) {
6321   default: llvm_unreachable("Invalid code");
6322   case ISD::ADDC: Opc = ARMISD::ADDC; break;
6323   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6324   case ISD::SUBC: Opc = ARMISD::SUBC; break;
6325   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6326   }
6327
6328   if (!ExtraOp)
6329     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6330                        Op.getOperand(1));
6331   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6332                      Op.getOperand(1), Op.getOperand(2));
6333 }
6334
6335 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6336   assert(Subtarget->isTargetDarwin());
6337
6338   // For iOS, we want to call an alternative entry point: __sincos_stret,
6339   // return values are passed via sret.
6340   SDLoc dl(Op);
6341   SDValue Arg = Op.getOperand(0);
6342   EVT ArgVT = Arg.getValueType();
6343   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6344   auto PtrVT = getPointerTy(DAG.getDataLayout());
6345
6346   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6347
6348   // Pair of floats / doubles used to pass the result.
6349   StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
6350
6351   // Create stack object for sret.
6352   auto &DL = DAG.getDataLayout();
6353   const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
6354   const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
6355   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6356   SDValue SRet = DAG.getFrameIndex(FrameIdx, getPointerTy(DL));
6357
6358   ArgListTy Args;
6359   ArgListEntry Entry;
6360
6361   Entry.Node = SRet;
6362   Entry.Ty = RetTy->getPointerTo();
6363   Entry.isSExt = false;
6364   Entry.isZExt = false;
6365   Entry.isSRet = true;
6366   Args.push_back(Entry);
6367
6368   Entry.Node = Arg;
6369   Entry.Ty = ArgTy;
6370   Entry.isSExt = false;
6371   Entry.isZExt = false;
6372   Args.push_back(Entry);
6373
6374   const char *LibcallName  = (ArgVT == MVT::f64)
6375   ? "__sincos_stret" : "__sincosf_stret";
6376   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
6377
6378   TargetLowering::CallLoweringInfo CLI(DAG);
6379   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6380     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6381                std::move(Args), 0)
6382     .setDiscardResult();
6383
6384   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6385
6386   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6387                                 MachinePointerInfo(), false, false, false, 0);
6388
6389   // Address of cos field.
6390   SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
6391                             DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
6392   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6393                                 MachinePointerInfo(), false, false, false, 0);
6394
6395   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6396   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6397                      LoadSin.getValue(0), LoadCos.getValue(0));
6398 }
6399
6400 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6401   // Monotonic load/store is legal for all targets
6402   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6403     return Op;
6404
6405   // Acquire/Release load/store is not legal for targets without a
6406   // dmb or equivalent available.
6407   return SDValue();
6408 }
6409
6410 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6411                                     SmallVectorImpl<SDValue> &Results,
6412                                     SelectionDAG &DAG,
6413                                     const ARMSubtarget *Subtarget) {
6414   SDLoc DL(N);
6415   SDValue Cycles32, OutChain;
6416
6417   if (Subtarget->hasPerfMon()) {
6418     // Under Power Management extensions, the cycle-count is:
6419     //    mrc p15, #0, <Rt>, c9, c13, #0
6420     SDValue Ops[] = { N->getOperand(0), // Chain
6421                       DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
6422                       DAG.getConstant(15, DL, MVT::i32),
6423                       DAG.getConstant(0, DL, MVT::i32),
6424                       DAG.getConstant(9, DL, MVT::i32),
6425                       DAG.getConstant(13, DL, MVT::i32),
6426                       DAG.getConstant(0, DL, MVT::i32)
6427     };
6428
6429     Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6430                            DAG.getVTList(MVT::i32, MVT::Other), Ops);
6431     OutChain = Cycles32.getValue(1);
6432   } else {
6433     // Intrinsic is defined to return 0 on unsupported platforms. Technically
6434     // there are older ARM CPUs that have implementation-specific ways of
6435     // obtaining this information (FIXME!).
6436     Cycles32 = DAG.getConstant(0, DL, MVT::i32);
6437     OutChain = DAG.getEntryNode();
6438   }
6439
6440
6441   SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6442                                  Cycles32, DAG.getConstant(0, DL, MVT::i32));
6443   Results.push_back(Cycles64);
6444   Results.push_back(OutChain);
6445 }
6446
6447 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6448   switch (Op.getOpcode()) {
6449   default: llvm_unreachable("Don't know how to custom lower this!");
6450   case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
6451   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6452   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6453   case ISD::GlobalAddress:
6454     switch (Subtarget->getTargetTriple().getObjectFormat()) {
6455     default: llvm_unreachable("unknown object format");
6456     case Triple::COFF:
6457       return LowerGlobalAddressWindows(Op, DAG);
6458     case Triple::ELF:
6459       return LowerGlobalAddressELF(Op, DAG);
6460     case Triple::MachO:
6461       return LowerGlobalAddressDarwin(Op, DAG);
6462     }
6463   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6464   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6465   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6466   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6467   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6468   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6469   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6470   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6471   case ISD::SINT_TO_FP:
6472   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6473   case ISD::FP_TO_SINT:
6474   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6475   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6476   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6477   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6478   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6479   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6480   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6481   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6482                                                                Subtarget);
6483   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6484   case ISD::SHL:
6485   case ISD::SRL:
6486   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6487   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6488   case ISD::SRL_PARTS:
6489   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6490   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6491   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6492   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6493   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6494   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6495   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6496   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6497   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6498   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6499   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6500   case ISD::MUL:           return LowerMUL(Op, DAG);
6501   case ISD::SDIV:          return LowerSDIV(Op, DAG);
6502   case ISD::UDIV:          return LowerUDIV(Op, DAG);
6503   case ISD::ADDC:
6504   case ISD::ADDE:
6505   case ISD::SUBC:
6506   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6507   case ISD::SADDO:
6508   case ISD::UADDO:
6509   case ISD::SSUBO:
6510   case ISD::USUBO:
6511     return LowerXALUO(Op, DAG);
6512   case ISD::ATOMIC_LOAD:
6513   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6514   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6515   case ISD::SDIVREM:
6516   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6517   case ISD::DYNAMIC_STACKALLOC:
6518     if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6519       return LowerDYNAMIC_STACKALLOC(Op, DAG);
6520     llvm_unreachable("Don't know how to custom lower this!");
6521   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6522   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6523   }
6524 }
6525
6526 /// ReplaceNodeResults - Replace the results of node with an illegal result
6527 /// type with new values built out of custom code.
6528 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6529                                            SmallVectorImpl<SDValue>&Results,
6530                                            SelectionDAG &DAG) const {
6531   SDValue Res;
6532   switch (N->getOpcode()) {
6533   default:
6534     llvm_unreachable("Don't know how to custom expand this!");
6535   case ISD::READ_REGISTER:
6536     ExpandREAD_REGISTER(N, Results, DAG);
6537     break;
6538   case ISD::BITCAST:
6539     Res = ExpandBITCAST(N, DAG);
6540     break;
6541   case ISD::SRL:
6542   case ISD::SRA:
6543     Res = Expand64BitShift(N, DAG, Subtarget);
6544     break;
6545   case ISD::READCYCLECOUNTER:
6546     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6547     return;
6548   }
6549   if (Res.getNode())
6550     Results.push_back(Res);
6551 }
6552
6553 //===----------------------------------------------------------------------===//
6554 //                           ARM Scheduler Hooks
6555 //===----------------------------------------------------------------------===//
6556
6557 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6558 /// registers the function context.
6559 void ARMTargetLowering::
6560 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6561                        MachineBasicBlock *DispatchBB, int FI) const {
6562   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6563   DebugLoc dl = MI->getDebugLoc();
6564   MachineFunction *MF = MBB->getParent();
6565   MachineRegisterInfo *MRI = &MF->getRegInfo();
6566   MachineConstantPool *MCP = MF->getConstantPool();
6567   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6568   const Function *F = MF->getFunction();
6569
6570   bool isThumb = Subtarget->isThumb();
6571   bool isThumb2 = Subtarget->isThumb2();
6572
6573   unsigned PCLabelId = AFI->createPICLabelUId();
6574   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6575   ARMConstantPoolValue *CPV =
6576     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6577   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6578
6579   const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
6580                                            : &ARM::GPRRegClass;
6581
6582   // Grab constant pool and fixed stack memory operands.
6583   MachineMemOperand *CPMMO =
6584     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6585                              MachineMemOperand::MOLoad, 4, 4);
6586
6587   MachineMemOperand *FIMMOSt =
6588     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6589                              MachineMemOperand::MOStore, 4, 4);
6590
6591   // Load the address of the dispatch MBB into the jump buffer.
6592   if (isThumb2) {
6593     // Incoming value: jbuf
6594     //   ldr.n  r5, LCPI1_1
6595     //   orr    r5, r5, #1
6596     //   add    r5, pc
6597     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6598     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6599     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6600                    .addConstantPoolIndex(CPI)
6601                    .addMemOperand(CPMMO));
6602     // Set the low bit because of thumb mode.
6603     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6604     AddDefaultCC(
6605       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6606                      .addReg(NewVReg1, RegState::Kill)
6607                      .addImm(0x01)));
6608     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6609     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6610       .addReg(NewVReg2, RegState::Kill)
6611       .addImm(PCLabelId);
6612     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6613                    .addReg(NewVReg3, RegState::Kill)
6614                    .addFrameIndex(FI)
6615                    .addImm(36)  // &jbuf[1] :: pc
6616                    .addMemOperand(FIMMOSt));
6617   } else if (isThumb) {
6618     // Incoming value: jbuf
6619     //   ldr.n  r1, LCPI1_4
6620     //   add    r1, pc
6621     //   mov    r2, #1
6622     //   orrs   r1, r2
6623     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6624     //   str    r1, [r2]
6625     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6626     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6627                    .addConstantPoolIndex(CPI)
6628                    .addMemOperand(CPMMO));
6629     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6630     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6631       .addReg(NewVReg1, RegState::Kill)
6632       .addImm(PCLabelId);
6633     // Set the low bit because of thumb mode.
6634     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6635     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6636                    .addReg(ARM::CPSR, RegState::Define)
6637                    .addImm(1));
6638     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6639     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6640                    .addReg(ARM::CPSR, RegState::Define)
6641                    .addReg(NewVReg2, RegState::Kill)
6642                    .addReg(NewVReg3, RegState::Kill));
6643     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6644     BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
6645             .addFrameIndex(FI)
6646             .addImm(36); // &jbuf[1] :: pc
6647     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6648                    .addReg(NewVReg4, RegState::Kill)
6649                    .addReg(NewVReg5, RegState::Kill)
6650                    .addImm(0)
6651                    .addMemOperand(FIMMOSt));
6652   } else {
6653     // Incoming value: jbuf
6654     //   ldr  r1, LCPI1_1
6655     //   add  r1, pc, r1
6656     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6657     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6658     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6659                    .addConstantPoolIndex(CPI)
6660                    .addImm(0)
6661                    .addMemOperand(CPMMO));
6662     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6663     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6664                    .addReg(NewVReg1, RegState::Kill)
6665                    .addImm(PCLabelId));
6666     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6667                    .addReg(NewVReg2, RegState::Kill)
6668                    .addFrameIndex(FI)
6669                    .addImm(36)  // &jbuf[1] :: pc
6670                    .addMemOperand(FIMMOSt));
6671   }
6672 }
6673
6674 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr *MI,
6675                                               MachineBasicBlock *MBB) const {
6676   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6677   DebugLoc dl = MI->getDebugLoc();
6678   MachineFunction *MF = MBB->getParent();
6679   MachineRegisterInfo *MRI = &MF->getRegInfo();
6680   MachineFrameInfo *MFI = MF->getFrameInfo();
6681   int FI = MFI->getFunctionContextIndex();
6682
6683   const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
6684                                                         : &ARM::GPRnopcRegClass;
6685
6686   // Get a mapping of the call site numbers to all of the landing pads they're
6687   // associated with.
6688   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6689   unsigned MaxCSNum = 0;
6690   MachineModuleInfo &MMI = MF->getMMI();
6691   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6692        ++BB) {
6693     if (!BB->isLandingPad()) continue;
6694
6695     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6696     // pad.
6697     for (MachineBasicBlock::iterator
6698            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6699       if (!II->isEHLabel()) continue;
6700
6701       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6702       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6703
6704       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6705       for (SmallVectorImpl<unsigned>::iterator
6706              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6707            CSI != CSE; ++CSI) {
6708         CallSiteNumToLPad[*CSI].push_back(BB);
6709         MaxCSNum = std::max(MaxCSNum, *CSI);
6710       }
6711       break;
6712     }
6713   }
6714
6715   // Get an ordered list of the machine basic blocks for the jump table.
6716   std::vector<MachineBasicBlock*> LPadList;
6717   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6718   LPadList.reserve(CallSiteNumToLPad.size());
6719   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6720     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6721     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6722            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6723       LPadList.push_back(*II);
6724       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6725     }
6726   }
6727
6728   assert(!LPadList.empty() &&
6729          "No landing pad destinations for the dispatch jump table!");
6730
6731   // Create the jump table and associated information.
6732   MachineJumpTableInfo *JTI =
6733     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6734   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6735   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6736
6737   // Create the MBBs for the dispatch code.
6738
6739   // Shove the dispatch's address into the return slot in the function context.
6740   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6741   DispatchBB->setIsLandingPad();
6742
6743   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6744   unsigned trap_opcode;
6745   if (Subtarget->isThumb())
6746     trap_opcode = ARM::tTRAP;
6747   else
6748     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6749
6750   BuildMI(TrapBB, dl, TII->get(trap_opcode));
6751   DispatchBB->addSuccessor(TrapBB);
6752
6753   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6754   DispatchBB->addSuccessor(DispContBB);
6755
6756   // Insert and MBBs.
6757   MF->insert(MF->end(), DispatchBB);
6758   MF->insert(MF->end(), DispContBB);
6759   MF->insert(MF->end(), TrapBB);
6760
6761   // Insert code into the entry block that creates and registers the function
6762   // context.
6763   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6764
6765   MachineMemOperand *FIMMOLd =
6766     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6767                              MachineMemOperand::MOLoad |
6768                              MachineMemOperand::MOVolatile, 4, 4);
6769
6770   MachineInstrBuilder MIB;
6771   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6772
6773   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6774   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6775
6776   // Add a register mask with no preserved registers.  This results in all
6777   // registers being marked as clobbered.
6778   MIB.addRegMask(RI.getNoPreservedMask());
6779
6780   unsigned NumLPads = LPadList.size();
6781   if (Subtarget->isThumb2()) {
6782     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6783     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6784                    .addFrameIndex(FI)
6785                    .addImm(4)
6786                    .addMemOperand(FIMMOLd));
6787
6788     if (NumLPads < 256) {
6789       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6790                      .addReg(NewVReg1)
6791                      .addImm(LPadList.size()));
6792     } else {
6793       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6794       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6795                      .addImm(NumLPads & 0xFFFF));
6796
6797       unsigned VReg2 = VReg1;
6798       if ((NumLPads & 0xFFFF0000) != 0) {
6799         VReg2 = MRI->createVirtualRegister(TRC);
6800         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6801                        .addReg(VReg1)
6802                        .addImm(NumLPads >> 16));
6803       }
6804
6805       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6806                      .addReg(NewVReg1)
6807                      .addReg(VReg2));
6808     }
6809
6810     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6811       .addMBB(TrapBB)
6812       .addImm(ARMCC::HI)
6813       .addReg(ARM::CPSR);
6814
6815     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6816     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6817                    .addJumpTableIndex(MJTI));
6818
6819     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6820     AddDefaultCC(
6821       AddDefaultPred(
6822         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6823         .addReg(NewVReg3, RegState::Kill)
6824         .addReg(NewVReg1)
6825         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6826
6827     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6828       .addReg(NewVReg4, RegState::Kill)
6829       .addReg(NewVReg1)
6830       .addJumpTableIndex(MJTI);
6831   } else if (Subtarget->isThumb()) {
6832     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6833     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6834                    .addFrameIndex(FI)
6835                    .addImm(1)
6836                    .addMemOperand(FIMMOLd));
6837
6838     if (NumLPads < 256) {
6839       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6840                      .addReg(NewVReg1)
6841                      .addImm(NumLPads));
6842     } else {
6843       MachineConstantPool *ConstantPool = MF->getConstantPool();
6844       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6845       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6846
6847       // MachineConstantPool wants an explicit alignment.
6848       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6849       if (Align == 0)
6850         Align = getDataLayout()->getTypeAllocSize(C->getType());
6851       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6852
6853       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6854       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6855                      .addReg(VReg1, RegState::Define)
6856                      .addConstantPoolIndex(Idx));
6857       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6858                      .addReg(NewVReg1)
6859                      .addReg(VReg1));
6860     }
6861
6862     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6863       .addMBB(TrapBB)
6864       .addImm(ARMCC::HI)
6865       .addReg(ARM::CPSR);
6866
6867     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6868     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6869                    .addReg(ARM::CPSR, RegState::Define)
6870                    .addReg(NewVReg1)
6871                    .addImm(2));
6872
6873     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6874     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6875                    .addJumpTableIndex(MJTI));
6876
6877     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6878     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6879                    .addReg(ARM::CPSR, RegState::Define)
6880                    .addReg(NewVReg2, RegState::Kill)
6881                    .addReg(NewVReg3));
6882
6883     MachineMemOperand *JTMMOLd =
6884       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6885                                MachineMemOperand::MOLoad, 4, 4);
6886
6887     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6888     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6889                    .addReg(NewVReg4, RegState::Kill)
6890                    .addImm(0)
6891                    .addMemOperand(JTMMOLd));
6892
6893     unsigned NewVReg6 = NewVReg5;
6894     if (RelocM == Reloc::PIC_) {
6895       NewVReg6 = MRI->createVirtualRegister(TRC);
6896       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6897                      .addReg(ARM::CPSR, RegState::Define)
6898                      .addReg(NewVReg5, RegState::Kill)
6899                      .addReg(NewVReg3));
6900     }
6901
6902     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6903       .addReg(NewVReg6, RegState::Kill)
6904       .addJumpTableIndex(MJTI);
6905   } else {
6906     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6907     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6908                    .addFrameIndex(FI)
6909                    .addImm(4)
6910                    .addMemOperand(FIMMOLd));
6911
6912     if (NumLPads < 256) {
6913       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6914                      .addReg(NewVReg1)
6915                      .addImm(NumLPads));
6916     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6917       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6918       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6919                      .addImm(NumLPads & 0xFFFF));
6920
6921       unsigned VReg2 = VReg1;
6922       if ((NumLPads & 0xFFFF0000) != 0) {
6923         VReg2 = MRI->createVirtualRegister(TRC);
6924         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6925                        .addReg(VReg1)
6926                        .addImm(NumLPads >> 16));
6927       }
6928
6929       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6930                      .addReg(NewVReg1)
6931                      .addReg(VReg2));
6932     } else {
6933       MachineConstantPool *ConstantPool = MF->getConstantPool();
6934       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6935       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6936
6937       // MachineConstantPool wants an explicit alignment.
6938       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6939       if (Align == 0)
6940         Align = getDataLayout()->getTypeAllocSize(C->getType());
6941       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6942
6943       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6944       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6945                      .addReg(VReg1, RegState::Define)
6946                      .addConstantPoolIndex(Idx)
6947                      .addImm(0));
6948       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6949                      .addReg(NewVReg1)
6950                      .addReg(VReg1, RegState::Kill));
6951     }
6952
6953     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6954       .addMBB(TrapBB)
6955       .addImm(ARMCC::HI)
6956       .addReg(ARM::CPSR);
6957
6958     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6959     AddDefaultCC(
6960       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6961                      .addReg(NewVReg1)
6962                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6963     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6964     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6965                    .addJumpTableIndex(MJTI));
6966
6967     MachineMemOperand *JTMMOLd =
6968       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6969                                MachineMemOperand::MOLoad, 4, 4);
6970     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6971     AddDefaultPred(
6972       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6973       .addReg(NewVReg3, RegState::Kill)
6974       .addReg(NewVReg4)
6975       .addImm(0)
6976       .addMemOperand(JTMMOLd));
6977
6978     if (RelocM == Reloc::PIC_) {
6979       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6980         .addReg(NewVReg5, RegState::Kill)
6981         .addReg(NewVReg4)
6982         .addJumpTableIndex(MJTI);
6983     } else {
6984       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6985         .addReg(NewVReg5, RegState::Kill)
6986         .addJumpTableIndex(MJTI);
6987     }
6988   }
6989
6990   // Add the jump table entries as successors to the MBB.
6991   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6992   for (std::vector<MachineBasicBlock*>::iterator
6993          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6994     MachineBasicBlock *CurMBB = *I;
6995     if (SeenMBBs.insert(CurMBB).second)
6996       DispContBB->addSuccessor(CurMBB);
6997   }
6998
6999   // N.B. the order the invoke BBs are processed in doesn't matter here.
7000   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
7001   SmallVector<MachineBasicBlock*, 64> MBBLPads;
7002   for (MachineBasicBlock *BB : InvokeBBs) {
7003
7004     // Remove the landing pad successor from the invoke block and replace it
7005     // with the new dispatch block.
7006     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
7007                                                   BB->succ_end());
7008     while (!Successors.empty()) {
7009       MachineBasicBlock *SMBB = Successors.pop_back_val();
7010       if (SMBB->isLandingPad()) {
7011         BB->removeSuccessor(SMBB);
7012         MBBLPads.push_back(SMBB);
7013       }
7014     }
7015
7016     BB->addSuccessor(DispatchBB);
7017
7018     // Find the invoke call and mark all of the callee-saved registers as
7019     // 'implicit defined' so that they're spilled. This prevents code from
7020     // moving instructions to before the EH block, where they will never be
7021     // executed.
7022     for (MachineBasicBlock::reverse_iterator
7023            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
7024       if (!II->isCall()) continue;
7025
7026       DenseMap<unsigned, bool> DefRegs;
7027       for (MachineInstr::mop_iterator
7028              OI = II->operands_begin(), OE = II->operands_end();
7029            OI != OE; ++OI) {
7030         if (!OI->isReg()) continue;
7031         DefRegs[OI->getReg()] = true;
7032       }
7033
7034       MachineInstrBuilder MIB(*MF, &*II);
7035
7036       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
7037         unsigned Reg = SavedRegs[i];
7038         if (Subtarget->isThumb2() &&
7039             !ARM::tGPRRegClass.contains(Reg) &&
7040             !ARM::hGPRRegClass.contains(Reg))
7041           continue;
7042         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
7043           continue;
7044         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7045           continue;
7046         if (!DefRegs[Reg])
7047           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7048       }
7049
7050       break;
7051     }
7052   }
7053
7054   // Mark all former landing pads as non-landing pads. The dispatch is the only
7055   // landing pad now.
7056   for (SmallVectorImpl<MachineBasicBlock*>::iterator
7057          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7058     (*I)->setIsLandingPad(false);
7059
7060   // The instruction is gone now.
7061   MI->eraseFromParent();
7062 }
7063
7064 static
7065 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7066   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7067        E = MBB->succ_end(); I != E; ++I)
7068     if (*I != Succ)
7069       return *I;
7070   llvm_unreachable("Expecting a BB with two successors!");
7071 }
7072
7073 /// Return the load opcode for a given load size. If load size >= 8,
7074 /// neon opcode will be returned.
7075 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7076   if (LdSize >= 8)
7077     return LdSize == 16 ? ARM::VLD1q32wb_fixed
7078                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7079   if (IsThumb1)
7080     return LdSize == 4 ? ARM::tLDRi
7081                        : LdSize == 2 ? ARM::tLDRHi
7082                                      : LdSize == 1 ? ARM::tLDRBi : 0;
7083   if (IsThumb2)
7084     return LdSize == 4 ? ARM::t2LDR_POST
7085                        : LdSize == 2 ? ARM::t2LDRH_POST
7086                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7087   return LdSize == 4 ? ARM::LDR_POST_IMM
7088                      : LdSize == 2 ? ARM::LDRH_POST
7089                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7090 }
7091
7092 /// Return the store opcode for a given store size. If store size >= 8,
7093 /// neon opcode will be returned.
7094 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7095   if (StSize >= 8)
7096     return StSize == 16 ? ARM::VST1q32wb_fixed
7097                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7098   if (IsThumb1)
7099     return StSize == 4 ? ARM::tSTRi
7100                        : StSize == 2 ? ARM::tSTRHi
7101                                      : StSize == 1 ? ARM::tSTRBi : 0;
7102   if (IsThumb2)
7103     return StSize == 4 ? ARM::t2STR_POST
7104                        : StSize == 2 ? ARM::t2STRH_POST
7105                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
7106   return StSize == 4 ? ARM::STR_POST_IMM
7107                      : StSize == 2 ? ARM::STRH_POST
7108                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7109 }
7110
7111 /// Emit a post-increment load operation with given size. The instructions
7112 /// will be added to BB at Pos.
7113 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7114                        const TargetInstrInfo *TII, DebugLoc dl,
7115                        unsigned LdSize, unsigned Data, unsigned AddrIn,
7116                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7117   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7118   assert(LdOpc != 0 && "Should have a load opcode");
7119   if (LdSize >= 8) {
7120     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7121                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7122                        .addImm(0));
7123   } else if (IsThumb1) {
7124     // load + update AddrIn
7125     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7126                        .addReg(AddrIn).addImm(0));
7127     MachineInstrBuilder MIB =
7128         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7129     MIB = AddDefaultT1CC(MIB);
7130     MIB.addReg(AddrIn).addImm(LdSize);
7131     AddDefaultPred(MIB);
7132   } else if (IsThumb2) {
7133     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7134                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7135                        .addImm(LdSize));
7136   } else { // arm
7137     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7138                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7139                        .addReg(0).addImm(LdSize));
7140   }
7141 }
7142
7143 /// Emit a post-increment store operation with given size. The instructions
7144 /// will be added to BB at Pos.
7145 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7146                        const TargetInstrInfo *TII, DebugLoc dl,
7147                        unsigned StSize, unsigned Data, unsigned AddrIn,
7148                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7149   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7150   assert(StOpc != 0 && "Should have a store opcode");
7151   if (StSize >= 8) {
7152     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7153                        .addReg(AddrIn).addImm(0).addReg(Data));
7154   } else if (IsThumb1) {
7155     // store + update AddrIn
7156     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7157                        .addReg(AddrIn).addImm(0));
7158     MachineInstrBuilder MIB =
7159         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7160     MIB = AddDefaultT1CC(MIB);
7161     MIB.addReg(AddrIn).addImm(StSize);
7162     AddDefaultPred(MIB);
7163   } else if (IsThumb2) {
7164     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7165                        .addReg(Data).addReg(AddrIn).addImm(StSize));
7166   } else { // arm
7167     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7168                        .addReg(Data).addReg(AddrIn).addReg(0)
7169                        .addImm(StSize));
7170   }
7171 }
7172
7173 MachineBasicBlock *
7174 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7175                                    MachineBasicBlock *BB) const {
7176   // This pseudo instruction has 3 operands: dst, src, size
7177   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7178   // Otherwise, we will generate unrolled scalar copies.
7179   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7180   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7181   MachineFunction::iterator It = BB;
7182   ++It;
7183
7184   unsigned dest = MI->getOperand(0).getReg();
7185   unsigned src = MI->getOperand(1).getReg();
7186   unsigned SizeVal = MI->getOperand(2).getImm();
7187   unsigned Align = MI->getOperand(3).getImm();
7188   DebugLoc dl = MI->getDebugLoc();
7189
7190   MachineFunction *MF = BB->getParent();
7191   MachineRegisterInfo &MRI = MF->getRegInfo();
7192   unsigned UnitSize = 0;
7193   const TargetRegisterClass *TRC = nullptr;
7194   const TargetRegisterClass *VecTRC = nullptr;
7195
7196   bool IsThumb1 = Subtarget->isThumb1Only();
7197   bool IsThumb2 = Subtarget->isThumb2();
7198
7199   if (Align & 1) {
7200     UnitSize = 1;
7201   } else if (Align & 2) {
7202     UnitSize = 2;
7203   } else {
7204     // Check whether we can use NEON instructions.
7205     if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
7206         Subtarget->hasNEON()) {
7207       if ((Align % 16 == 0) && SizeVal >= 16)
7208         UnitSize = 16;
7209       else if ((Align % 8 == 0) && SizeVal >= 8)
7210         UnitSize = 8;
7211     }
7212     // Can't use NEON instructions.
7213     if (UnitSize == 0)
7214       UnitSize = 4;
7215   }
7216
7217   // Select the correct opcode and register class for unit size load/store
7218   bool IsNeon = UnitSize >= 8;
7219   TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
7220   if (IsNeon)
7221     VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
7222                             : UnitSize == 8 ? &ARM::DPRRegClass
7223                                             : nullptr;
7224
7225   unsigned BytesLeft = SizeVal % UnitSize;
7226   unsigned LoopSize = SizeVal - BytesLeft;
7227
7228   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7229     // Use LDR and STR to copy.
7230     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7231     // [destOut] = STR_POST(scratch, destIn, UnitSize)
7232     unsigned srcIn = src;
7233     unsigned destIn = dest;
7234     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7235       unsigned srcOut = MRI.createVirtualRegister(TRC);
7236       unsigned destOut = MRI.createVirtualRegister(TRC);
7237       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7238       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7239                  IsThumb1, IsThumb2);
7240       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7241                  IsThumb1, IsThumb2);
7242       srcIn = srcOut;
7243       destIn = destOut;
7244     }
7245
7246     // Handle the leftover bytes with LDRB and STRB.
7247     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7248     // [destOut] = STRB_POST(scratch, destIn, 1)
7249     for (unsigned i = 0; i < BytesLeft; i++) {
7250       unsigned srcOut = MRI.createVirtualRegister(TRC);
7251       unsigned destOut = MRI.createVirtualRegister(TRC);
7252       unsigned scratch = MRI.createVirtualRegister(TRC);
7253       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7254                  IsThumb1, IsThumb2);
7255       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7256                  IsThumb1, IsThumb2);
7257       srcIn = srcOut;
7258       destIn = destOut;
7259     }
7260     MI->eraseFromParent();   // The instruction is gone now.
7261     return BB;
7262   }
7263
7264   // Expand the pseudo op to a loop.
7265   // thisMBB:
7266   //   ...
7267   //   movw varEnd, # --> with thumb2
7268   //   movt varEnd, #
7269   //   ldrcp varEnd, idx --> without thumb2
7270   //   fallthrough --> loopMBB
7271   // loopMBB:
7272   //   PHI varPhi, varEnd, varLoop
7273   //   PHI srcPhi, src, srcLoop
7274   //   PHI destPhi, dst, destLoop
7275   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7276   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7277   //   subs varLoop, varPhi, #UnitSize
7278   //   bne loopMBB
7279   //   fallthrough --> exitMBB
7280   // exitMBB:
7281   //   epilogue to handle left-over bytes
7282   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7283   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7284   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7285   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7286   MF->insert(It, loopMBB);
7287   MF->insert(It, exitMBB);
7288
7289   // Transfer the remainder of BB and its successor edges to exitMBB.
7290   exitMBB->splice(exitMBB->begin(), BB,
7291                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7292   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7293
7294   // Load an immediate to varEnd.
7295   unsigned varEnd = MRI.createVirtualRegister(TRC);
7296   if (Subtarget->useMovt(*MF)) {
7297     unsigned Vtmp = varEnd;
7298     if ((LoopSize & 0xFFFF0000) != 0)
7299       Vtmp = MRI.createVirtualRegister(TRC);
7300     AddDefaultPred(BuildMI(BB, dl,
7301                            TII->get(IsThumb2 ? ARM::t2MOVi16 : ARM::MOVi16),
7302                            Vtmp).addImm(LoopSize & 0xFFFF));
7303
7304     if ((LoopSize & 0xFFFF0000) != 0)
7305       AddDefaultPred(BuildMI(BB, dl,
7306                              TII->get(IsThumb2 ? ARM::t2MOVTi16 : ARM::MOVTi16),
7307                              varEnd)
7308                          .addReg(Vtmp)
7309                          .addImm(LoopSize >> 16));
7310   } else {
7311     MachineConstantPool *ConstantPool = MF->getConstantPool();
7312     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7313     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7314
7315     // MachineConstantPool wants an explicit alignment.
7316     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7317     if (Align == 0)
7318       Align = getDataLayout()->getTypeAllocSize(C->getType());
7319     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7320
7321     if (IsThumb1)
7322       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7323           varEnd, RegState::Define).addConstantPoolIndex(Idx));
7324     else
7325       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7326           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7327   }
7328   BB->addSuccessor(loopMBB);
7329
7330   // Generate the loop body:
7331   //   varPhi = PHI(varLoop, varEnd)
7332   //   srcPhi = PHI(srcLoop, src)
7333   //   destPhi = PHI(destLoop, dst)
7334   MachineBasicBlock *entryBB = BB;
7335   BB = loopMBB;
7336   unsigned varLoop = MRI.createVirtualRegister(TRC);
7337   unsigned varPhi = MRI.createVirtualRegister(TRC);
7338   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7339   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7340   unsigned destLoop = MRI.createVirtualRegister(TRC);
7341   unsigned destPhi = MRI.createVirtualRegister(TRC);
7342
7343   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7344     .addReg(varLoop).addMBB(loopMBB)
7345     .addReg(varEnd).addMBB(entryBB);
7346   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7347     .addReg(srcLoop).addMBB(loopMBB)
7348     .addReg(src).addMBB(entryBB);
7349   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7350     .addReg(destLoop).addMBB(loopMBB)
7351     .addReg(dest).addMBB(entryBB);
7352
7353   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7354   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7355   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7356   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7357              IsThumb1, IsThumb2);
7358   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7359              IsThumb1, IsThumb2);
7360
7361   // Decrement loop variable by UnitSize.
7362   if (IsThumb1) {
7363     MachineInstrBuilder MIB =
7364         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7365     MIB = AddDefaultT1CC(MIB);
7366     MIB.addReg(varPhi).addImm(UnitSize);
7367     AddDefaultPred(MIB);
7368   } else {
7369     MachineInstrBuilder MIB =
7370         BuildMI(*BB, BB->end(), dl,
7371                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7372     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7373     MIB->getOperand(5).setReg(ARM::CPSR);
7374     MIB->getOperand(5).setIsDef(true);
7375   }
7376   BuildMI(*BB, BB->end(), dl,
7377           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7378       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7379
7380   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7381   BB->addSuccessor(loopMBB);
7382   BB->addSuccessor(exitMBB);
7383
7384   // Add epilogue to handle BytesLeft.
7385   BB = exitMBB;
7386   MachineInstr *StartOfExit = exitMBB->begin();
7387
7388   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7389   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7390   unsigned srcIn = srcLoop;
7391   unsigned destIn = destLoop;
7392   for (unsigned i = 0; i < BytesLeft; i++) {
7393     unsigned srcOut = MRI.createVirtualRegister(TRC);
7394     unsigned destOut = MRI.createVirtualRegister(TRC);
7395     unsigned scratch = MRI.createVirtualRegister(TRC);
7396     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7397                IsThumb1, IsThumb2);
7398     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7399                IsThumb1, IsThumb2);
7400     srcIn = srcOut;
7401     destIn = destOut;
7402   }
7403
7404   MI->eraseFromParent();   // The instruction is gone now.
7405   return BB;
7406 }
7407
7408 MachineBasicBlock *
7409 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7410                                        MachineBasicBlock *MBB) const {
7411   const TargetMachine &TM = getTargetMachine();
7412   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
7413   DebugLoc DL = MI->getDebugLoc();
7414
7415   assert(Subtarget->isTargetWindows() &&
7416          "__chkstk is only supported on Windows");
7417   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7418
7419   // __chkstk takes the number of words to allocate on the stack in R4, and
7420   // returns the stack adjustment in number of bytes in R4.  This will not
7421   // clober any other registers (other than the obvious lr).
7422   //
7423   // Although, technically, IP should be considered a register which may be
7424   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
7425   // thumb-2 environment, so there is no interworking required.  As a result, we
7426   // do not expect a veneer to be emitted by the linker, clobbering IP.
7427   //
7428   // Each module receives its own copy of __chkstk, so no import thunk is
7429   // required, again, ensuring that IP is not clobbered.
7430   //
7431   // Finally, although some linkers may theoretically provide a trampoline for
7432   // out of range calls (which is quite common due to a 32M range limitation of
7433   // branches for Thumb), we can generate the long-call version via
7434   // -mcmodel=large, alleviating the need for the trampoline which may clobber
7435   // IP.
7436
7437   switch (TM.getCodeModel()) {
7438   case CodeModel::Small:
7439   case CodeModel::Medium:
7440   case CodeModel::Default:
7441   case CodeModel::Kernel:
7442     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7443       .addImm((unsigned)ARMCC::AL).addReg(0)
7444       .addExternalSymbol("__chkstk")
7445       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7446       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7447       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7448     break;
7449   case CodeModel::Large:
7450   case CodeModel::JITDefault: {
7451     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7452     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7453
7454     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7455       .addExternalSymbol("__chkstk");
7456     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7457       .addImm((unsigned)ARMCC::AL).addReg(0)
7458       .addReg(Reg, RegState::Kill)
7459       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7460       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7461       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7462     break;
7463   }
7464   }
7465
7466   AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7467                                       ARM::SP)
7468                               .addReg(ARM::SP).addReg(ARM::R4)));
7469
7470   MI->eraseFromParent();
7471   return MBB;
7472 }
7473
7474 MachineBasicBlock *
7475 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7476                                                MachineBasicBlock *BB) const {
7477   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7478   DebugLoc dl = MI->getDebugLoc();
7479   bool isThumb2 = Subtarget->isThumb2();
7480   switch (MI->getOpcode()) {
7481   default: {
7482     MI->dump();
7483     llvm_unreachable("Unexpected instr type to insert");
7484   }
7485   // The Thumb2 pre-indexed stores have the same MI operands, they just
7486   // define them differently in the .td files from the isel patterns, so
7487   // they need pseudos.
7488   case ARM::t2STR_preidx:
7489     MI->setDesc(TII->get(ARM::t2STR_PRE));
7490     return BB;
7491   case ARM::t2STRB_preidx:
7492     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7493     return BB;
7494   case ARM::t2STRH_preidx:
7495     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7496     return BB;
7497
7498   case ARM::STRi_preidx:
7499   case ARM::STRBi_preidx: {
7500     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7501       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7502     // Decode the offset.
7503     unsigned Offset = MI->getOperand(4).getImm();
7504     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7505     Offset = ARM_AM::getAM2Offset(Offset);
7506     if (isSub)
7507       Offset = -Offset;
7508
7509     MachineMemOperand *MMO = *MI->memoperands_begin();
7510     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7511       .addOperand(MI->getOperand(0))  // Rn_wb
7512       .addOperand(MI->getOperand(1))  // Rt
7513       .addOperand(MI->getOperand(2))  // Rn
7514       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7515       .addOperand(MI->getOperand(5))  // pred
7516       .addOperand(MI->getOperand(6))
7517       .addMemOperand(MMO);
7518     MI->eraseFromParent();
7519     return BB;
7520   }
7521   case ARM::STRr_preidx:
7522   case ARM::STRBr_preidx:
7523   case ARM::STRH_preidx: {
7524     unsigned NewOpc;
7525     switch (MI->getOpcode()) {
7526     default: llvm_unreachable("unexpected opcode!");
7527     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7528     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7529     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7530     }
7531     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7532     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7533       MIB.addOperand(MI->getOperand(i));
7534     MI->eraseFromParent();
7535     return BB;
7536   }
7537
7538   case ARM::tMOVCCr_pseudo: {
7539     // To "insert" a SELECT_CC instruction, we actually have to insert the
7540     // diamond control-flow pattern.  The incoming instruction knows the
7541     // destination vreg to set, the condition code register to branch on, the
7542     // true/false values to select between, and a branch opcode to use.
7543     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7544     MachineFunction::iterator It = BB;
7545     ++It;
7546
7547     //  thisMBB:
7548     //  ...
7549     //   TrueVal = ...
7550     //   cmpTY ccX, r1, r2
7551     //   bCC copy1MBB
7552     //   fallthrough --> copy0MBB
7553     MachineBasicBlock *thisMBB  = BB;
7554     MachineFunction *F = BB->getParent();
7555     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7556     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7557     F->insert(It, copy0MBB);
7558     F->insert(It, sinkMBB);
7559
7560     // Transfer the remainder of BB and its successor edges to sinkMBB.
7561     sinkMBB->splice(sinkMBB->begin(), BB,
7562                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7563     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7564
7565     BB->addSuccessor(copy0MBB);
7566     BB->addSuccessor(sinkMBB);
7567
7568     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7569       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7570
7571     //  copy0MBB:
7572     //   %FalseValue = ...
7573     //   # fallthrough to sinkMBB
7574     BB = copy0MBB;
7575
7576     // Update machine-CFG edges
7577     BB->addSuccessor(sinkMBB);
7578
7579     //  sinkMBB:
7580     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7581     //  ...
7582     BB = sinkMBB;
7583     BuildMI(*BB, BB->begin(), dl,
7584             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7585       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7586       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7587
7588     MI->eraseFromParent();   // The pseudo instruction is gone now.
7589     return BB;
7590   }
7591
7592   case ARM::BCCi64:
7593   case ARM::BCCZi64: {
7594     // If there is an unconditional branch to the other successor, remove it.
7595     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7596
7597     // Compare both parts that make up the double comparison separately for
7598     // equality.
7599     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7600
7601     unsigned LHS1 = MI->getOperand(1).getReg();
7602     unsigned LHS2 = MI->getOperand(2).getReg();
7603     if (RHSisZero) {
7604       AddDefaultPred(BuildMI(BB, dl,
7605                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7606                      .addReg(LHS1).addImm(0));
7607       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7608         .addReg(LHS2).addImm(0)
7609         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7610     } else {
7611       unsigned RHS1 = MI->getOperand(3).getReg();
7612       unsigned RHS2 = MI->getOperand(4).getReg();
7613       AddDefaultPred(BuildMI(BB, dl,
7614                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7615                      .addReg(LHS1).addReg(RHS1));
7616       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7617         .addReg(LHS2).addReg(RHS2)
7618         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7619     }
7620
7621     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7622     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7623     if (MI->getOperand(0).getImm() == ARMCC::NE)
7624       std::swap(destMBB, exitMBB);
7625
7626     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7627       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7628     if (isThumb2)
7629       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7630     else
7631       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7632
7633     MI->eraseFromParent();   // The pseudo instruction is gone now.
7634     return BB;
7635   }
7636
7637   case ARM::Int_eh_sjlj_setjmp:
7638   case ARM::Int_eh_sjlj_setjmp_nofp:
7639   case ARM::tInt_eh_sjlj_setjmp:
7640   case ARM::t2Int_eh_sjlj_setjmp:
7641   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7642     EmitSjLjDispatchBlock(MI, BB);
7643     return BB;
7644
7645   case ARM::ABS:
7646   case ARM::t2ABS: {
7647     // To insert an ABS instruction, we have to insert the
7648     // diamond control-flow pattern.  The incoming instruction knows the
7649     // source vreg to test against 0, the destination vreg to set,
7650     // the condition code register to branch on, the
7651     // true/false values to select between, and a branch opcode to use.
7652     // It transforms
7653     //     V1 = ABS V0
7654     // into
7655     //     V2 = MOVS V0
7656     //     BCC                      (branch to SinkBB if V0 >= 0)
7657     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7658     //     SinkBB: V1 = PHI(V2, V3)
7659     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7660     MachineFunction::iterator BBI = BB;
7661     ++BBI;
7662     MachineFunction *Fn = BB->getParent();
7663     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7664     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7665     Fn->insert(BBI, RSBBB);
7666     Fn->insert(BBI, SinkBB);
7667
7668     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7669     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7670     bool ABSSrcKIll = MI->getOperand(1).isKill();
7671     bool isThumb2 = Subtarget->isThumb2();
7672     MachineRegisterInfo &MRI = Fn->getRegInfo();
7673     // In Thumb mode S must not be specified if source register is the SP or
7674     // PC and if destination register is the SP, so restrict register class
7675     unsigned NewRsbDstReg =
7676       MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
7677
7678     // Transfer the remainder of BB and its successor edges to sinkMBB.
7679     SinkBB->splice(SinkBB->begin(), BB,
7680                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
7681     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7682
7683     BB->addSuccessor(RSBBB);
7684     BB->addSuccessor(SinkBB);
7685
7686     // fall through to SinkMBB
7687     RSBBB->addSuccessor(SinkBB);
7688
7689     // insert a cmp at the end of BB
7690     AddDefaultPred(BuildMI(BB, dl,
7691                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7692                    .addReg(ABSSrcReg).addImm(0));
7693
7694     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7695     BuildMI(BB, dl,
7696       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7697       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7698
7699     // insert rsbri in RSBBB
7700     // Note: BCC and rsbri will be converted into predicated rsbmi
7701     // by if-conversion pass
7702     BuildMI(*RSBBB, RSBBB->begin(), dl,
7703       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7704       .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
7705       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7706
7707     // insert PHI in SinkBB,
7708     // reuse ABSDstReg to not change uses of ABS instruction
7709     BuildMI(*SinkBB, SinkBB->begin(), dl,
7710       TII->get(ARM::PHI), ABSDstReg)
7711       .addReg(NewRsbDstReg).addMBB(RSBBB)
7712       .addReg(ABSSrcReg).addMBB(BB);
7713
7714     // remove ABS instruction
7715     MI->eraseFromParent();
7716
7717     // return last added BB
7718     return SinkBB;
7719   }
7720   case ARM::COPY_STRUCT_BYVAL_I32:
7721     ++NumLoopByVals;
7722     return EmitStructByval(MI, BB);
7723   case ARM::WIN__CHKSTK:
7724     return EmitLowered__chkstk(MI, BB);
7725   }
7726 }
7727
7728 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7729                                                       SDNode *Node) const {
7730   const MCInstrDesc *MCID = &MI->getDesc();
7731   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7732   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7733   // operand is still set to noreg. If needed, set the optional operand's
7734   // register to CPSR, and remove the redundant implicit def.
7735   //
7736   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7737
7738   // Rename pseudo opcodes.
7739   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7740   if (NewOpc) {
7741     const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
7742     MCID = &TII->get(NewOpc);
7743
7744     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7745            "converted opcode should be the same except for cc_out");
7746
7747     MI->setDesc(*MCID);
7748
7749     // Add the optional cc_out operand
7750     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7751   }
7752   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7753
7754   // Any ARM instruction that sets the 's' bit should specify an optional
7755   // "cc_out" operand in the last operand position.
7756   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7757     assert(!NewOpc && "Optional cc_out operand required");
7758     return;
7759   }
7760   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7761   // since we already have an optional CPSR def.
7762   bool definesCPSR = false;
7763   bool deadCPSR = false;
7764   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7765        i != e; ++i) {
7766     const MachineOperand &MO = MI->getOperand(i);
7767     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7768       definesCPSR = true;
7769       if (MO.isDead())
7770         deadCPSR = true;
7771       MI->RemoveOperand(i);
7772       break;
7773     }
7774   }
7775   if (!definesCPSR) {
7776     assert(!NewOpc && "Optional cc_out operand required");
7777     return;
7778   }
7779   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7780   if (deadCPSR) {
7781     assert(!MI->getOperand(ccOutIdx).getReg() &&
7782            "expect uninitialized optional cc_out operand");
7783     return;
7784   }
7785
7786   // If this instruction was defined with an optional CPSR def and its dag node
7787   // had a live implicit CPSR def, then activate the optional CPSR def.
7788   MachineOperand &MO = MI->getOperand(ccOutIdx);
7789   MO.setReg(ARM::CPSR);
7790   MO.setIsDef(true);
7791 }
7792
7793 //===----------------------------------------------------------------------===//
7794 //                           ARM Optimization Hooks
7795 //===----------------------------------------------------------------------===//
7796
7797 // Helper function that checks if N is a null or all ones constant.
7798 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7799   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7800   if (!C)
7801     return false;
7802   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7803 }
7804
7805 // Return true if N is conditionally 0 or all ones.
7806 // Detects these expressions where cc is an i1 value:
7807 //
7808 //   (select cc 0, y)   [AllOnes=0]
7809 //   (select cc y, 0)   [AllOnes=0]
7810 //   (zext cc)          [AllOnes=0]
7811 //   (sext cc)          [AllOnes=0/1]
7812 //   (select cc -1, y)  [AllOnes=1]
7813 //   (select cc y, -1)  [AllOnes=1]
7814 //
7815 // Invert is set when N is the null/all ones constant when CC is false.
7816 // OtherOp is set to the alternative value of N.
7817 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7818                                        SDValue &CC, bool &Invert,
7819                                        SDValue &OtherOp,
7820                                        SelectionDAG &DAG) {
7821   switch (N->getOpcode()) {
7822   default: return false;
7823   case ISD::SELECT: {
7824     CC = N->getOperand(0);
7825     SDValue N1 = N->getOperand(1);
7826     SDValue N2 = N->getOperand(2);
7827     if (isZeroOrAllOnes(N1, AllOnes)) {
7828       Invert = false;
7829       OtherOp = N2;
7830       return true;
7831     }
7832     if (isZeroOrAllOnes(N2, AllOnes)) {
7833       Invert = true;
7834       OtherOp = N1;
7835       return true;
7836     }
7837     return false;
7838   }
7839   case ISD::ZERO_EXTEND:
7840     // (zext cc) can never be the all ones value.
7841     if (AllOnes)
7842       return false;
7843     // Fall through.
7844   case ISD::SIGN_EXTEND: {
7845     SDLoc dl(N);
7846     EVT VT = N->getValueType(0);
7847     CC = N->getOperand(0);
7848     if (CC.getValueType() != MVT::i1)
7849       return false;
7850     Invert = !AllOnes;
7851     if (AllOnes)
7852       // When looking for an AllOnes constant, N is an sext, and the 'other'
7853       // value is 0.
7854       OtherOp = DAG.getConstant(0, dl, VT);
7855     else if (N->getOpcode() == ISD::ZERO_EXTEND)
7856       // When looking for a 0 constant, N can be zext or sext.
7857       OtherOp = DAG.getConstant(1, dl, VT);
7858     else
7859       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
7860                                 VT);
7861     return true;
7862   }
7863   }
7864 }
7865
7866 // Combine a constant select operand into its use:
7867 //
7868 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
7869 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
7870 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
7871 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
7872 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
7873 //
7874 // The transform is rejected if the select doesn't have a constant operand that
7875 // is null, or all ones when AllOnes is set.
7876 //
7877 // Also recognize sext/zext from i1:
7878 //
7879 //   (add (zext cc), x) -> (select cc (add x, 1), x)
7880 //   (add (sext cc), x) -> (select cc (add x, -1), x)
7881 //
7882 // These transformations eventually create predicated instructions.
7883 //
7884 // @param N       The node to transform.
7885 // @param Slct    The N operand that is a select.
7886 // @param OtherOp The other N operand (x above).
7887 // @param DCI     Context.
7888 // @param AllOnes Require the select constant to be all ones instead of null.
7889 // @returns The new node, or SDValue() on failure.
7890 static
7891 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7892                             TargetLowering::DAGCombinerInfo &DCI,
7893                             bool AllOnes = false) {
7894   SelectionDAG &DAG = DCI.DAG;
7895   EVT VT = N->getValueType(0);
7896   SDValue NonConstantVal;
7897   SDValue CCOp;
7898   bool SwapSelectOps;
7899   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7900                                   NonConstantVal, DAG))
7901     return SDValue();
7902
7903   // Slct is now know to be the desired identity constant when CC is true.
7904   SDValue TrueVal = OtherOp;
7905   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7906                                  OtherOp, NonConstantVal);
7907   // Unless SwapSelectOps says CC should be false.
7908   if (SwapSelectOps)
7909     std::swap(TrueVal, FalseVal);
7910
7911   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7912                      CCOp, TrueVal, FalseVal);
7913 }
7914
7915 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7916 static
7917 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7918                                        TargetLowering::DAGCombinerInfo &DCI) {
7919   SDValue N0 = N->getOperand(0);
7920   SDValue N1 = N->getOperand(1);
7921   if (N0.getNode()->hasOneUse()) {
7922     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7923     if (Result.getNode())
7924       return Result;
7925   }
7926   if (N1.getNode()->hasOneUse()) {
7927     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7928     if (Result.getNode())
7929       return Result;
7930   }
7931   return SDValue();
7932 }
7933
7934 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7935 // (only after legalization).
7936 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7937                                  TargetLowering::DAGCombinerInfo &DCI,
7938                                  const ARMSubtarget *Subtarget) {
7939
7940   // Only perform optimization if after legalize, and if NEON is available. We
7941   // also expected both operands to be BUILD_VECTORs.
7942   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7943       || N0.getOpcode() != ISD::BUILD_VECTOR
7944       || N1.getOpcode() != ISD::BUILD_VECTOR)
7945     return SDValue();
7946
7947   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7948   EVT VT = N->getValueType(0);
7949   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7950     return SDValue();
7951
7952   // Check that the vector operands are of the right form.
7953   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7954   // operands, where N is the size of the formed vector.
7955   // Each EXTRACT_VECTOR should have the same input vector and odd or even
7956   // index such that we have a pair wise add pattern.
7957
7958   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7959   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7960     return SDValue();
7961   SDValue Vec = N0->getOperand(0)->getOperand(0);
7962   SDNode *V = Vec.getNode();
7963   unsigned nextIndex = 0;
7964
7965   // For each operands to the ADD which are BUILD_VECTORs,
7966   // check to see if each of their operands are an EXTRACT_VECTOR with
7967   // the same vector and appropriate index.
7968   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7969     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7970         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7971
7972       SDValue ExtVec0 = N0->getOperand(i);
7973       SDValue ExtVec1 = N1->getOperand(i);
7974
7975       // First operand is the vector, verify its the same.
7976       if (V != ExtVec0->getOperand(0).getNode() ||
7977           V != ExtVec1->getOperand(0).getNode())
7978         return SDValue();
7979
7980       // Second is the constant, verify its correct.
7981       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7982       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7983
7984       // For the constant, we want to see all the even or all the odd.
7985       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7986           || C1->getZExtValue() != nextIndex+1)
7987         return SDValue();
7988
7989       // Increment index.
7990       nextIndex+=2;
7991     } else
7992       return SDValue();
7993   }
7994
7995   // Create VPADDL node.
7996   SelectionDAG &DAG = DCI.DAG;
7997   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7998
7999   SDLoc dl(N);
8000
8001   // Build operand list.
8002   SmallVector<SDValue, 8> Ops;
8003   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
8004                                 TLI.getPointerTy(DAG.getDataLayout())));
8005
8006   // Input is the vector.
8007   Ops.push_back(Vec);
8008
8009   // Get widened type and narrowed type.
8010   MVT widenType;
8011   unsigned numElem = VT.getVectorNumElements();
8012   
8013   EVT inputLaneType = Vec.getValueType().getVectorElementType();
8014   switch (inputLaneType.getSimpleVT().SimpleTy) {
8015     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
8016     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
8017     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
8018     default:
8019       llvm_unreachable("Invalid vector element type for padd optimization.");
8020   }
8021
8022   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
8023   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
8024   return DAG.getNode(ExtOp, dl, VT, tmp);
8025 }
8026
8027 static SDValue findMUL_LOHI(SDValue V) {
8028   if (V->getOpcode() == ISD::UMUL_LOHI ||
8029       V->getOpcode() == ISD::SMUL_LOHI)
8030     return V;
8031   return SDValue();
8032 }
8033
8034 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
8035                                      TargetLowering::DAGCombinerInfo &DCI,
8036                                      const ARMSubtarget *Subtarget) {
8037
8038   if (Subtarget->isThumb1Only()) return SDValue();
8039
8040   // Only perform the checks after legalize when the pattern is available.
8041   if (DCI.isBeforeLegalize()) return SDValue();
8042
8043   // Look for multiply add opportunities.
8044   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8045   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8046   // a glue link from the first add to the second add.
8047   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8048   // a S/UMLAL instruction.
8049   //                  UMUL_LOHI
8050   //                 / :lo    \ :hi
8051   //                /          \          [no multiline comment]
8052   //    loAdd ->  ADDE         |
8053   //                 \ :glue  /
8054   //                  \      /
8055   //                    ADDC   <- hiAdd
8056   //
8057   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8058   SDValue AddcOp0 = AddcNode->getOperand(0);
8059   SDValue AddcOp1 = AddcNode->getOperand(1);
8060
8061   // Check if the two operands are from the same mul_lohi node.
8062   if (AddcOp0.getNode() == AddcOp1.getNode())
8063     return SDValue();
8064
8065   assert(AddcNode->getNumValues() == 2 &&
8066          AddcNode->getValueType(0) == MVT::i32 &&
8067          "Expect ADDC with two result values. First: i32");
8068
8069   // Check that we have a glued ADDC node.
8070   if (AddcNode->getValueType(1) != MVT::Glue)
8071     return SDValue();
8072
8073   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8074   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8075       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8076       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8077       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8078     return SDValue();
8079
8080   // Look for the glued ADDE.
8081   SDNode* AddeNode = AddcNode->getGluedUser();
8082   if (!AddeNode)
8083     return SDValue();
8084
8085   // Make sure it is really an ADDE.
8086   if (AddeNode->getOpcode() != ISD::ADDE)
8087     return SDValue();
8088
8089   assert(AddeNode->getNumOperands() == 3 &&
8090          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8091          "ADDE node has the wrong inputs");
8092
8093   // Check for the triangle shape.
8094   SDValue AddeOp0 = AddeNode->getOperand(0);
8095   SDValue AddeOp1 = AddeNode->getOperand(1);
8096
8097   // Make sure that the ADDE operands are not coming from the same node.
8098   if (AddeOp0.getNode() == AddeOp1.getNode())
8099     return SDValue();
8100
8101   // Find the MUL_LOHI node walking up ADDE's operands.
8102   bool IsLeftOperandMUL = false;
8103   SDValue MULOp = findMUL_LOHI(AddeOp0);
8104   if (MULOp == SDValue())
8105    MULOp = findMUL_LOHI(AddeOp1);
8106   else
8107     IsLeftOperandMUL = true;
8108   if (MULOp == SDValue())
8109     return SDValue();
8110
8111   // Figure out the right opcode.
8112   unsigned Opc = MULOp->getOpcode();
8113   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8114
8115   // Figure out the high and low input values to the MLAL node.
8116   SDValue* HiAdd = nullptr;
8117   SDValue* LoMul = nullptr;
8118   SDValue* LowAdd = nullptr;
8119
8120   // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
8121   if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
8122     return SDValue();
8123
8124   if (IsLeftOperandMUL)
8125     HiAdd = &AddeOp1;
8126   else
8127     HiAdd = &AddeOp0;
8128
8129
8130   // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
8131   // whose low result is fed to the ADDC we are checking.
8132
8133   if (AddcOp0 == MULOp.getValue(0)) {
8134     LoMul = &AddcOp0;
8135     LowAdd = &AddcOp1;
8136   }
8137   if (AddcOp1 == MULOp.getValue(0)) {
8138     LoMul = &AddcOp1;
8139     LowAdd = &AddcOp0;
8140   }
8141
8142   if (!LoMul)
8143     return SDValue();
8144
8145   // Create the merged node.
8146   SelectionDAG &DAG = DCI.DAG;
8147
8148   // Build operand list.
8149   SmallVector<SDValue, 8> Ops;
8150   Ops.push_back(LoMul->getOperand(0));
8151   Ops.push_back(LoMul->getOperand(1));
8152   Ops.push_back(*LowAdd);
8153   Ops.push_back(*HiAdd);
8154
8155   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
8156                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
8157
8158   // Replace the ADDs' nodes uses by the MLA node's values.
8159   SDValue HiMLALResult(MLALNode.getNode(), 1);
8160   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8161
8162   SDValue LoMLALResult(MLALNode.getNode(), 0);
8163   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8164
8165   // Return original node to notify the driver to stop replacing.
8166   SDValue resNode(AddcNode, 0);
8167   return resNode;
8168 }
8169
8170 /// PerformADDCCombine - Target-specific dag combine transform from
8171 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8172 static SDValue PerformADDCCombine(SDNode *N,
8173                                  TargetLowering::DAGCombinerInfo &DCI,
8174                                  const ARMSubtarget *Subtarget) {
8175
8176   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8177
8178 }
8179
8180 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8181 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
8182 /// called with the default operands, and if that fails, with commuted
8183 /// operands.
8184 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8185                                           TargetLowering::DAGCombinerInfo &DCI,
8186                                           const ARMSubtarget *Subtarget){
8187
8188   // Attempt to create vpaddl for this add.
8189   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8190   if (Result.getNode())
8191     return Result;
8192
8193   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8194   if (N0.getNode()->hasOneUse()) {
8195     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8196     if (Result.getNode()) return Result;
8197   }
8198   return SDValue();
8199 }
8200
8201 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8202 ///
8203 static SDValue PerformADDCombine(SDNode *N,
8204                                  TargetLowering::DAGCombinerInfo &DCI,
8205                                  const ARMSubtarget *Subtarget) {
8206   SDValue N0 = N->getOperand(0);
8207   SDValue N1 = N->getOperand(1);
8208
8209   // First try with the default operand order.
8210   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8211   if (Result.getNode())
8212     return Result;
8213
8214   // If that didn't work, try again with the operands commuted.
8215   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8216 }
8217
8218 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8219 ///
8220 static SDValue PerformSUBCombine(SDNode *N,
8221                                  TargetLowering::DAGCombinerInfo &DCI) {
8222   SDValue N0 = N->getOperand(0);
8223   SDValue N1 = N->getOperand(1);
8224
8225   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8226   if (N1.getNode()->hasOneUse()) {
8227     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8228     if (Result.getNode()) return Result;
8229   }
8230
8231   return SDValue();
8232 }
8233
8234 /// PerformVMULCombine
8235 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8236 /// special multiplier accumulator forwarding.
8237 ///   vmul d3, d0, d2
8238 ///   vmla d3, d1, d2
8239 /// is faster than
8240 ///   vadd d3, d0, d1
8241 ///   vmul d3, d3, d2
8242 //  However, for (A + B) * (A + B),
8243 //    vadd d2, d0, d1
8244 //    vmul d3, d0, d2
8245 //    vmla d3, d1, d2
8246 //  is slower than
8247 //    vadd d2, d0, d1
8248 //    vmul d3, d2, d2
8249 static SDValue PerformVMULCombine(SDNode *N,
8250                                   TargetLowering::DAGCombinerInfo &DCI,
8251                                   const ARMSubtarget *Subtarget) {
8252   if (!Subtarget->hasVMLxForwarding())
8253     return SDValue();
8254
8255   SelectionDAG &DAG = DCI.DAG;
8256   SDValue N0 = N->getOperand(0);
8257   SDValue N1 = N->getOperand(1);
8258   unsigned Opcode = N0.getOpcode();
8259   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8260       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8261     Opcode = N1.getOpcode();
8262     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8263         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8264       return SDValue();
8265     std::swap(N0, N1);
8266   }
8267
8268   if (N0 == N1)
8269     return SDValue();
8270
8271   EVT VT = N->getValueType(0);
8272   SDLoc DL(N);
8273   SDValue N00 = N0->getOperand(0);
8274   SDValue N01 = N0->getOperand(1);
8275   return DAG.getNode(Opcode, DL, VT,
8276                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8277                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8278 }
8279
8280 static SDValue PerformMULCombine(SDNode *N,
8281                                  TargetLowering::DAGCombinerInfo &DCI,
8282                                  const ARMSubtarget *Subtarget) {
8283   SelectionDAG &DAG = DCI.DAG;
8284
8285   if (Subtarget->isThumb1Only())
8286     return SDValue();
8287
8288   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8289     return SDValue();
8290
8291   EVT VT = N->getValueType(0);
8292   if (VT.is64BitVector() || VT.is128BitVector())
8293     return PerformVMULCombine(N, DCI, Subtarget);
8294   if (VT != MVT::i32)
8295     return SDValue();
8296
8297   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8298   if (!C)
8299     return SDValue();
8300
8301   int64_t MulAmt = C->getSExtValue();
8302   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8303
8304   ShiftAmt = ShiftAmt & (32 - 1);
8305   SDValue V = N->getOperand(0);
8306   SDLoc DL(N);
8307
8308   SDValue Res;
8309   MulAmt >>= ShiftAmt;
8310
8311   if (MulAmt >= 0) {
8312     if (isPowerOf2_32(MulAmt - 1)) {
8313       // (mul x, 2^N + 1) => (add (shl x, N), x)
8314       Res = DAG.getNode(ISD::ADD, DL, VT,
8315                         V,
8316                         DAG.getNode(ISD::SHL, DL, VT,
8317                                     V,
8318                                     DAG.getConstant(Log2_32(MulAmt - 1), DL,
8319                                                     MVT::i32)));
8320     } else if (isPowerOf2_32(MulAmt + 1)) {
8321       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8322       Res = DAG.getNode(ISD::SUB, DL, VT,
8323                         DAG.getNode(ISD::SHL, DL, VT,
8324                                     V,
8325                                     DAG.getConstant(Log2_32(MulAmt + 1), DL,
8326                                                     MVT::i32)),
8327                         V);
8328     } else
8329       return SDValue();
8330   } else {
8331     uint64_t MulAmtAbs = -MulAmt;
8332     if (isPowerOf2_32(MulAmtAbs + 1)) {
8333       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8334       Res = DAG.getNode(ISD::SUB, DL, VT,
8335                         V,
8336                         DAG.getNode(ISD::SHL, DL, VT,
8337                                     V,
8338                                     DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
8339                                                     MVT::i32)));
8340     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8341       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8342       Res = DAG.getNode(ISD::ADD, DL, VT,
8343                         V,
8344                         DAG.getNode(ISD::SHL, DL, VT,
8345                                     V,
8346                                     DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
8347                                                     MVT::i32)));
8348       Res = DAG.getNode(ISD::SUB, DL, VT,
8349                         DAG.getConstant(0, DL, MVT::i32), Res);
8350
8351     } else
8352       return SDValue();
8353   }
8354
8355   if (ShiftAmt != 0)
8356     Res = DAG.getNode(ISD::SHL, DL, VT,
8357                       Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
8358
8359   // Do not add new nodes to DAG combiner worklist.
8360   DCI.CombineTo(N, Res, false);
8361   return SDValue();
8362 }
8363
8364 static SDValue PerformANDCombine(SDNode *N,
8365                                  TargetLowering::DAGCombinerInfo &DCI,
8366                                  const ARMSubtarget *Subtarget) {
8367
8368   // Attempt to use immediate-form VBIC
8369   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8370   SDLoc dl(N);
8371   EVT VT = N->getValueType(0);
8372   SelectionDAG &DAG = DCI.DAG;
8373
8374   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8375     return SDValue();
8376
8377   APInt SplatBits, SplatUndef;
8378   unsigned SplatBitSize;
8379   bool HasAnyUndefs;
8380   if (BVN &&
8381       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8382     if (SplatBitSize <= 64) {
8383       EVT VbicVT;
8384       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8385                                       SplatUndef.getZExtValue(), SplatBitSize,
8386                                       DAG, dl, VbicVT, VT.is128BitVector(),
8387                                       OtherModImm);
8388       if (Val.getNode()) {
8389         SDValue Input =
8390           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8391         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8392         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8393       }
8394     }
8395   }
8396
8397   if (!Subtarget->isThumb1Only()) {
8398     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8399     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8400     if (Result.getNode())
8401       return Result;
8402   }
8403
8404   return SDValue();
8405 }
8406
8407 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8408 static SDValue PerformORCombine(SDNode *N,
8409                                 TargetLowering::DAGCombinerInfo &DCI,
8410                                 const ARMSubtarget *Subtarget) {
8411   // Attempt to use immediate-form VORR
8412   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8413   SDLoc dl(N);
8414   EVT VT = N->getValueType(0);
8415   SelectionDAG &DAG = DCI.DAG;
8416
8417   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8418     return SDValue();
8419
8420   APInt SplatBits, SplatUndef;
8421   unsigned SplatBitSize;
8422   bool HasAnyUndefs;
8423   if (BVN && Subtarget->hasNEON() &&
8424       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8425     if (SplatBitSize <= 64) {
8426       EVT VorrVT;
8427       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8428                                       SplatUndef.getZExtValue(), SplatBitSize,
8429                                       DAG, dl, VorrVT, VT.is128BitVector(),
8430                                       OtherModImm);
8431       if (Val.getNode()) {
8432         SDValue Input =
8433           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8434         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8435         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8436       }
8437     }
8438   }
8439
8440   if (!Subtarget->isThumb1Only()) {
8441     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8442     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8443     if (Result.getNode())
8444       return Result;
8445   }
8446
8447   // The code below optimizes (or (and X, Y), Z).
8448   // The AND operand needs to have a single user to make these optimizations
8449   // profitable.
8450   SDValue N0 = N->getOperand(0);
8451   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8452     return SDValue();
8453   SDValue N1 = N->getOperand(1);
8454
8455   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8456   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8457       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8458     APInt SplatUndef;
8459     unsigned SplatBitSize;
8460     bool HasAnyUndefs;
8461
8462     APInt SplatBits0, SplatBits1;
8463     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8464     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8465     // Ensure that the second operand of both ands are constants
8466     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8467                                       HasAnyUndefs) && !HasAnyUndefs) {
8468         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8469                                           HasAnyUndefs) && !HasAnyUndefs) {
8470             // Ensure that the bit width of the constants are the same and that
8471             // the splat arguments are logical inverses as per the pattern we
8472             // are trying to simplify.
8473             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8474                 SplatBits0 == ~SplatBits1) {
8475                 // Canonicalize the vector type to make instruction selection
8476                 // simpler.
8477                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8478                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8479                                              N0->getOperand(1),
8480                                              N0->getOperand(0),
8481                                              N1->getOperand(0));
8482                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8483             }
8484         }
8485     }
8486   }
8487
8488   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8489   // reasonable.
8490
8491   // BFI is only available on V6T2+
8492   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8493     return SDValue();
8494
8495   SDLoc DL(N);
8496   // 1) or (and A, mask), val => ARMbfi A, val, mask
8497   //      iff (val & mask) == val
8498   //
8499   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8500   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8501   //          && mask == ~mask2
8502   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8503   //          && ~mask == mask2
8504   //  (i.e., copy a bitfield value into another bitfield of the same width)
8505
8506   if (VT != MVT::i32)
8507     return SDValue();
8508
8509   SDValue N00 = N0.getOperand(0);
8510
8511   // The value and the mask need to be constants so we can verify this is
8512   // actually a bitfield set. If the mask is 0xffff, we can do better
8513   // via a movt instruction, so don't use BFI in that case.
8514   SDValue MaskOp = N0.getOperand(1);
8515   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8516   if (!MaskC)
8517     return SDValue();
8518   unsigned Mask = MaskC->getZExtValue();
8519   if (Mask == 0xffff)
8520     return SDValue();
8521   SDValue Res;
8522   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8523   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8524   if (N1C) {
8525     unsigned Val = N1C->getZExtValue();
8526     if ((Val & ~Mask) != Val)
8527       return SDValue();
8528
8529     if (ARM::isBitFieldInvertedMask(Mask)) {
8530       Val >>= countTrailingZeros(~Mask);
8531
8532       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8533                         DAG.getConstant(Val, DL, MVT::i32),
8534                         DAG.getConstant(Mask, DL, MVT::i32));
8535
8536       // Do not add new nodes to DAG combiner worklist.
8537       DCI.CombineTo(N, Res, false);
8538       return SDValue();
8539     }
8540   } else if (N1.getOpcode() == ISD::AND) {
8541     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8542     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8543     if (!N11C)
8544       return SDValue();
8545     unsigned Mask2 = N11C->getZExtValue();
8546
8547     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8548     // as is to match.
8549     if (ARM::isBitFieldInvertedMask(Mask) &&
8550         (Mask == ~Mask2)) {
8551       // The pack halfword instruction works better for masks that fit it,
8552       // so use that when it's available.
8553       if (Subtarget->hasT2ExtractPack() &&
8554           (Mask == 0xffff || Mask == 0xffff0000))
8555         return SDValue();
8556       // 2a
8557       unsigned amt = countTrailingZeros(Mask2);
8558       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8559                         DAG.getConstant(amt, DL, MVT::i32));
8560       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8561                         DAG.getConstant(Mask, DL, MVT::i32));
8562       // Do not add new nodes to DAG combiner worklist.
8563       DCI.CombineTo(N, Res, false);
8564       return SDValue();
8565     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8566                (~Mask == Mask2)) {
8567       // The pack halfword instruction works better for masks that fit it,
8568       // so use that when it's available.
8569       if (Subtarget->hasT2ExtractPack() &&
8570           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8571         return SDValue();
8572       // 2b
8573       unsigned lsb = countTrailingZeros(Mask);
8574       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8575                         DAG.getConstant(lsb, DL, MVT::i32));
8576       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8577                         DAG.getConstant(Mask2, DL, MVT::i32));
8578       // Do not add new nodes to DAG combiner worklist.
8579       DCI.CombineTo(N, Res, false);
8580       return SDValue();
8581     }
8582   }
8583
8584   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8585       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8586       ARM::isBitFieldInvertedMask(~Mask)) {
8587     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8588     // where lsb(mask) == #shamt and masked bits of B are known zero.
8589     SDValue ShAmt = N00.getOperand(1);
8590     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8591     unsigned LSB = countTrailingZeros(Mask);
8592     if (ShAmtC != LSB)
8593       return SDValue();
8594
8595     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8596                       DAG.getConstant(~Mask, DL, MVT::i32));
8597
8598     // Do not add new nodes to DAG combiner worklist.
8599     DCI.CombineTo(N, Res, false);
8600   }
8601
8602   return SDValue();
8603 }
8604
8605 static SDValue PerformXORCombine(SDNode *N,
8606                                  TargetLowering::DAGCombinerInfo &DCI,
8607                                  const ARMSubtarget *Subtarget) {
8608   EVT VT = N->getValueType(0);
8609   SelectionDAG &DAG = DCI.DAG;
8610
8611   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8612     return SDValue();
8613
8614   if (!Subtarget->isThumb1Only()) {
8615     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8616     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8617     if (Result.getNode())
8618       return Result;
8619   }
8620
8621   return SDValue();
8622 }
8623
8624 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8625 /// the bits being cleared by the AND are not demanded by the BFI.
8626 static SDValue PerformBFICombine(SDNode *N,
8627                                  TargetLowering::DAGCombinerInfo &DCI) {
8628   SDValue N1 = N->getOperand(1);
8629   if (N1.getOpcode() == ISD::AND) {
8630     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8631     if (!N11C)
8632       return SDValue();
8633     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8634     unsigned LSB = countTrailingZeros(~InvMask);
8635     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8636     assert(Width <
8637                static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
8638            "undefined behavior");
8639     unsigned Mask = (1u << Width) - 1;
8640     unsigned Mask2 = N11C->getZExtValue();
8641     if ((Mask & (~Mask2)) == 0)
8642       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8643                              N->getOperand(0), N1.getOperand(0),
8644                              N->getOperand(2));
8645   }
8646   return SDValue();
8647 }
8648
8649 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8650 /// ARMISD::VMOVRRD.
8651 static SDValue PerformVMOVRRDCombine(SDNode *N,
8652                                      TargetLowering::DAGCombinerInfo &DCI,
8653                                      const ARMSubtarget *Subtarget) {
8654   // vmovrrd(vmovdrr x, y) -> x,y
8655   SDValue InDouble = N->getOperand(0);
8656   if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
8657     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8658
8659   // vmovrrd(load f64) -> (load i32), (load i32)
8660   SDNode *InNode = InDouble.getNode();
8661   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8662       InNode->getValueType(0) == MVT::f64 &&
8663       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8664       !cast<LoadSDNode>(InNode)->isVolatile()) {
8665     // TODO: Should this be done for non-FrameIndex operands?
8666     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8667
8668     SelectionDAG &DAG = DCI.DAG;
8669     SDLoc DL(LD);
8670     SDValue BasePtr = LD->getBasePtr();
8671     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8672                                  LD->getPointerInfo(), LD->isVolatile(),
8673                                  LD->isNonTemporal(), LD->isInvariant(),
8674                                  LD->getAlignment());
8675
8676     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8677                                     DAG.getConstant(4, DL, MVT::i32));
8678     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8679                                  LD->getPointerInfo(), LD->isVolatile(),
8680                                  LD->isNonTemporal(), LD->isInvariant(),
8681                                  std::min(4U, LD->getAlignment() / 2));
8682
8683     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8684     if (DCI.DAG.getDataLayout().isBigEndian())
8685       std::swap (NewLD1, NewLD2);
8686     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8687     return Result;
8688   }
8689
8690   return SDValue();
8691 }
8692
8693 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8694 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8695 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8696   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8697   SDValue Op0 = N->getOperand(0);
8698   SDValue Op1 = N->getOperand(1);
8699   if (Op0.getOpcode() == ISD::BITCAST)
8700     Op0 = Op0.getOperand(0);
8701   if (Op1.getOpcode() == ISD::BITCAST)
8702     Op1 = Op1.getOperand(0);
8703   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8704       Op0.getNode() == Op1.getNode() &&
8705       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8706     return DAG.getNode(ISD::BITCAST, SDLoc(N),
8707                        N->getValueType(0), Op0.getOperand(0));
8708   return SDValue();
8709 }
8710
8711 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8712 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8713 /// i64 vector to have f64 elements, since the value can then be loaded
8714 /// directly into a VFP register.
8715 static bool hasNormalLoadOperand(SDNode *N) {
8716   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8717   for (unsigned i = 0; i < NumElts; ++i) {
8718     SDNode *Elt = N->getOperand(i).getNode();
8719     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8720       return true;
8721   }
8722   return false;
8723 }
8724
8725 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8726 /// ISD::BUILD_VECTOR.
8727 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8728                                           TargetLowering::DAGCombinerInfo &DCI,
8729                                           const ARMSubtarget *Subtarget) {
8730   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8731   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
8732   // into a pair of GPRs, which is fine when the value is used as a scalar,
8733   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8734   SelectionDAG &DAG = DCI.DAG;
8735   if (N->getNumOperands() == 2) {
8736     SDValue RV = PerformVMOVDRRCombine(N, DAG);
8737     if (RV.getNode())
8738       return RV;
8739   }
8740
8741   // Load i64 elements as f64 values so that type legalization does not split
8742   // them up into i32 values.
8743   EVT VT = N->getValueType(0);
8744   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8745     return SDValue();
8746   SDLoc dl(N);
8747   SmallVector<SDValue, 8> Ops;
8748   unsigned NumElts = VT.getVectorNumElements();
8749   for (unsigned i = 0; i < NumElts; ++i) {
8750     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8751     Ops.push_back(V);
8752     // Make the DAGCombiner fold the bitcast.
8753     DCI.AddToWorklist(V.getNode());
8754   }
8755   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8756   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8757   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8758 }
8759
8760 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8761 static SDValue
8762 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8763   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8764   // At that time, we may have inserted bitcasts from integer to float.
8765   // If these bitcasts have survived DAGCombine, change the lowering of this
8766   // BUILD_VECTOR in something more vector friendly, i.e., that does not
8767   // force to use floating point types.
8768
8769   // Make sure we can change the type of the vector.
8770   // This is possible iff:
8771   // 1. The vector is only used in a bitcast to a integer type. I.e.,
8772   //    1.1. Vector is used only once.
8773   //    1.2. Use is a bit convert to an integer type.
8774   // 2. The size of its operands are 32-bits (64-bits are not legal).
8775   EVT VT = N->getValueType(0);
8776   EVT EltVT = VT.getVectorElementType();
8777
8778   // Check 1.1. and 2.
8779   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8780     return SDValue();
8781
8782   // By construction, the input type must be float.
8783   assert(EltVT == MVT::f32 && "Unexpected type!");
8784
8785   // Check 1.2.
8786   SDNode *Use = *N->use_begin();
8787   if (Use->getOpcode() != ISD::BITCAST ||
8788       Use->getValueType(0).isFloatingPoint())
8789     return SDValue();
8790
8791   // Check profitability.
8792   // Model is, if more than half of the relevant operands are bitcast from
8793   // i32, turn the build_vector into a sequence of insert_vector_elt.
8794   // Relevant operands are everything that is not statically
8795   // (i.e., at compile time) bitcasted.
8796   unsigned NumOfBitCastedElts = 0;
8797   unsigned NumElts = VT.getVectorNumElements();
8798   unsigned NumOfRelevantElts = NumElts;
8799   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8800     SDValue Elt = N->getOperand(Idx);
8801     if (Elt->getOpcode() == ISD::BITCAST) {
8802       // Assume only bit cast to i32 will go away.
8803       if (Elt->getOperand(0).getValueType() == MVT::i32)
8804         ++NumOfBitCastedElts;
8805     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8806       // Constants are statically casted, thus do not count them as
8807       // relevant operands.
8808       --NumOfRelevantElts;
8809   }
8810
8811   // Check if more than half of the elements require a non-free bitcast.
8812   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8813     return SDValue();
8814
8815   SelectionDAG &DAG = DCI.DAG;
8816   // Create the new vector type.
8817   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8818   // Check if the type is legal.
8819   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8820   if (!TLI.isTypeLegal(VecVT))
8821     return SDValue();
8822
8823   // Combine:
8824   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8825   // => BITCAST INSERT_VECTOR_ELT
8826   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8827   //                      (BITCAST EN), N.
8828   SDValue Vec = DAG.getUNDEF(VecVT);
8829   SDLoc dl(N);
8830   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8831     SDValue V = N->getOperand(Idx);
8832     if (V.getOpcode() == ISD::UNDEF)
8833       continue;
8834     if (V.getOpcode() == ISD::BITCAST &&
8835         V->getOperand(0).getValueType() == MVT::i32)
8836       // Fold obvious case.
8837       V = V.getOperand(0);
8838     else {
8839       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
8840       // Make the DAGCombiner fold the bitcasts.
8841       DCI.AddToWorklist(V.getNode());
8842     }
8843     SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
8844     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8845   }
8846   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8847   // Make the DAGCombiner fold the bitcasts.
8848   DCI.AddToWorklist(Vec.getNode());
8849   return Vec;
8850 }
8851
8852 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8853 /// ISD::INSERT_VECTOR_ELT.
8854 static SDValue PerformInsertEltCombine(SDNode *N,
8855                                        TargetLowering::DAGCombinerInfo &DCI) {
8856   // Bitcast an i64 load inserted into a vector to f64.
8857   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8858   EVT VT = N->getValueType(0);
8859   SDNode *Elt = N->getOperand(1).getNode();
8860   if (VT.getVectorElementType() != MVT::i64 ||
8861       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8862     return SDValue();
8863
8864   SelectionDAG &DAG = DCI.DAG;
8865   SDLoc dl(N);
8866   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8867                                  VT.getVectorNumElements());
8868   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8869   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8870   // Make the DAGCombiner fold the bitcasts.
8871   DCI.AddToWorklist(Vec.getNode());
8872   DCI.AddToWorklist(V.getNode());
8873   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8874                                Vec, V, N->getOperand(2));
8875   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8876 }
8877
8878 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8879 /// ISD::VECTOR_SHUFFLE.
8880 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8881   // The LLVM shufflevector instruction does not require the shuffle mask
8882   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8883   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
8884   // operands do not match the mask length, they are extended by concatenating
8885   // them with undef vectors.  That is probably the right thing for other
8886   // targets, but for NEON it is better to concatenate two double-register
8887   // size vector operands into a single quad-register size vector.  Do that
8888   // transformation here:
8889   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
8890   //   shuffle(concat(v1, v2), undef)
8891   SDValue Op0 = N->getOperand(0);
8892   SDValue Op1 = N->getOperand(1);
8893   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8894       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8895       Op0.getNumOperands() != 2 ||
8896       Op1.getNumOperands() != 2)
8897     return SDValue();
8898   SDValue Concat0Op1 = Op0.getOperand(1);
8899   SDValue Concat1Op1 = Op1.getOperand(1);
8900   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8901       Concat1Op1.getOpcode() != ISD::UNDEF)
8902     return SDValue();
8903   // Skip the transformation if any of the types are illegal.
8904   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8905   EVT VT = N->getValueType(0);
8906   if (!TLI.isTypeLegal(VT) ||
8907       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8908       !TLI.isTypeLegal(Concat1Op1.getValueType()))
8909     return SDValue();
8910
8911   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
8912                                   Op0.getOperand(0), Op1.getOperand(0));
8913   // Translate the shuffle mask.
8914   SmallVector<int, 16> NewMask;
8915   unsigned NumElts = VT.getVectorNumElements();
8916   unsigned HalfElts = NumElts/2;
8917   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8918   for (unsigned n = 0; n < NumElts; ++n) {
8919     int MaskElt = SVN->getMaskElt(n);
8920     int NewElt = -1;
8921     if (MaskElt < (int)HalfElts)
8922       NewElt = MaskElt;
8923     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8924       NewElt = HalfElts + MaskElt - NumElts;
8925     NewMask.push_back(NewElt);
8926   }
8927   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
8928                               DAG.getUNDEF(VT), NewMask.data());
8929 }
8930
8931 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
8932 /// NEON load/store intrinsics, and generic vector load/stores, to merge
8933 /// base address updates.
8934 /// For generic load/stores, the memory type is assumed to be a vector.
8935 /// The caller is assumed to have checked legality.
8936 static SDValue CombineBaseUpdate(SDNode *N,
8937                                  TargetLowering::DAGCombinerInfo &DCI) {
8938   SelectionDAG &DAG = DCI.DAG;
8939   const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8940                             N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8941   const bool isStore = N->getOpcode() == ISD::STORE;
8942   const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
8943   SDValue Addr = N->getOperand(AddrOpIdx);
8944   MemSDNode *MemN = cast<MemSDNode>(N);
8945   SDLoc dl(N);
8946
8947   // Search for a use of the address operand that is an increment.
8948   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8949          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8950     SDNode *User = *UI;
8951     if (User->getOpcode() != ISD::ADD ||
8952         UI.getUse().getResNo() != Addr.getResNo())
8953       continue;
8954
8955     // Check that the add is independent of the load/store.  Otherwise, folding
8956     // it would create a cycle.
8957     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8958       continue;
8959
8960     // Find the new opcode for the updating load/store.
8961     bool isLoadOp = true;
8962     bool isLaneOp = false;
8963     unsigned NewOpc = 0;
8964     unsigned NumVecs = 0;
8965     if (isIntrinsic) {
8966       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8967       switch (IntNo) {
8968       default: llvm_unreachable("unexpected intrinsic for Neon base update");
8969       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
8970         NumVecs = 1; break;
8971       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
8972         NumVecs = 2; break;
8973       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
8974         NumVecs = 3; break;
8975       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
8976         NumVecs = 4; break;
8977       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8978         NumVecs = 2; isLaneOp = true; break;
8979       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8980         NumVecs = 3; isLaneOp = true; break;
8981       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8982         NumVecs = 4; isLaneOp = true; break;
8983       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
8984         NumVecs = 1; isLoadOp = false; break;
8985       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
8986         NumVecs = 2; isLoadOp = false; break;
8987       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
8988         NumVecs = 3; isLoadOp = false; break;
8989       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
8990         NumVecs = 4; isLoadOp = false; break;
8991       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8992         NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
8993       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8994         NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
8995       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8996         NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
8997       }
8998     } else {
8999       isLaneOp = true;
9000       switch (N->getOpcode()) {
9001       default: llvm_unreachable("unexpected opcode for Neon base update");
9002       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9003       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9004       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9005       case ISD::LOAD:       NewOpc = ARMISD::VLD1_UPD;
9006         NumVecs = 1; isLaneOp = false; break;
9007       case ISD::STORE:      NewOpc = ARMISD::VST1_UPD;
9008         NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
9009       }
9010     }
9011
9012     // Find the size of memory referenced by the load/store.
9013     EVT VecTy;
9014     if (isLoadOp) {
9015       VecTy = N->getValueType(0);
9016     } else if (isIntrinsic) {
9017       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9018     } else {
9019       assert(isStore && "Node has to be a load, a store, or an intrinsic!");
9020       VecTy = N->getOperand(1).getValueType();
9021     }
9022
9023     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9024     if (isLaneOp)
9025       NumBytes /= VecTy.getVectorNumElements();
9026
9027     // If the increment is a constant, it must match the memory ref size.
9028     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9029     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9030       uint64_t IncVal = CInc->getZExtValue();
9031       if (IncVal != NumBytes)
9032         continue;
9033     } else if (NumBytes >= 3 * 16) {
9034       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9035       // separate instructions that make it harder to use a non-constant update.
9036       continue;
9037     }
9038
9039     // OK, we found an ADD we can fold into the base update.
9040     // Now, create a _UPD node, taking care of not breaking alignment.
9041
9042     EVT AlignedVecTy = VecTy;
9043     unsigned Alignment = MemN->getAlignment();
9044
9045     // If this is a less-than-standard-aligned load/store, change the type to
9046     // match the standard alignment.
9047     // The alignment is overlooked when selecting _UPD variants; and it's
9048     // easier to introduce bitcasts here than fix that.
9049     // There are 3 ways to get to this base-update combine:
9050     // - intrinsics: they are assumed to be properly aligned (to the standard
9051     //   alignment of the memory type), so we don't need to do anything.
9052     // - ARMISD::VLDx nodes: they are only generated from the aforementioned
9053     //   intrinsics, so, likewise, there's nothing to do.
9054     // - generic load/store instructions: the alignment is specified as an
9055     //   explicit operand, rather than implicitly as the standard alignment
9056     //   of the memory type (like the intrisics).  We need to change the
9057     //   memory type to match the explicit alignment.  That way, we don't
9058     //   generate non-standard-aligned ARMISD::VLDx nodes.
9059     if (isa<LSBaseSDNode>(N)) {
9060       if (Alignment == 0)
9061         Alignment = 1;
9062       if (Alignment < VecTy.getScalarSizeInBits() / 8) {
9063         MVT EltTy = MVT::getIntegerVT(Alignment * 8);
9064         assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
9065         assert(!isLaneOp && "Unexpected generic load/store lane.");
9066         unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
9067         AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
9068       }
9069       // Don't set an explicit alignment on regular load/stores that we want
9070       // to transform to VLD/VST 1_UPD nodes.
9071       // This matches the behavior of regular load/stores, which only get an
9072       // explicit alignment if the MMO alignment is larger than the standard
9073       // alignment of the memory type.
9074       // Intrinsics, however, always get an explicit alignment, set to the
9075       // alignment of the MMO.
9076       Alignment = 1;
9077     }
9078
9079     // Create the new updating load/store node.
9080     // First, create an SDVTList for the new updating node's results.
9081     EVT Tys[6];
9082     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
9083     unsigned n;
9084     for (n = 0; n < NumResultVecs; ++n)
9085       Tys[n] = AlignedVecTy;
9086     Tys[n++] = MVT::i32;
9087     Tys[n] = MVT::Other;
9088     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
9089
9090     // Then, gather the new node's operands.
9091     SmallVector<SDValue, 8> Ops;
9092     Ops.push_back(N->getOperand(0)); // incoming chain
9093     Ops.push_back(N->getOperand(AddrOpIdx));
9094     Ops.push_back(Inc);
9095
9096     if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
9097       // Try to match the intrinsic's signature
9098       Ops.push_back(StN->getValue());
9099     } else {
9100       // Loads (and of course intrinsics) match the intrinsics' signature,
9101       // so just add all but the alignment operand.
9102       for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
9103         Ops.push_back(N->getOperand(i));
9104     }
9105
9106     // For all node types, the alignment operand is always the last one.
9107     Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
9108
9109     // If this is a non-standard-aligned STORE, the penultimate operand is the
9110     // stored value.  Bitcast it to the aligned type.
9111     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
9112       SDValue &StVal = Ops[Ops.size()-2];
9113       StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
9114     }
9115
9116     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys,
9117                                            Ops, AlignedVecTy,
9118                                            MemN->getMemOperand());
9119
9120     // Update the uses.
9121     SmallVector<SDValue, 5> NewResults;
9122     for (unsigned i = 0; i < NumResultVecs; ++i)
9123       NewResults.push_back(SDValue(UpdN.getNode(), i));
9124
9125     // If this is an non-standard-aligned LOAD, the first result is the loaded
9126     // value.  Bitcast it to the expected result type.
9127     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
9128       SDValue &LdVal = NewResults[0];
9129       LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
9130     }
9131
9132     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9133     DCI.CombineTo(N, NewResults);
9134     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9135
9136     break;
9137   }
9138   return SDValue();
9139 }
9140
9141 static SDValue PerformVLDCombine(SDNode *N,
9142                                  TargetLowering::DAGCombinerInfo &DCI) {
9143   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9144     return SDValue();
9145
9146   return CombineBaseUpdate(N, DCI);
9147 }
9148
9149 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9150 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9151 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
9152 /// return true.
9153 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9154   SelectionDAG &DAG = DCI.DAG;
9155   EVT VT = N->getValueType(0);
9156   // vldN-dup instructions only support 64-bit vectors for N > 1.
9157   if (!VT.is64BitVector())
9158     return false;
9159
9160   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9161   SDNode *VLD = N->getOperand(0).getNode();
9162   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9163     return false;
9164   unsigned NumVecs = 0;
9165   unsigned NewOpc = 0;
9166   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9167   if (IntNo == Intrinsic::arm_neon_vld2lane) {
9168     NumVecs = 2;
9169     NewOpc = ARMISD::VLD2DUP;
9170   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9171     NumVecs = 3;
9172     NewOpc = ARMISD::VLD3DUP;
9173   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9174     NumVecs = 4;
9175     NewOpc = ARMISD::VLD4DUP;
9176   } else {
9177     return false;
9178   }
9179
9180   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9181   // numbers match the load.
9182   unsigned VLDLaneNo =
9183     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9184   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9185        UI != UE; ++UI) {
9186     // Ignore uses of the chain result.
9187     if (UI.getUse().getResNo() == NumVecs)
9188       continue;
9189     SDNode *User = *UI;
9190     if (User->getOpcode() != ARMISD::VDUPLANE ||
9191         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9192       return false;
9193   }
9194
9195   // Create the vldN-dup node.
9196   EVT Tys[5];
9197   unsigned n;
9198   for (n = 0; n < NumVecs; ++n)
9199     Tys[n] = VT;
9200   Tys[n] = MVT::Other;
9201   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9202   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9203   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9204   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9205                                            Ops, VLDMemInt->getMemoryVT(),
9206                                            VLDMemInt->getMemOperand());
9207
9208   // Update the uses.
9209   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9210        UI != UE; ++UI) {
9211     unsigned ResNo = UI.getUse().getResNo();
9212     // Ignore uses of the chain result.
9213     if (ResNo == NumVecs)
9214       continue;
9215     SDNode *User = *UI;
9216     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9217   }
9218
9219   // Now the vldN-lane intrinsic is dead except for its chain result.
9220   // Update uses of the chain.
9221   std::vector<SDValue> VLDDupResults;
9222   for (unsigned n = 0; n < NumVecs; ++n)
9223     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9224   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9225   DCI.CombineTo(VLD, VLDDupResults);
9226
9227   return true;
9228 }
9229
9230 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9231 /// ARMISD::VDUPLANE.
9232 static SDValue PerformVDUPLANECombine(SDNode *N,
9233                                       TargetLowering::DAGCombinerInfo &DCI) {
9234   SDValue Op = N->getOperand(0);
9235
9236   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9237   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9238   if (CombineVLDDUP(N, DCI))
9239     return SDValue(N, 0);
9240
9241   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9242   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9243   while (Op.getOpcode() == ISD::BITCAST)
9244     Op = Op.getOperand(0);
9245   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9246     return SDValue();
9247
9248   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9249   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9250   // The canonical VMOV for a zero vector uses a 32-bit element size.
9251   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9252   unsigned EltBits;
9253   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9254     EltSize = 8;
9255   EVT VT = N->getValueType(0);
9256   if (EltSize > VT.getVectorElementType().getSizeInBits())
9257     return SDValue();
9258
9259   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9260 }
9261
9262 static SDValue PerformLOADCombine(SDNode *N,
9263                                   TargetLowering::DAGCombinerInfo &DCI) {
9264   EVT VT = N->getValueType(0);
9265
9266   // If this is a legal vector load, try to combine it into a VLD1_UPD.
9267   if (ISD::isNormalLoad(N) && VT.isVector() &&
9268       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9269     return CombineBaseUpdate(N, DCI);
9270
9271   return SDValue();
9272 }
9273
9274 /// PerformSTORECombine - Target-specific dag combine xforms for
9275 /// ISD::STORE.
9276 static SDValue PerformSTORECombine(SDNode *N,
9277                                    TargetLowering::DAGCombinerInfo &DCI) {
9278   StoreSDNode *St = cast<StoreSDNode>(N);
9279   if (St->isVolatile())
9280     return SDValue();
9281
9282   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
9283   // pack all of the elements in one place.  Next, store to memory in fewer
9284   // chunks.
9285   SDValue StVal = St->getValue();
9286   EVT VT = StVal.getValueType();
9287   if (St->isTruncatingStore() && VT.isVector()) {
9288     SelectionDAG &DAG = DCI.DAG;
9289     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9290     EVT StVT = St->getMemoryVT();
9291     unsigned NumElems = VT.getVectorNumElements();
9292     assert(StVT != VT && "Cannot truncate to the same type");
9293     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
9294     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
9295
9296     // From, To sizes and ElemCount must be pow of two
9297     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
9298
9299     // We are going to use the original vector elt for storing.
9300     // Accumulated smaller vector elements must be a multiple of the store size.
9301     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
9302
9303     unsigned SizeRatio  = FromEltSz / ToEltSz;
9304     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
9305
9306     // Create a type on which we perform the shuffle.
9307     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9308                                      NumElems*SizeRatio);
9309     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9310
9311     SDLoc DL(St);
9312     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9313     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9314     for (unsigned i = 0; i < NumElems; ++i)
9315       ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
9316                           ? (i + 1) * SizeRatio - 1
9317                           : i * SizeRatio;
9318
9319     // Can't shuffle using an illegal type.
9320     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9321
9322     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9323                                 DAG.getUNDEF(WideVec.getValueType()),
9324                                 ShuffleVec.data());
9325     // At this point all of the data is stored at the bottom of the
9326     // register. We now need to save it to mem.
9327
9328     // Find the largest store unit
9329     MVT StoreType = MVT::i8;
9330     for (MVT Tp : MVT::integer_valuetypes()) {
9331       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9332         StoreType = Tp;
9333     }
9334     // Didn't find a legal store type.
9335     if (!TLI.isTypeLegal(StoreType))
9336       return SDValue();
9337
9338     // Bitcast the original vector into a vector of store-size units
9339     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9340             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9341     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9342     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9343     SmallVector<SDValue, 8> Chains;
9344     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
9345                                         TLI.getPointerTy(DAG.getDataLayout()));
9346     SDValue BasePtr = St->getBasePtr();
9347
9348     // Perform one or more big stores into memory.
9349     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9350     for (unsigned I = 0; I < E; I++) {
9351       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9352                                    StoreType, ShuffWide,
9353                                    DAG.getIntPtrConstant(I, DL));
9354       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9355                                 St->getPointerInfo(), St->isVolatile(),
9356                                 St->isNonTemporal(), St->getAlignment());
9357       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9358                             Increment);
9359       Chains.push_back(Ch);
9360     }
9361     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
9362   }
9363
9364   if (!ISD::isNormalStore(St))
9365     return SDValue();
9366
9367   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9368   // ARM stores of arguments in the same cache line.
9369   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9370       StVal.getNode()->hasOneUse()) {
9371     SelectionDAG  &DAG = DCI.DAG;
9372     bool isBigEndian = DAG.getDataLayout().isBigEndian();
9373     SDLoc DL(St);
9374     SDValue BasePtr = St->getBasePtr();
9375     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9376                                   StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
9377                                   BasePtr, St->getPointerInfo(), St->isVolatile(),
9378                                   St->isNonTemporal(), St->getAlignment());
9379
9380     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9381                                     DAG.getConstant(4, DL, MVT::i32));
9382     return DAG.getStore(NewST1.getValue(0), DL,
9383                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
9384                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9385                         St->isNonTemporal(),
9386                         std::min(4U, St->getAlignment() / 2));
9387   }
9388
9389   if (StVal.getValueType() == MVT::i64 &&
9390       StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9391
9392     // Bitcast an i64 store extracted from a vector to f64.
9393     // Otherwise, the i64 value will be legalized to a pair of i32 values.
9394     SelectionDAG &DAG = DCI.DAG;
9395     SDLoc dl(StVal);
9396     SDValue IntVec = StVal.getOperand(0);
9397     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9398                                    IntVec.getValueType().getVectorNumElements());
9399     SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9400     SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9401                                  Vec, StVal.getOperand(1));
9402     dl = SDLoc(N);
9403     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9404     // Make the DAGCombiner fold the bitcasts.
9405     DCI.AddToWorklist(Vec.getNode());
9406     DCI.AddToWorklist(ExtElt.getNode());
9407     DCI.AddToWorklist(V.getNode());
9408     return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9409                         St->getPointerInfo(), St->isVolatile(),
9410                         St->isNonTemporal(), St->getAlignment(),
9411                         St->getAAInfo());
9412   }
9413
9414   // If this is a legal vector store, try to combine it into a VST1_UPD.
9415   if (ISD::isNormalStore(N) && VT.isVector() &&
9416       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9417     return CombineBaseUpdate(N, DCI);
9418
9419   return SDValue();
9420 }
9421
9422 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9423 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9424 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9425 {
9426   integerPart cN;
9427   integerPart c0 = 0;
9428   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9429        I != E; I++) {
9430     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9431     if (!C)
9432       return false;
9433
9434     bool isExact;
9435     APFloat APF = C->getValueAPF();
9436     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9437         != APFloat::opOK || !isExact)
9438       return false;
9439
9440     c0 = (I == 0) ? cN : c0;
9441     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9442       return false;
9443   }
9444   C = c0;
9445   return true;
9446 }
9447
9448 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9449 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9450 /// when the VMUL has a constant operand that is a power of 2.
9451 ///
9452 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9453 ///  vmul.f32        d16, d17, d16
9454 ///  vcvt.s32.f32    d16, d16
9455 /// becomes:
9456 ///  vcvt.s32.f32    d16, d16, #3
9457 static SDValue PerformVCVTCombine(SDNode *N,
9458                                   TargetLowering::DAGCombinerInfo &DCI,
9459                                   const ARMSubtarget *Subtarget) {
9460   SelectionDAG &DAG = DCI.DAG;
9461   SDValue Op = N->getOperand(0);
9462
9463   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9464       Op.getOpcode() != ISD::FMUL)
9465     return SDValue();
9466
9467   uint64_t C;
9468   SDValue N0 = Op->getOperand(0);
9469   SDValue ConstVec = Op->getOperand(1);
9470   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9471
9472   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9473       !isConstVecPow2(ConstVec, isSigned, C))
9474     return SDValue();
9475
9476   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9477   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9478   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9479   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32 ||
9480       NumLanes > 4) {
9481     // These instructions only exist converting from f32 to i32. We can handle
9482     // smaller integers by generating an extra truncate, but larger ones would
9483     // be lossy. We also can't handle more then 4 lanes, since these intructions
9484     // only support v2i32/v4i32 types.
9485     return SDValue();
9486   }
9487
9488   SDLoc dl(N);
9489   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9490     Intrinsic::arm_neon_vcvtfp2fxu;
9491   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9492                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9493                                  DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9494                                  N0,
9495                                  DAG.getConstant(Log2_64(C), dl, MVT::i32));
9496
9497   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9498     FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
9499
9500   return FixConv;
9501 }
9502
9503 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9504 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9505 /// when the VDIV has a constant operand that is a power of 2.
9506 ///
9507 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9508 ///  vcvt.f32.s32    d16, d16
9509 ///  vdiv.f32        d16, d17, d16
9510 /// becomes:
9511 ///  vcvt.f32.s32    d16, d16, #3
9512 static SDValue PerformVDIVCombine(SDNode *N,
9513                                   TargetLowering::DAGCombinerInfo &DCI,
9514                                   const ARMSubtarget *Subtarget) {
9515   SelectionDAG &DAG = DCI.DAG;
9516   SDValue Op = N->getOperand(0);
9517   unsigned OpOpcode = Op.getNode()->getOpcode();
9518
9519   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9520       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9521     return SDValue();
9522
9523   uint64_t C;
9524   SDValue ConstVec = N->getOperand(1);
9525   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9526
9527   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9528       !isConstVecPow2(ConstVec, isSigned, C))
9529     return SDValue();
9530
9531   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9532   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9533   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9534     // These instructions only exist converting from i32 to f32. We can handle
9535     // smaller integers by generating an extra extend, but larger ones would
9536     // be lossy.
9537     return SDValue();
9538   }
9539
9540   SDLoc dl(N);
9541   SDValue ConvInput = Op.getOperand(0);
9542   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9543   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9544     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9545                             dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9546                             ConvInput);
9547
9548   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9549     Intrinsic::arm_neon_vcvtfxu2fp;
9550   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9551                      Op.getValueType(),
9552                      DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9553                      ConvInput, DAG.getConstant(Log2_64(C), dl, MVT::i32));
9554 }
9555
9556 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9557 /// operand of a vector shift operation, where all the elements of the
9558 /// build_vector must have the same constant integer value.
9559 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9560   // Ignore bit_converts.
9561   while (Op.getOpcode() == ISD::BITCAST)
9562     Op = Op.getOperand(0);
9563   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9564   APInt SplatBits, SplatUndef;
9565   unsigned SplatBitSize;
9566   bool HasAnyUndefs;
9567   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9568                                       HasAnyUndefs, ElementBits) ||
9569       SplatBitSize > ElementBits)
9570     return false;
9571   Cnt = SplatBits.getSExtValue();
9572   return true;
9573 }
9574
9575 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9576 /// operand of a vector shift left operation.  That value must be in the range:
9577 ///   0 <= Value < ElementBits for a left shift; or
9578 ///   0 <= Value <= ElementBits for a long left shift.
9579 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9580   assert(VT.isVector() && "vector shift count is not a vector type");
9581   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9582   if (! getVShiftImm(Op, ElementBits, Cnt))
9583     return false;
9584   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9585 }
9586
9587 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9588 /// operand of a vector shift right operation.  For a shift opcode, the value
9589 /// is positive, but for an intrinsic the value count must be negative. The
9590 /// absolute value must be in the range:
9591 ///   1 <= |Value| <= ElementBits for a right shift; or
9592 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9593 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9594                          int64_t &Cnt) {
9595   assert(VT.isVector() && "vector shift count is not a vector type");
9596   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9597   if (! getVShiftImm(Op, ElementBits, Cnt))
9598     return false;
9599   if (isIntrinsic)
9600     Cnt = -Cnt;
9601   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9602 }
9603
9604 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9605 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9606   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9607   switch (IntNo) {
9608   default:
9609     // Don't do anything for most intrinsics.
9610     break;
9611
9612   // Vector shifts: check for immediate versions and lower them.
9613   // Note: This is done during DAG combining instead of DAG legalizing because
9614   // the build_vectors for 64-bit vector element shift counts are generally
9615   // not legal, and it is hard to see their values after they get legalized to
9616   // loads from a constant pool.
9617   case Intrinsic::arm_neon_vshifts:
9618   case Intrinsic::arm_neon_vshiftu:
9619   case Intrinsic::arm_neon_vrshifts:
9620   case Intrinsic::arm_neon_vrshiftu:
9621   case Intrinsic::arm_neon_vrshiftn:
9622   case Intrinsic::arm_neon_vqshifts:
9623   case Intrinsic::arm_neon_vqshiftu:
9624   case Intrinsic::arm_neon_vqshiftsu:
9625   case Intrinsic::arm_neon_vqshiftns:
9626   case Intrinsic::arm_neon_vqshiftnu:
9627   case Intrinsic::arm_neon_vqshiftnsu:
9628   case Intrinsic::arm_neon_vqrshiftns:
9629   case Intrinsic::arm_neon_vqrshiftnu:
9630   case Intrinsic::arm_neon_vqrshiftnsu: {
9631     EVT VT = N->getOperand(1).getValueType();
9632     int64_t Cnt;
9633     unsigned VShiftOpc = 0;
9634
9635     switch (IntNo) {
9636     case Intrinsic::arm_neon_vshifts:
9637     case Intrinsic::arm_neon_vshiftu:
9638       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9639         VShiftOpc = ARMISD::VSHL;
9640         break;
9641       }
9642       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9643         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9644                      ARMISD::VSHRs : ARMISD::VSHRu);
9645         break;
9646       }
9647       return SDValue();
9648
9649     case Intrinsic::arm_neon_vrshifts:
9650     case Intrinsic::arm_neon_vrshiftu:
9651       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9652         break;
9653       return SDValue();
9654
9655     case Intrinsic::arm_neon_vqshifts:
9656     case Intrinsic::arm_neon_vqshiftu:
9657       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9658         break;
9659       return SDValue();
9660
9661     case Intrinsic::arm_neon_vqshiftsu:
9662       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9663         break;
9664       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9665
9666     case Intrinsic::arm_neon_vrshiftn:
9667     case Intrinsic::arm_neon_vqshiftns:
9668     case Intrinsic::arm_neon_vqshiftnu:
9669     case Intrinsic::arm_neon_vqshiftnsu:
9670     case Intrinsic::arm_neon_vqrshiftns:
9671     case Intrinsic::arm_neon_vqrshiftnu:
9672     case Intrinsic::arm_neon_vqrshiftnsu:
9673       // Narrowing shifts require an immediate right shift.
9674       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9675         break;
9676       llvm_unreachable("invalid shift count for narrowing vector shift "
9677                        "intrinsic");
9678
9679     default:
9680       llvm_unreachable("unhandled vector shift");
9681     }
9682
9683     switch (IntNo) {
9684     case Intrinsic::arm_neon_vshifts:
9685     case Intrinsic::arm_neon_vshiftu:
9686       // Opcode already set above.
9687       break;
9688     case Intrinsic::arm_neon_vrshifts:
9689       VShiftOpc = ARMISD::VRSHRs; break;
9690     case Intrinsic::arm_neon_vrshiftu:
9691       VShiftOpc = ARMISD::VRSHRu; break;
9692     case Intrinsic::arm_neon_vrshiftn:
9693       VShiftOpc = ARMISD::VRSHRN; break;
9694     case Intrinsic::arm_neon_vqshifts:
9695       VShiftOpc = ARMISD::VQSHLs; break;
9696     case Intrinsic::arm_neon_vqshiftu:
9697       VShiftOpc = ARMISD::VQSHLu; break;
9698     case Intrinsic::arm_neon_vqshiftsu:
9699       VShiftOpc = ARMISD::VQSHLsu; break;
9700     case Intrinsic::arm_neon_vqshiftns:
9701       VShiftOpc = ARMISD::VQSHRNs; break;
9702     case Intrinsic::arm_neon_vqshiftnu:
9703       VShiftOpc = ARMISD::VQSHRNu; break;
9704     case Intrinsic::arm_neon_vqshiftnsu:
9705       VShiftOpc = ARMISD::VQSHRNsu; break;
9706     case Intrinsic::arm_neon_vqrshiftns:
9707       VShiftOpc = ARMISD::VQRSHRNs; break;
9708     case Intrinsic::arm_neon_vqrshiftnu:
9709       VShiftOpc = ARMISD::VQRSHRNu; break;
9710     case Intrinsic::arm_neon_vqrshiftnsu:
9711       VShiftOpc = ARMISD::VQRSHRNsu; break;
9712     }
9713
9714     SDLoc dl(N);
9715     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
9716                        N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
9717   }
9718
9719   case Intrinsic::arm_neon_vshiftins: {
9720     EVT VT = N->getOperand(1).getValueType();
9721     int64_t Cnt;
9722     unsigned VShiftOpc = 0;
9723
9724     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9725       VShiftOpc = ARMISD::VSLI;
9726     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9727       VShiftOpc = ARMISD::VSRI;
9728     else {
9729       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9730     }
9731
9732     SDLoc dl(N);
9733     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
9734                        N->getOperand(1), N->getOperand(2),
9735                        DAG.getConstant(Cnt, dl, MVT::i32));
9736   }
9737
9738   case Intrinsic::arm_neon_vqrshifts:
9739   case Intrinsic::arm_neon_vqrshiftu:
9740     // No immediate versions of these to check for.
9741     break;
9742   }
9743
9744   return SDValue();
9745 }
9746
9747 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9748 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9749 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9750 /// vector element shift counts are generally not legal, and it is hard to see
9751 /// their values after they get legalized to loads from a constant pool.
9752 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9753                                    const ARMSubtarget *ST) {
9754   EVT VT = N->getValueType(0);
9755   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9756     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9757     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9758     SDValue N1 = N->getOperand(1);
9759     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9760       SDValue N0 = N->getOperand(0);
9761       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9762           DAG.MaskedValueIsZero(N0.getOperand(0),
9763                                 APInt::getHighBitsSet(32, 16)))
9764         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9765     }
9766   }
9767
9768   // Nothing to be done for scalar shifts.
9769   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9770   if (!VT.isVector() || !TLI.isTypeLegal(VT))
9771     return SDValue();
9772
9773   assert(ST->hasNEON() && "unexpected vector shift");
9774   int64_t Cnt;
9775
9776   switch (N->getOpcode()) {
9777   default: llvm_unreachable("unexpected shift opcode");
9778
9779   case ISD::SHL:
9780     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
9781       SDLoc dl(N);
9782       return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
9783                          DAG.getConstant(Cnt, dl, MVT::i32));
9784     }
9785     break;
9786
9787   case ISD::SRA:
9788   case ISD::SRL:
9789     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9790       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9791                             ARMISD::VSHRs : ARMISD::VSHRu);
9792       SDLoc dl(N);
9793       return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
9794                          DAG.getConstant(Cnt, dl, MVT::i32));
9795     }
9796   }
9797   return SDValue();
9798 }
9799
9800 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9801 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9802 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9803                                     const ARMSubtarget *ST) {
9804   SDValue N0 = N->getOperand(0);
9805
9806   // Check for sign- and zero-extensions of vector extract operations of 8-
9807   // and 16-bit vector elements.  NEON supports these directly.  They are
9808   // handled during DAG combining because type legalization will promote them
9809   // to 32-bit types and it is messy to recognize the operations after that.
9810   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9811     SDValue Vec = N0.getOperand(0);
9812     SDValue Lane = N0.getOperand(1);
9813     EVT VT = N->getValueType(0);
9814     EVT EltVT = N0.getValueType();
9815     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9816
9817     if (VT == MVT::i32 &&
9818         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9819         TLI.isTypeLegal(Vec.getValueType()) &&
9820         isa<ConstantSDNode>(Lane)) {
9821
9822       unsigned Opc = 0;
9823       switch (N->getOpcode()) {
9824       default: llvm_unreachable("unexpected opcode");
9825       case ISD::SIGN_EXTEND:
9826         Opc = ARMISD::VGETLANEs;
9827         break;
9828       case ISD::ZERO_EXTEND:
9829       case ISD::ANY_EXTEND:
9830         Opc = ARMISD::VGETLANEu;
9831         break;
9832       }
9833       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9834     }
9835   }
9836
9837   return SDValue();
9838 }
9839
9840 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9841 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9842 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9843                                        const ARMSubtarget *ST) {
9844   // If the target supports NEON, try to use vmax/vmin instructions for f32
9845   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
9846   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
9847   // a NaN; only do the transformation when it matches that behavior.
9848
9849   // For now only do this when using NEON for FP operations; if using VFP, it
9850   // is not obvious that the benefit outweighs the cost of switching to the
9851   // NEON pipeline.
9852   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9853       N->getValueType(0) != MVT::f32)
9854     return SDValue();
9855
9856   SDValue CondLHS = N->getOperand(0);
9857   SDValue CondRHS = N->getOperand(1);
9858   SDValue LHS = N->getOperand(2);
9859   SDValue RHS = N->getOperand(3);
9860   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9861
9862   unsigned Opcode = 0;
9863   bool IsReversed;
9864   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9865     IsReversed = false; // x CC y ? x : y
9866   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9867     IsReversed = true ; // x CC y ? y : x
9868   } else {
9869     return SDValue();
9870   }
9871
9872   bool IsUnordered;
9873   switch (CC) {
9874   default: break;
9875   case ISD::SETOLT:
9876   case ISD::SETOLE:
9877   case ISD::SETLT:
9878   case ISD::SETLE:
9879   case ISD::SETULT:
9880   case ISD::SETULE:
9881     // If LHS is NaN, an ordered comparison will be false and the result will
9882     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
9883     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9884     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9885     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9886       break;
9887     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9888     // will return -0, so vmin can only be used for unsafe math or if one of
9889     // the operands is known to be nonzero.
9890     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9891         !DAG.getTarget().Options.UnsafeFPMath &&
9892         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9893       break;
9894     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9895     break;
9896
9897   case ISD::SETOGT:
9898   case ISD::SETOGE:
9899   case ISD::SETGT:
9900   case ISD::SETGE:
9901   case ISD::SETUGT:
9902   case ISD::SETUGE:
9903     // If LHS is NaN, an ordered comparison will be false and the result will
9904     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
9905     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9906     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9907     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9908       break;
9909     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9910     // will return +0, so vmax can only be used for unsafe math or if one of
9911     // the operands is known to be nonzero.
9912     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9913         !DAG.getTarget().Options.UnsafeFPMath &&
9914         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9915       break;
9916     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9917     break;
9918   }
9919
9920   if (!Opcode)
9921     return SDValue();
9922   return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9923 }
9924
9925 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9926 SDValue
9927 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9928   SDValue Cmp = N->getOperand(4);
9929   if (Cmp.getOpcode() != ARMISD::CMPZ)
9930     // Only looking at EQ and NE cases.
9931     return SDValue();
9932
9933   EVT VT = N->getValueType(0);
9934   SDLoc dl(N);
9935   SDValue LHS = Cmp.getOperand(0);
9936   SDValue RHS = Cmp.getOperand(1);
9937   SDValue FalseVal = N->getOperand(0);
9938   SDValue TrueVal = N->getOperand(1);
9939   SDValue ARMcc = N->getOperand(2);
9940   ARMCC::CondCodes CC =
9941     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9942
9943   // Simplify
9944   //   mov     r1, r0
9945   //   cmp     r1, x
9946   //   mov     r0, y
9947   //   moveq   r0, x
9948   // to
9949   //   cmp     r0, x
9950   //   movne   r0, y
9951   //
9952   //   mov     r1, r0
9953   //   cmp     r1, x
9954   //   mov     r0, x
9955   //   movne   r0, y
9956   // to
9957   //   cmp     r0, x
9958   //   movne   r0, y
9959   /// FIXME: Turn this into a target neutral optimization?
9960   SDValue Res;
9961   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9962     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9963                       N->getOperand(3), Cmp);
9964   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9965     SDValue ARMcc;
9966     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9967     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9968                       N->getOperand(3), NewCmp);
9969   }
9970
9971   if (Res.getNode()) {
9972     APInt KnownZero, KnownOne;
9973     DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
9974     // Capture demanded bits information that would be otherwise lost.
9975     if (KnownZero == 0xfffffffe)
9976       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9977                         DAG.getValueType(MVT::i1));
9978     else if (KnownZero == 0xffffff00)
9979       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9980                         DAG.getValueType(MVT::i8));
9981     else if (KnownZero == 0xffff0000)
9982       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9983                         DAG.getValueType(MVT::i16));
9984   }
9985
9986   return Res;
9987 }
9988
9989 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9990                                              DAGCombinerInfo &DCI) const {
9991   switch (N->getOpcode()) {
9992   default: break;
9993   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
9994   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
9995   case ISD::SUB:        return PerformSUBCombine(N, DCI);
9996   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
9997   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
9998   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
9999   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
10000   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
10001   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
10002   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
10003   case ISD::STORE:      return PerformSTORECombine(N, DCI);
10004   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
10005   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
10006   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
10007   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
10008   case ISD::FP_TO_SINT:
10009   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
10010   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
10011   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
10012   case ISD::SHL:
10013   case ISD::SRA:
10014   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
10015   case ISD::SIGN_EXTEND:
10016   case ISD::ZERO_EXTEND:
10017   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
10018   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
10019   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
10020   case ISD::LOAD:       return PerformLOADCombine(N, DCI);
10021   case ARMISD::VLD2DUP:
10022   case ARMISD::VLD3DUP:
10023   case ARMISD::VLD4DUP:
10024     return PerformVLDCombine(N, DCI);
10025   case ARMISD::BUILD_VECTOR:
10026     return PerformARMBUILD_VECTORCombine(N, DCI);
10027   case ISD::INTRINSIC_VOID:
10028   case ISD::INTRINSIC_W_CHAIN:
10029     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10030     case Intrinsic::arm_neon_vld1:
10031     case Intrinsic::arm_neon_vld2:
10032     case Intrinsic::arm_neon_vld3:
10033     case Intrinsic::arm_neon_vld4:
10034     case Intrinsic::arm_neon_vld2lane:
10035     case Intrinsic::arm_neon_vld3lane:
10036     case Intrinsic::arm_neon_vld4lane:
10037     case Intrinsic::arm_neon_vst1:
10038     case Intrinsic::arm_neon_vst2:
10039     case Intrinsic::arm_neon_vst3:
10040     case Intrinsic::arm_neon_vst4:
10041     case Intrinsic::arm_neon_vst2lane:
10042     case Intrinsic::arm_neon_vst3lane:
10043     case Intrinsic::arm_neon_vst4lane:
10044       return PerformVLDCombine(N, DCI);
10045     default: break;
10046     }
10047     break;
10048   }
10049   return SDValue();
10050 }
10051
10052 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
10053                                                           EVT VT) const {
10054   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
10055 }
10056
10057 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
10058                                                        unsigned,
10059                                                        unsigned,
10060                                                        bool *Fast) const {
10061   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
10062   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
10063
10064   switch (VT.getSimpleVT().SimpleTy) {
10065   default:
10066     return false;
10067   case MVT::i8:
10068   case MVT::i16:
10069   case MVT::i32: {
10070     // Unaligned access can use (for example) LRDB, LRDH, LDR
10071     if (AllowsUnaligned) {
10072       if (Fast)
10073         *Fast = Subtarget->hasV7Ops();
10074       return true;
10075     }
10076     return false;
10077   }
10078   case MVT::f64:
10079   case MVT::v2f64: {
10080     // For any little-endian targets with neon, we can support unaligned ld/st
10081     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10082     // A big-endian target may also explicitly support unaligned accesses
10083     if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
10084       if (Fast)
10085         *Fast = true;
10086       return true;
10087     }
10088     return false;
10089   }
10090   }
10091 }
10092
10093 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10094                        unsigned AlignCheck) {
10095   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10096           (DstAlign == 0 || DstAlign % AlignCheck == 0));
10097 }
10098
10099 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10100                                            unsigned DstAlign, unsigned SrcAlign,
10101                                            bool IsMemset, bool ZeroMemset,
10102                                            bool MemcpyStrSrc,
10103                                            MachineFunction &MF) const {
10104   const Function *F = MF.getFunction();
10105
10106   // See if we can use NEON instructions for this...
10107   if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
10108       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10109     bool Fast;
10110     if (Size >= 16 &&
10111         (memOpAlign(SrcAlign, DstAlign, 16) ||
10112          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
10113       return MVT::v2f64;
10114     } else if (Size >= 8 &&
10115                (memOpAlign(SrcAlign, DstAlign, 8) ||
10116                 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
10117                  Fast))) {
10118       return MVT::f64;
10119     }
10120   }
10121
10122   // Lowering to i32/i16 if the size permits.
10123   if (Size >= 4)
10124     return MVT::i32;
10125   else if (Size >= 2)
10126     return MVT::i16;
10127
10128   // Let the target-independent logic figure it out.
10129   return MVT::Other;
10130 }
10131
10132 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10133   if (Val.getOpcode() != ISD::LOAD)
10134     return false;
10135
10136   EVT VT1 = Val.getValueType();
10137   if (!VT1.isSimple() || !VT1.isInteger() ||
10138       !VT2.isSimple() || !VT2.isInteger())
10139     return false;
10140
10141   switch (VT1.getSimpleVT().SimpleTy) {
10142   default: break;
10143   case MVT::i1:
10144   case MVT::i8:
10145   case MVT::i16:
10146     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10147     return true;
10148   }
10149
10150   return false;
10151 }
10152
10153 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
10154   EVT VT = ExtVal.getValueType();
10155
10156   if (!isTypeLegal(VT))
10157     return false;
10158
10159   // Don't create a loadext if we can fold the extension into a wide/long
10160   // instruction.
10161   // If there's more than one user instruction, the loadext is desirable no
10162   // matter what.  There can be two uses by the same instruction.
10163   if (ExtVal->use_empty() ||
10164       !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
10165     return true;
10166
10167   SDNode *U = *ExtVal->use_begin();
10168   if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
10169        U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
10170     return false;
10171
10172   return true;
10173 }
10174
10175 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10176   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10177     return false;
10178
10179   if (!isTypeLegal(EVT::getEVT(Ty1)))
10180     return false;
10181
10182   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10183
10184   // Assuming the caller doesn't have a zeroext or signext return parameter,
10185   // truncation all the way down to i1 is valid.
10186   return true;
10187 }
10188
10189
10190 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10191   if (V < 0)
10192     return false;
10193
10194   unsigned Scale = 1;
10195   switch (VT.getSimpleVT().SimpleTy) {
10196   default: return false;
10197   case MVT::i1:
10198   case MVT::i8:
10199     // Scale == 1;
10200     break;
10201   case MVT::i16:
10202     // Scale == 2;
10203     Scale = 2;
10204     break;
10205   case MVT::i32:
10206     // Scale == 4;
10207     Scale = 4;
10208     break;
10209   }
10210
10211   if ((V & (Scale - 1)) != 0)
10212     return false;
10213   V /= Scale;
10214   return V == (V & ((1LL << 5) - 1));
10215 }
10216
10217 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10218                                       const ARMSubtarget *Subtarget) {
10219   bool isNeg = false;
10220   if (V < 0) {
10221     isNeg = true;
10222     V = - V;
10223   }
10224
10225   switch (VT.getSimpleVT().SimpleTy) {
10226   default: return false;
10227   case MVT::i1:
10228   case MVT::i8:
10229   case MVT::i16:
10230   case MVT::i32:
10231     // + imm12 or - imm8
10232     if (isNeg)
10233       return V == (V & ((1LL << 8) - 1));
10234     return V == (V & ((1LL << 12) - 1));
10235   case MVT::f32:
10236   case MVT::f64:
10237     // Same as ARM mode. FIXME: NEON?
10238     if (!Subtarget->hasVFP2())
10239       return false;
10240     if ((V & 3) != 0)
10241       return false;
10242     V >>= 2;
10243     return V == (V & ((1LL << 8) - 1));
10244   }
10245 }
10246
10247 /// isLegalAddressImmediate - Return true if the integer value can be used
10248 /// as the offset of the target addressing mode for load / store of the
10249 /// given type.
10250 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10251                                     const ARMSubtarget *Subtarget) {
10252   if (V == 0)
10253     return true;
10254
10255   if (!VT.isSimple())
10256     return false;
10257
10258   if (Subtarget->isThumb1Only())
10259     return isLegalT1AddressImmediate(V, VT);
10260   else if (Subtarget->isThumb2())
10261     return isLegalT2AddressImmediate(V, VT, Subtarget);
10262
10263   // ARM mode.
10264   if (V < 0)
10265     V = - V;
10266   switch (VT.getSimpleVT().SimpleTy) {
10267   default: return false;
10268   case MVT::i1:
10269   case MVT::i8:
10270   case MVT::i32:
10271     // +- imm12
10272     return V == (V & ((1LL << 12) - 1));
10273   case MVT::i16:
10274     // +- imm8
10275     return V == (V & ((1LL << 8) - 1));
10276   case MVT::f32:
10277   case MVT::f64:
10278     if (!Subtarget->hasVFP2()) // FIXME: NEON?
10279       return false;
10280     if ((V & 3) != 0)
10281       return false;
10282     V >>= 2;
10283     return V == (V & ((1LL << 8) - 1));
10284   }
10285 }
10286
10287 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10288                                                       EVT VT) const {
10289   int Scale = AM.Scale;
10290   if (Scale < 0)
10291     return false;
10292
10293   switch (VT.getSimpleVT().SimpleTy) {
10294   default: return false;
10295   case MVT::i1:
10296   case MVT::i8:
10297   case MVT::i16:
10298   case MVT::i32:
10299     if (Scale == 1)
10300       return true;
10301     // r + r << imm
10302     Scale = Scale & ~1;
10303     return Scale == 2 || Scale == 4 || Scale == 8;
10304   case MVT::i64:
10305     // r + r
10306     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10307       return true;
10308     return false;
10309   case MVT::isVoid:
10310     // Note, we allow "void" uses (basically, uses that aren't loads or
10311     // stores), because arm allows folding a scale into many arithmetic
10312     // operations.  This should be made more precise and revisited later.
10313
10314     // Allow r << imm, but the imm has to be a multiple of two.
10315     if (Scale & 1) return false;
10316     return isPowerOf2_32(Scale);
10317   }
10318 }
10319
10320 /// isLegalAddressingMode - Return true if the addressing mode represented
10321 /// by AM is legal for this target, for a load/store of the specified type.
10322 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10323                                               Type *Ty,
10324                                               unsigned AS) const {
10325   EVT VT = getValueType(*getDataLayout(), Ty, true);
10326   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10327     return false;
10328
10329   // Can never fold addr of global into load/store.
10330   if (AM.BaseGV)
10331     return false;
10332
10333   switch (AM.Scale) {
10334   case 0:  // no scale reg, must be "r+i" or "r", or "i".
10335     break;
10336   case 1:
10337     if (Subtarget->isThumb1Only())
10338       return false;
10339     // FALL THROUGH.
10340   default:
10341     // ARM doesn't support any R+R*scale+imm addr modes.
10342     if (AM.BaseOffs)
10343       return false;
10344
10345     if (!VT.isSimple())
10346       return false;
10347
10348     if (Subtarget->isThumb2())
10349       return isLegalT2ScaledAddressingMode(AM, VT);
10350
10351     int Scale = AM.Scale;
10352     switch (VT.getSimpleVT().SimpleTy) {
10353     default: return false;
10354     case MVT::i1:
10355     case MVT::i8:
10356     case MVT::i32:
10357       if (Scale < 0) Scale = -Scale;
10358       if (Scale == 1)
10359         return true;
10360       // r + r << imm
10361       return isPowerOf2_32(Scale & ~1);
10362     case MVT::i16:
10363     case MVT::i64:
10364       // r + r
10365       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10366         return true;
10367       return false;
10368
10369     case MVT::isVoid:
10370       // Note, we allow "void" uses (basically, uses that aren't loads or
10371       // stores), because arm allows folding a scale into many arithmetic
10372       // operations.  This should be made more precise and revisited later.
10373
10374       // Allow r << imm, but the imm has to be a multiple of two.
10375       if (Scale & 1) return false;
10376       return isPowerOf2_32(Scale);
10377     }
10378   }
10379   return true;
10380 }
10381
10382 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10383 /// icmp immediate, that is the target has icmp instructions which can compare
10384 /// a register against the immediate without having to materialize the
10385 /// immediate into a register.
10386 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10387   // Thumb2 and ARM modes can use cmn for negative immediates.
10388   if (!Subtarget->isThumb())
10389     return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
10390   if (Subtarget->isThumb2())
10391     return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
10392   // Thumb1 doesn't have cmn, and only 8-bit immediates.
10393   return Imm >= 0 && Imm <= 255;
10394 }
10395
10396 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10397 /// *or sub* immediate, that is the target has add or sub instructions which can
10398 /// add a register with the immediate without having to materialize the
10399 /// immediate into a register.
10400 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10401   // Same encoding for add/sub, just flip the sign.
10402   int64_t AbsImm = std::abs(Imm);
10403   if (!Subtarget->isThumb())
10404     return ARM_AM::getSOImmVal(AbsImm) != -1;
10405   if (Subtarget->isThumb2())
10406     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10407   // Thumb1 only has 8-bit unsigned immediate.
10408   return AbsImm >= 0 && AbsImm <= 255;
10409 }
10410
10411 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10412                                       bool isSEXTLoad, SDValue &Base,
10413                                       SDValue &Offset, bool &isInc,
10414                                       SelectionDAG &DAG) {
10415   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10416     return false;
10417
10418   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10419     // AddressingMode 3
10420     Base = Ptr->getOperand(0);
10421     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10422       int RHSC = (int)RHS->getZExtValue();
10423       if (RHSC < 0 && RHSC > -256) {
10424         assert(Ptr->getOpcode() == ISD::ADD);
10425         isInc = false;
10426         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10427         return true;
10428       }
10429     }
10430     isInc = (Ptr->getOpcode() == ISD::ADD);
10431     Offset = Ptr->getOperand(1);
10432     return true;
10433   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10434     // AddressingMode 2
10435     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10436       int RHSC = (int)RHS->getZExtValue();
10437       if (RHSC < 0 && RHSC > -0x1000) {
10438         assert(Ptr->getOpcode() == ISD::ADD);
10439         isInc = false;
10440         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10441         Base = Ptr->getOperand(0);
10442         return true;
10443       }
10444     }
10445
10446     if (Ptr->getOpcode() == ISD::ADD) {
10447       isInc = true;
10448       ARM_AM::ShiftOpc ShOpcVal=
10449         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10450       if (ShOpcVal != ARM_AM::no_shift) {
10451         Base = Ptr->getOperand(1);
10452         Offset = Ptr->getOperand(0);
10453       } else {
10454         Base = Ptr->getOperand(0);
10455         Offset = Ptr->getOperand(1);
10456       }
10457       return true;
10458     }
10459
10460     isInc = (Ptr->getOpcode() == ISD::ADD);
10461     Base = Ptr->getOperand(0);
10462     Offset = Ptr->getOperand(1);
10463     return true;
10464   }
10465
10466   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10467   return false;
10468 }
10469
10470 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10471                                      bool isSEXTLoad, SDValue &Base,
10472                                      SDValue &Offset, bool &isInc,
10473                                      SelectionDAG &DAG) {
10474   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10475     return false;
10476
10477   Base = Ptr->getOperand(0);
10478   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10479     int RHSC = (int)RHS->getZExtValue();
10480     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10481       assert(Ptr->getOpcode() == ISD::ADD);
10482       isInc = false;
10483       Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10484       return true;
10485     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10486       isInc = Ptr->getOpcode() == ISD::ADD;
10487       Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
10488       return true;
10489     }
10490   }
10491
10492   return false;
10493 }
10494
10495 /// getPreIndexedAddressParts - returns true by value, base pointer and
10496 /// offset pointer and addressing mode by reference if the node's address
10497 /// can be legally represented as pre-indexed load / store address.
10498 bool
10499 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10500                                              SDValue &Offset,
10501                                              ISD::MemIndexedMode &AM,
10502                                              SelectionDAG &DAG) const {
10503   if (Subtarget->isThumb1Only())
10504     return false;
10505
10506   EVT VT;
10507   SDValue Ptr;
10508   bool isSEXTLoad = false;
10509   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10510     Ptr = LD->getBasePtr();
10511     VT  = LD->getMemoryVT();
10512     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10513   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10514     Ptr = ST->getBasePtr();
10515     VT  = ST->getMemoryVT();
10516   } else
10517     return false;
10518
10519   bool isInc;
10520   bool isLegal = false;
10521   if (Subtarget->isThumb2())
10522     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10523                                        Offset, isInc, DAG);
10524   else
10525     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10526                                         Offset, isInc, DAG);
10527   if (!isLegal)
10528     return false;
10529
10530   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10531   return true;
10532 }
10533
10534 /// getPostIndexedAddressParts - returns true by value, base pointer and
10535 /// offset pointer and addressing mode by reference if this node can be
10536 /// combined with a load / store to form a post-indexed load / store.
10537 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10538                                                    SDValue &Base,
10539                                                    SDValue &Offset,
10540                                                    ISD::MemIndexedMode &AM,
10541                                                    SelectionDAG &DAG) const {
10542   if (Subtarget->isThumb1Only())
10543     return false;
10544
10545   EVT VT;
10546   SDValue Ptr;
10547   bool isSEXTLoad = false;
10548   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10549     VT  = LD->getMemoryVT();
10550     Ptr = LD->getBasePtr();
10551     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10552   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10553     VT  = ST->getMemoryVT();
10554     Ptr = ST->getBasePtr();
10555   } else
10556     return false;
10557
10558   bool isInc;
10559   bool isLegal = false;
10560   if (Subtarget->isThumb2())
10561     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10562                                        isInc, DAG);
10563   else
10564     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10565                                         isInc, DAG);
10566   if (!isLegal)
10567     return false;
10568
10569   if (Ptr != Base) {
10570     // Swap base ptr and offset to catch more post-index load / store when
10571     // it's legal. In Thumb2 mode, offset must be an immediate.
10572     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10573         !Subtarget->isThumb2())
10574       std::swap(Base, Offset);
10575
10576     // Post-indexed load / store update the base pointer.
10577     if (Ptr != Base)
10578       return false;
10579   }
10580
10581   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10582   return true;
10583 }
10584
10585 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10586                                                       APInt &KnownZero,
10587                                                       APInt &KnownOne,
10588                                                       const SelectionDAG &DAG,
10589                                                       unsigned Depth) const {
10590   unsigned BitWidth = KnownOne.getBitWidth();
10591   KnownZero = KnownOne = APInt(BitWidth, 0);
10592   switch (Op.getOpcode()) {
10593   default: break;
10594   case ARMISD::ADDC:
10595   case ARMISD::ADDE:
10596   case ARMISD::SUBC:
10597   case ARMISD::SUBE:
10598     // These nodes' second result is a boolean
10599     if (Op.getResNo() == 0)
10600       break;
10601     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10602     break;
10603   case ARMISD::CMOV: {
10604     // Bits are known zero/one if known on the LHS and RHS.
10605     DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10606     if (KnownZero == 0 && KnownOne == 0) return;
10607
10608     APInt KnownZeroRHS, KnownOneRHS;
10609     DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10610     KnownZero &= KnownZeroRHS;
10611     KnownOne  &= KnownOneRHS;
10612     return;
10613   }
10614   case ISD::INTRINSIC_W_CHAIN: {
10615     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10616     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10617     switch (IntID) {
10618     default: return;
10619     case Intrinsic::arm_ldaex:
10620     case Intrinsic::arm_ldrex: {
10621       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10622       unsigned MemBits = VT.getScalarType().getSizeInBits();
10623       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10624       return;
10625     }
10626     }
10627   }
10628   }
10629 }
10630
10631 //===----------------------------------------------------------------------===//
10632 //                           ARM Inline Assembly Support
10633 //===----------------------------------------------------------------------===//
10634
10635 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10636   // Looking for "rev" which is V6+.
10637   if (!Subtarget->hasV6Ops())
10638     return false;
10639
10640   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10641   std::string AsmStr = IA->getAsmString();
10642   SmallVector<StringRef, 4> AsmPieces;
10643   SplitString(AsmStr, AsmPieces, ";\n");
10644
10645   switch (AsmPieces.size()) {
10646   default: return false;
10647   case 1:
10648     AsmStr = AsmPieces[0];
10649     AsmPieces.clear();
10650     SplitString(AsmStr, AsmPieces, " \t,");
10651
10652     // rev $0, $1
10653     if (AsmPieces.size() == 3 &&
10654         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10655         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10656       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10657       if (Ty && Ty->getBitWidth() == 32)
10658         return IntrinsicLowering::LowerToByteSwap(CI);
10659     }
10660     break;
10661   }
10662
10663   return false;
10664 }
10665
10666 /// getConstraintType - Given a constraint letter, return the type of
10667 /// constraint it is for this target.
10668 ARMTargetLowering::ConstraintType
10669 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
10670   if (Constraint.size() == 1) {
10671     switch (Constraint[0]) {
10672     default:  break;
10673     case 'l': return C_RegisterClass;
10674     case 'w': return C_RegisterClass;
10675     case 'h': return C_RegisterClass;
10676     case 'x': return C_RegisterClass;
10677     case 't': return C_RegisterClass;
10678     case 'j': return C_Other; // Constant for movw.
10679       // An address with a single base register. Due to the way we
10680       // currently handle addresses it is the same as an 'r' memory constraint.
10681     case 'Q': return C_Memory;
10682     }
10683   } else if (Constraint.size() == 2) {
10684     switch (Constraint[0]) {
10685     default: break;
10686     // All 'U+' constraints are addresses.
10687     case 'U': return C_Memory;
10688     }
10689   }
10690   return TargetLowering::getConstraintType(Constraint);
10691 }
10692
10693 /// Examine constraint type and operand type and determine a weight value.
10694 /// This object must already have been set up with the operand type
10695 /// and the current alternative constraint selected.
10696 TargetLowering::ConstraintWeight
10697 ARMTargetLowering::getSingleConstraintMatchWeight(
10698     AsmOperandInfo &info, const char *constraint) const {
10699   ConstraintWeight weight = CW_Invalid;
10700   Value *CallOperandVal = info.CallOperandVal;
10701     // If we don't have a value, we can't do a match,
10702     // but allow it at the lowest weight.
10703   if (!CallOperandVal)
10704     return CW_Default;
10705   Type *type = CallOperandVal->getType();
10706   // Look at the constraint type.
10707   switch (*constraint) {
10708   default:
10709     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10710     break;
10711   case 'l':
10712     if (type->isIntegerTy()) {
10713       if (Subtarget->isThumb())
10714         weight = CW_SpecificReg;
10715       else
10716         weight = CW_Register;
10717     }
10718     break;
10719   case 'w':
10720     if (type->isFloatingPointTy())
10721       weight = CW_Register;
10722     break;
10723   }
10724   return weight;
10725 }
10726
10727 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10728 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
10729     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
10730   if (Constraint.size() == 1) {
10731     // GCC ARM Constraint Letters
10732     switch (Constraint[0]) {
10733     case 'l': // Low regs or general regs.
10734       if (Subtarget->isThumb())
10735         return RCPair(0U, &ARM::tGPRRegClass);
10736       return RCPair(0U, &ARM::GPRRegClass);
10737     case 'h': // High regs or no regs.
10738       if (Subtarget->isThumb())
10739         return RCPair(0U, &ARM::hGPRRegClass);
10740       break;
10741     case 'r':
10742       if (Subtarget->isThumb1Only())
10743         return RCPair(0U, &ARM::tGPRRegClass);
10744       return RCPair(0U, &ARM::GPRRegClass);
10745     case 'w':
10746       if (VT == MVT::Other)
10747         break;
10748       if (VT == MVT::f32)
10749         return RCPair(0U, &ARM::SPRRegClass);
10750       if (VT.getSizeInBits() == 64)
10751         return RCPair(0U, &ARM::DPRRegClass);
10752       if (VT.getSizeInBits() == 128)
10753         return RCPair(0U, &ARM::QPRRegClass);
10754       break;
10755     case 'x':
10756       if (VT == MVT::Other)
10757         break;
10758       if (VT == MVT::f32)
10759         return RCPair(0U, &ARM::SPR_8RegClass);
10760       if (VT.getSizeInBits() == 64)
10761         return RCPair(0U, &ARM::DPR_8RegClass);
10762       if (VT.getSizeInBits() == 128)
10763         return RCPair(0U, &ARM::QPR_8RegClass);
10764       break;
10765     case 't':
10766       if (VT == MVT::f32)
10767         return RCPair(0U, &ARM::SPRRegClass);
10768       break;
10769     }
10770   }
10771   if (StringRef("{cc}").equals_lower(Constraint))
10772     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10773
10774   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10775 }
10776
10777 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10778 /// vector.  If it is invalid, don't add anything to Ops.
10779 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10780                                                      std::string &Constraint,
10781                                                      std::vector<SDValue>&Ops,
10782                                                      SelectionDAG &DAG) const {
10783   SDValue Result;
10784
10785   // Currently only support length 1 constraints.
10786   if (Constraint.length() != 1) return;
10787
10788   char ConstraintLetter = Constraint[0];
10789   switch (ConstraintLetter) {
10790   default: break;
10791   case 'j':
10792   case 'I': case 'J': case 'K': case 'L':
10793   case 'M': case 'N': case 'O':
10794     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10795     if (!C)
10796       return;
10797
10798     int64_t CVal64 = C->getSExtValue();
10799     int CVal = (int) CVal64;
10800     // None of these constraints allow values larger than 32 bits.  Check
10801     // that the value fits in an int.
10802     if (CVal != CVal64)
10803       return;
10804
10805     switch (ConstraintLetter) {
10806       case 'j':
10807         // Constant suitable for movw, must be between 0 and
10808         // 65535.
10809         if (Subtarget->hasV6T2Ops())
10810           if (CVal >= 0 && CVal <= 65535)
10811             break;
10812         return;
10813       case 'I':
10814         if (Subtarget->isThumb1Only()) {
10815           // This must be a constant between 0 and 255, for ADD
10816           // immediates.
10817           if (CVal >= 0 && CVal <= 255)
10818             break;
10819         } else if (Subtarget->isThumb2()) {
10820           // A constant that can be used as an immediate value in a
10821           // data-processing instruction.
10822           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10823             break;
10824         } else {
10825           // A constant that can be used as an immediate value in a
10826           // data-processing instruction.
10827           if (ARM_AM::getSOImmVal(CVal) != -1)
10828             break;
10829         }
10830         return;
10831
10832       case 'J':
10833         if (Subtarget->isThumb()) {  // FIXME thumb2
10834           // This must be a constant between -255 and -1, for negated ADD
10835           // immediates. This can be used in GCC with an "n" modifier that
10836           // prints the negated value, for use with SUB instructions. It is
10837           // not useful otherwise but is implemented for compatibility.
10838           if (CVal >= -255 && CVal <= -1)
10839             break;
10840         } else {
10841           // This must be a constant between -4095 and 4095. It is not clear
10842           // what this constraint is intended for. Implemented for
10843           // compatibility with GCC.
10844           if (CVal >= -4095 && CVal <= 4095)
10845             break;
10846         }
10847         return;
10848
10849       case 'K':
10850         if (Subtarget->isThumb1Only()) {
10851           // A 32-bit value where only one byte has a nonzero value. Exclude
10852           // zero to match GCC. This constraint is used by GCC internally for
10853           // constants that can be loaded with a move/shift combination.
10854           // It is not useful otherwise but is implemented for compatibility.
10855           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10856             break;
10857         } else if (Subtarget->isThumb2()) {
10858           // A constant whose bitwise inverse can be used as an immediate
10859           // value in a data-processing instruction. This can be used in GCC
10860           // with a "B" modifier that prints the inverted value, for use with
10861           // BIC and MVN instructions. It is not useful otherwise but is
10862           // implemented for compatibility.
10863           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10864             break;
10865         } else {
10866           // A constant whose bitwise inverse can be used as an immediate
10867           // value in a data-processing instruction. This can be used in GCC
10868           // with a "B" modifier that prints the inverted value, for use with
10869           // BIC and MVN instructions. It is not useful otherwise but is
10870           // implemented for compatibility.
10871           if (ARM_AM::getSOImmVal(~CVal) != -1)
10872             break;
10873         }
10874         return;
10875
10876       case 'L':
10877         if (Subtarget->isThumb1Only()) {
10878           // This must be a constant between -7 and 7,
10879           // for 3-operand ADD/SUB immediate instructions.
10880           if (CVal >= -7 && CVal < 7)
10881             break;
10882         } else if (Subtarget->isThumb2()) {
10883           // A constant whose negation can be used as an immediate value in a
10884           // data-processing instruction. This can be used in GCC with an "n"
10885           // modifier that prints the negated value, for use with SUB
10886           // instructions. It is not useful otherwise but is implemented for
10887           // compatibility.
10888           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10889             break;
10890         } else {
10891           // A constant whose negation can be used as an immediate value in a
10892           // data-processing instruction. This can be used in GCC with an "n"
10893           // modifier that prints the negated value, for use with SUB
10894           // instructions. It is not useful otherwise but is implemented for
10895           // compatibility.
10896           if (ARM_AM::getSOImmVal(-CVal) != -1)
10897             break;
10898         }
10899         return;
10900
10901       case 'M':
10902         if (Subtarget->isThumb()) { // FIXME thumb2
10903           // This must be a multiple of 4 between 0 and 1020, for
10904           // ADD sp + immediate.
10905           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10906             break;
10907         } else {
10908           // A power of two or a constant between 0 and 32.  This is used in
10909           // GCC for the shift amount on shifted register operands, but it is
10910           // useful in general for any shift amounts.
10911           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10912             break;
10913         }
10914         return;
10915
10916       case 'N':
10917         if (Subtarget->isThumb()) {  // FIXME thumb2
10918           // This must be a constant between 0 and 31, for shift amounts.
10919           if (CVal >= 0 && CVal <= 31)
10920             break;
10921         }
10922         return;
10923
10924       case 'O':
10925         if (Subtarget->isThumb()) {  // FIXME thumb2
10926           // This must be a multiple of 4 between -508 and 508, for
10927           // ADD/SUB sp = sp + immediate.
10928           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10929             break;
10930         }
10931         return;
10932     }
10933     Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
10934     break;
10935   }
10936
10937   if (Result.getNode()) {
10938     Ops.push_back(Result);
10939     return;
10940   }
10941   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10942 }
10943
10944 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10945   assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10946   unsigned Opcode = Op->getOpcode();
10947   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10948          "Invalid opcode for Div/Rem lowering");
10949   bool isSigned = (Opcode == ISD::SDIVREM);
10950   EVT VT = Op->getValueType(0);
10951   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10952
10953   RTLIB::Libcall LC;
10954   switch (VT.getSimpleVT().SimpleTy) {
10955   default: llvm_unreachable("Unexpected request for libcall!");
10956   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
10957   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10958   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10959   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10960   }
10961
10962   SDValue InChain = DAG.getEntryNode();
10963
10964   TargetLowering::ArgListTy Args;
10965   TargetLowering::ArgListEntry Entry;
10966   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
10967     EVT ArgVT = Op->getOperand(i).getValueType();
10968     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10969     Entry.Node = Op->getOperand(i);
10970     Entry.Ty = ArgTy;
10971     Entry.isSExt = isSigned;
10972     Entry.isZExt = !isSigned;
10973     Args.push_back(Entry);
10974   }
10975
10976   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
10977                                          getPointerTy(DAG.getDataLayout()));
10978
10979   Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
10980
10981   SDLoc dl(Op);
10982   TargetLowering::CallLoweringInfo CLI(DAG);
10983   CLI.setDebugLoc(dl).setChain(InChain)
10984     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
10985     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
10986
10987   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
10988   return CallInfo.first;
10989 }
10990
10991 SDValue
10992 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
10993   assert(Subtarget->isTargetWindows() && "unsupported target platform");
10994   SDLoc DL(Op);
10995
10996   // Get the inputs.
10997   SDValue Chain = Op.getOperand(0);
10998   SDValue Size  = Op.getOperand(1);
10999
11000   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
11001                               DAG.getConstant(2, DL, MVT::i32));
11002
11003   SDValue Flag;
11004   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
11005   Flag = Chain.getValue(1);
11006
11007   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11008   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
11009
11010   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
11011   Chain = NewSP.getValue(1);
11012
11013   SDValue Ops[2] = { NewSP, Chain };
11014   return DAG.getMergeValues(Ops, DL);
11015 }
11016
11017 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
11018   assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
11019          "Unexpected type for custom-lowering FP_EXTEND");
11020
11021   RTLIB::Libcall LC;
11022   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
11023
11024   SDValue SrcVal = Op.getOperand(0);
11025   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
11026                      /*isSigned*/ false, SDLoc(Op)).first;
11027 }
11028
11029 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
11030   assert(Op.getOperand(0).getValueType() == MVT::f64 &&
11031          Subtarget->isFPOnlySP() &&
11032          "Unexpected type for custom-lowering FP_ROUND");
11033
11034   RTLIB::Libcall LC;
11035   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
11036
11037   SDValue SrcVal = Op.getOperand(0);
11038   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
11039                      /*isSigned*/ false, SDLoc(Op)).first;
11040 }
11041
11042 bool
11043 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11044   // The ARM target isn't yet aware of offsets.
11045   return false;
11046 }
11047
11048 bool ARM::isBitFieldInvertedMask(unsigned v) {
11049   if (v == 0xffffffff)
11050     return false;
11051
11052   // there can be 1's on either or both "outsides", all the "inside"
11053   // bits must be 0's
11054   return isShiftedMask_32(~v);
11055 }
11056
11057 /// isFPImmLegal - Returns true if the target can instruction select the
11058 /// specified FP immediate natively. If false, the legalizer will
11059 /// materialize the FP immediate as a load from a constant pool.
11060 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
11061   if (!Subtarget->hasVFP3())
11062     return false;
11063   if (VT == MVT::f32)
11064     return ARM_AM::getFP32Imm(Imm) != -1;
11065   if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
11066     return ARM_AM::getFP64Imm(Imm) != -1;
11067   return false;
11068 }
11069
11070 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
11071 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
11072 /// specified in the intrinsic calls.
11073 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11074                                            const CallInst &I,
11075                                            unsigned Intrinsic) const {
11076   switch (Intrinsic) {
11077   case Intrinsic::arm_neon_vld1:
11078   case Intrinsic::arm_neon_vld2:
11079   case Intrinsic::arm_neon_vld3:
11080   case Intrinsic::arm_neon_vld4:
11081   case Intrinsic::arm_neon_vld2lane:
11082   case Intrinsic::arm_neon_vld3lane:
11083   case Intrinsic::arm_neon_vld4lane: {
11084     Info.opc = ISD::INTRINSIC_W_CHAIN;
11085     // Conservatively set memVT to the entire set of vectors loaded.
11086     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
11087     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11088     Info.ptrVal = I.getArgOperand(0);
11089     Info.offset = 0;
11090     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11091     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11092     Info.vol = false; // volatile loads with NEON intrinsics not supported
11093     Info.readMem = true;
11094     Info.writeMem = false;
11095     return true;
11096   }
11097   case Intrinsic::arm_neon_vst1:
11098   case Intrinsic::arm_neon_vst2:
11099   case Intrinsic::arm_neon_vst3:
11100   case Intrinsic::arm_neon_vst4:
11101   case Intrinsic::arm_neon_vst2lane:
11102   case Intrinsic::arm_neon_vst3lane:
11103   case Intrinsic::arm_neon_vst4lane: {
11104     Info.opc = ISD::INTRINSIC_VOID;
11105     // Conservatively set memVT to the entire set of vectors stored.
11106     unsigned NumElts = 0;
11107     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11108       Type *ArgTy = I.getArgOperand(ArgI)->getType();
11109       if (!ArgTy->isVectorTy())
11110         break;
11111       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
11112     }
11113     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11114     Info.ptrVal = I.getArgOperand(0);
11115     Info.offset = 0;
11116     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11117     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11118     Info.vol = false; // volatile stores with NEON intrinsics not supported
11119     Info.readMem = false;
11120     Info.writeMem = true;
11121     return true;
11122   }
11123   case Intrinsic::arm_ldaex:
11124   case Intrinsic::arm_ldrex: {
11125     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11126     Info.opc = ISD::INTRINSIC_W_CHAIN;
11127     Info.memVT = MVT::getVT(PtrTy->getElementType());
11128     Info.ptrVal = I.getArgOperand(0);
11129     Info.offset = 0;
11130     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11131     Info.vol = true;
11132     Info.readMem = true;
11133     Info.writeMem = false;
11134     return true;
11135   }
11136   case Intrinsic::arm_stlex:
11137   case Intrinsic::arm_strex: {
11138     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11139     Info.opc = ISD::INTRINSIC_W_CHAIN;
11140     Info.memVT = MVT::getVT(PtrTy->getElementType());
11141     Info.ptrVal = I.getArgOperand(1);
11142     Info.offset = 0;
11143     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11144     Info.vol = true;
11145     Info.readMem = false;
11146     Info.writeMem = true;
11147     return true;
11148   }
11149   case Intrinsic::arm_stlexd:
11150   case Intrinsic::arm_strexd: {
11151     Info.opc = ISD::INTRINSIC_W_CHAIN;
11152     Info.memVT = MVT::i64;
11153     Info.ptrVal = I.getArgOperand(2);
11154     Info.offset = 0;
11155     Info.align = 8;
11156     Info.vol = true;
11157     Info.readMem = false;
11158     Info.writeMem = true;
11159     return true;
11160   }
11161   case Intrinsic::arm_ldaexd:
11162   case Intrinsic::arm_ldrexd: {
11163     Info.opc = ISD::INTRINSIC_W_CHAIN;
11164     Info.memVT = MVT::i64;
11165     Info.ptrVal = I.getArgOperand(0);
11166     Info.offset = 0;
11167     Info.align = 8;
11168     Info.vol = true;
11169     Info.readMem = true;
11170     Info.writeMem = false;
11171     return true;
11172   }
11173   default:
11174     break;
11175   }
11176
11177   return false;
11178 }
11179
11180 /// \brief Returns true if it is beneficial to convert a load of a constant
11181 /// to just the constant itself.
11182 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11183                                                           Type *Ty) const {
11184   assert(Ty->isIntegerTy());
11185
11186   unsigned Bits = Ty->getPrimitiveSizeInBits();
11187   if (Bits == 0 || Bits > 32)
11188     return false;
11189   return true;
11190 }
11191
11192 bool ARMTargetLowering::hasLoadLinkedStoreConditional() const { return true; }
11193
11194 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
11195                                         ARM_MB::MemBOpt Domain) const {
11196   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11197
11198   // First, if the target has no DMB, see what fallback we can use.
11199   if (!Subtarget->hasDataBarrier()) {
11200     // Some ARMv6 cpus can support data barriers with an mcr instruction.
11201     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
11202     // here.
11203     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
11204       Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
11205       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
11206                         Builder.getInt32(0), Builder.getInt32(7),
11207                         Builder.getInt32(10), Builder.getInt32(5)};
11208       return Builder.CreateCall(MCR, args);
11209     } else {
11210       // Instead of using barriers, atomic accesses on these subtargets use
11211       // libcalls.
11212       llvm_unreachable("makeDMB on a target so old that it has no barriers");
11213     }
11214   } else {
11215     Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
11216     // Only a full system barrier exists in the M-class architectures.
11217     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
11218     Constant *CDomain = Builder.getInt32(Domain);
11219     return Builder.CreateCall(DMB, CDomain);
11220   }
11221 }
11222
11223 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11224 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11225                                          AtomicOrdering Ord, bool IsStore,
11226                                          bool IsLoad) const {
11227   if (!getInsertFencesForAtomic())
11228     return nullptr;
11229
11230   switch (Ord) {
11231   case NotAtomic:
11232   case Unordered:
11233     llvm_unreachable("Invalid fence: unordered/non-atomic");
11234   case Monotonic:
11235   case Acquire:
11236     return nullptr; // Nothing to do
11237   case SequentiallyConsistent:
11238     if (!IsStore)
11239       return nullptr; // Nothing to do
11240     /*FALLTHROUGH*/
11241   case Release:
11242   case AcquireRelease:
11243     if (Subtarget->isSwift())
11244       return makeDMB(Builder, ARM_MB::ISHST);
11245     // FIXME: add a comment with a link to documentation justifying this.
11246     else
11247       return makeDMB(Builder, ARM_MB::ISH);
11248   }
11249   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
11250 }
11251
11252 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11253                                           AtomicOrdering Ord, bool IsStore,
11254                                           bool IsLoad) const {
11255   if (!getInsertFencesForAtomic())
11256     return nullptr;
11257
11258   switch (Ord) {
11259   case NotAtomic:
11260   case Unordered:
11261     llvm_unreachable("Invalid fence: unordered/not-atomic");
11262   case Monotonic:
11263   case Release:
11264     return nullptr; // Nothing to do
11265   case Acquire:
11266   case AcquireRelease:
11267   case SequentiallyConsistent:
11268     return makeDMB(Builder, ARM_MB::ISH);
11269   }
11270   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
11271 }
11272
11273 // Loads and stores less than 64-bits are already atomic; ones above that
11274 // are doomed anyway, so defer to the default libcall and blame the OS when
11275 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11276 // anything for those.
11277 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11278   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11279   return (Size == 64) && !Subtarget->isMClass();
11280 }
11281
11282 // Loads and stores less than 64-bits are already atomic; ones above that
11283 // are doomed anyway, so defer to the default libcall and blame the OS when
11284 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11285 // anything for those.
11286 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
11287 // guarantee, see DDI0406C ARM architecture reference manual,
11288 // sections A8.8.72-74 LDRD)
11289 bool ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11290   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11291   return (Size == 64) && !Subtarget->isMClass();
11292 }
11293
11294 // For the real atomic operations, we have ldrex/strex up to 32 bits,
11295 // and up to 64 bits on the non-M profiles
11296 TargetLoweringBase::AtomicRMWExpansionKind
11297 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11298   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11299   return (Size <= (Subtarget->isMClass() ? 32U : 64U))
11300              ? AtomicRMWExpansionKind::LLSC
11301              : AtomicRMWExpansionKind::None;
11302 }
11303
11304 // This has so far only been implemented for MachO.
11305 bool ARMTargetLowering::useLoadStackGuardNode() const {
11306   return Subtarget->isTargetMachO();
11307 }
11308
11309 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
11310                                                   unsigned &Cost) const {
11311   // If we do not have NEON, vector types are not natively supported.
11312   if (!Subtarget->hasNEON())
11313     return false;
11314
11315   // Floating point values and vector values map to the same register file.
11316   // Therefore, althought we could do a store extract of a vector type, this is
11317   // better to leave at float as we have more freedom in the addressing mode for
11318   // those.
11319   if (VectorTy->isFPOrFPVectorTy())
11320     return false;
11321
11322   // If the index is unknown at compile time, this is very expensive to lower
11323   // and it is not possible to combine the store with the extract.
11324   if (!isa<ConstantInt>(Idx))
11325     return false;
11326
11327   assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
11328   unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
11329   // We can do a store + vector extract on any vector that fits perfectly in a D
11330   // or Q register.
11331   if (BitWidth == 64 || BitWidth == 128) {
11332     Cost = 0;
11333     return true;
11334   }
11335   return false;
11336 }
11337
11338 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11339                                          AtomicOrdering Ord) const {
11340   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11341   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11342   bool IsAcquire = isAtLeastAcquire(Ord);
11343
11344   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
11345   // intrinsic must return {i32, i32} and we have to recombine them into a
11346   // single i64 here.
11347   if (ValTy->getPrimitiveSizeInBits() == 64) {
11348     Intrinsic::ID Int =
11349         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
11350     Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
11351
11352     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11353     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
11354
11355     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11356     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11357     if (!Subtarget->isLittle())
11358       std::swap (Lo, Hi);
11359     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11360     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11361     return Builder.CreateOr(
11362         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
11363   }
11364
11365   Type *Tys[] = { Addr->getType() };
11366   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
11367   Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
11368
11369   return Builder.CreateTruncOrBitCast(
11370       Builder.CreateCall(Ldrex, Addr),
11371       cast<PointerType>(Addr->getType())->getElementType());
11372 }
11373
11374 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
11375                                                Value *Addr,
11376                                                AtomicOrdering Ord) const {
11377   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11378   bool IsRelease = isAtLeastRelease(Ord);
11379
11380   // Since the intrinsics must have legal type, the i64 intrinsics take two
11381   // parameters: "i32, i32". We must marshal Val into the appropriate form
11382   // before the call.
11383   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
11384     Intrinsic::ID Int =
11385         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
11386     Function *Strex = Intrinsic::getDeclaration(M, Int);
11387     Type *Int32Ty = Type::getInt32Ty(M->getContext());
11388
11389     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
11390     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
11391     if (!Subtarget->isLittle())
11392       std::swap (Lo, Hi);
11393     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11394     return Builder.CreateCall(Strex, {Lo, Hi, Addr});
11395   }
11396
11397   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
11398   Type *Tys[] = { Addr->getType() };
11399   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
11400
11401   return Builder.CreateCall(
11402       Strex, {Builder.CreateZExtOrBitCast(
11403                   Val, Strex->getFunctionType()->getParamType(0)),
11404               Addr});
11405 }
11406
11407 /// \brief Lower an interleaved load into a vldN intrinsic.
11408 ///
11409 /// E.g. Lower an interleaved load (Factor = 2):
11410 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
11411 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
11412 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
11413 ///
11414 ///      Into:
11415 ///        %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
11416 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
11417 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
11418 bool ARMTargetLowering::lowerInterleavedLoad(
11419     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
11420     ArrayRef<unsigned> Indices, unsigned Factor) const {
11421   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
11422          "Invalid interleave factor");
11423   assert(!Shuffles.empty() && "Empty shufflevector input");
11424   assert(Shuffles.size() == Indices.size() &&
11425          "Unmatched number of shufflevectors and indices");
11426
11427   VectorType *VecTy = Shuffles[0]->getType();
11428   Type *EltTy = VecTy->getVectorElementType();
11429
11430   const DataLayout *DL = getDataLayout();
11431   unsigned VecSize = DL->getTypeAllocSizeInBits(VecTy);
11432   bool EltIs64Bits = DL->getTypeAllocSizeInBits(EltTy) == 64;
11433
11434   // Skip illegal vector types and vector types of i64/f64 element (vldN doesn't
11435   // support i64/f64 element).
11436   if ((VecSize != 64 && VecSize != 128) || EltIs64Bits)
11437     return false;
11438
11439   // A pointer vector can not be the return type of the ldN intrinsics. Need to
11440   // load integer vectors first and then convert to pointer vectors.
11441   if (EltTy->isPointerTy())
11442     VecTy = VectorType::get(DL->getIntPtrType(EltTy),
11443                             VecTy->getVectorNumElements());
11444
11445   static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
11446                                             Intrinsic::arm_neon_vld3,
11447                                             Intrinsic::arm_neon_vld4};
11448
11449   Function *VldnFunc =
11450       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], VecTy);
11451
11452   IRBuilder<> Builder(LI);
11453   SmallVector<Value *, 2> Ops;
11454
11455   Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
11456   Ops.push_back(Builder.CreateBitCast(LI->getPointerOperand(), Int8Ptr));
11457   Ops.push_back(Builder.getInt32(LI->getAlignment()));
11458
11459   CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
11460
11461   // Replace uses of each shufflevector with the corresponding vector loaded
11462   // by ldN.
11463   for (unsigned i = 0; i < Shuffles.size(); i++) {
11464     ShuffleVectorInst *SV = Shuffles[i];
11465     unsigned Index = Indices[i];
11466
11467     Value *SubVec = Builder.CreateExtractValue(VldN, Index);
11468
11469     // Convert the integer vector to pointer vector if the element is pointer.
11470     if (EltTy->isPointerTy())
11471       SubVec = Builder.CreateIntToPtr(SubVec, SV->getType());
11472
11473     SV->replaceAllUsesWith(SubVec);
11474   }
11475
11476   return true;
11477 }
11478
11479 /// \brief Get a mask consisting of sequential integers starting from \p Start.
11480 ///
11481 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
11482 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
11483                                    unsigned NumElts) {
11484   SmallVector<Constant *, 16> Mask;
11485   for (unsigned i = 0; i < NumElts; i++)
11486     Mask.push_back(Builder.getInt32(Start + i));
11487
11488   return ConstantVector::get(Mask);
11489 }
11490
11491 /// \brief Lower an interleaved store into a vstN intrinsic.
11492 ///
11493 /// E.g. Lower an interleaved store (Factor = 3):
11494 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
11495 ///                                  <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
11496 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
11497 ///
11498 ///      Into:
11499 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
11500 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
11501 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
11502 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
11503 ///
11504 /// Note that the new shufflevectors will be removed and we'll only generate one
11505 /// vst3 instruction in CodeGen.
11506 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
11507                                               ShuffleVectorInst *SVI,
11508                                               unsigned Factor) const {
11509   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
11510          "Invalid interleave factor");
11511
11512   VectorType *VecTy = SVI->getType();
11513   assert(VecTy->getVectorNumElements() % Factor == 0 &&
11514          "Invalid interleaved store");
11515
11516   unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
11517   Type *EltTy = VecTy->getVectorElementType();
11518   VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
11519
11520   const DataLayout *DL = getDataLayout();
11521   unsigned SubVecSize = DL->getTypeAllocSizeInBits(SubVecTy);
11522   bool EltIs64Bits = DL->getTypeAllocSizeInBits(EltTy) == 64;
11523
11524   // Skip illegal sub vector types and vector types of i64/f64 element (vstN
11525   // doesn't support i64/f64 element).
11526   if ((SubVecSize != 64 && SubVecSize != 128) || EltIs64Bits)
11527     return false;
11528
11529   Value *Op0 = SVI->getOperand(0);
11530   Value *Op1 = SVI->getOperand(1);
11531   IRBuilder<> Builder(SI);
11532
11533   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
11534   // vectors to integer vectors.
11535   if (EltTy->isPointerTy()) {
11536     Type *IntTy = DL->getIntPtrType(EltTy);
11537
11538     // Convert to the corresponding integer vector.
11539     Type *IntVecTy =
11540         VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
11541     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
11542     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
11543
11544     SubVecTy = VectorType::get(IntTy, NumSubElts);
11545   }
11546
11547   static Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
11548                                        Intrinsic::arm_neon_vst3,
11549                                        Intrinsic::arm_neon_vst4};
11550   Function *VstNFunc = Intrinsic::getDeclaration(
11551       SI->getModule(), StoreInts[Factor - 2], SubVecTy);
11552
11553   SmallVector<Value *, 6> Ops;
11554
11555   Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
11556   Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), Int8Ptr));
11557
11558   // Split the shufflevector operands into sub vectors for the new vstN call.
11559   for (unsigned i = 0; i < Factor; i++)
11560     Ops.push_back(Builder.CreateShuffleVector(
11561         Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
11562
11563   Ops.push_back(Builder.getInt32(SI->getAlignment()));
11564   Builder.CreateCall(VstNFunc, Ops);
11565   return true;
11566 }
11567
11568 enum HABaseType {
11569   HA_UNKNOWN = 0,
11570   HA_FLOAT,
11571   HA_DOUBLE,
11572   HA_VECT64,
11573   HA_VECT128
11574 };
11575
11576 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
11577                                    uint64_t &Members) {
11578   if (const StructType *ST = dyn_cast<StructType>(Ty)) {
11579     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
11580       uint64_t SubMembers = 0;
11581       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
11582         return false;
11583       Members += SubMembers;
11584     }
11585   } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
11586     uint64_t SubMembers = 0;
11587     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
11588       return false;
11589     Members += SubMembers * AT->getNumElements();
11590   } else if (Ty->isFloatTy()) {
11591     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
11592       return false;
11593     Members = 1;
11594     Base = HA_FLOAT;
11595   } else if (Ty->isDoubleTy()) {
11596     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
11597       return false;
11598     Members = 1;
11599     Base = HA_DOUBLE;
11600   } else if (const VectorType *VT = dyn_cast<VectorType>(Ty)) {
11601     Members = 1;
11602     switch (Base) {
11603     case HA_FLOAT:
11604     case HA_DOUBLE:
11605       return false;
11606     case HA_VECT64:
11607       return VT->getBitWidth() == 64;
11608     case HA_VECT128:
11609       return VT->getBitWidth() == 128;
11610     case HA_UNKNOWN:
11611       switch (VT->getBitWidth()) {
11612       case 64:
11613         Base = HA_VECT64;
11614         return true;
11615       case 128:
11616         Base = HA_VECT128;
11617         return true;
11618       default:
11619         return false;
11620       }
11621     }
11622   }
11623
11624   return (Members > 0 && Members <= 4);
11625 }
11626
11627 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
11628 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
11629 /// passing according to AAPCS rules.
11630 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
11631     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11632   if (getEffectiveCallingConv(CallConv, isVarArg) !=
11633       CallingConv::ARM_AAPCS_VFP)
11634     return false;
11635
11636   HABaseType Base = HA_UNKNOWN;
11637   uint64_t Members = 0;
11638   bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
11639   DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
11640
11641   bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
11642   return IsHA || IsIntArray;
11643 }