51f8d562fe112ad88c34a2108774f77d9b936ca5
[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   if (VT.isInteger()) {
147     setOperationAction(ISD::SABSDIFF, VT, Legal);
148     setOperationAction(ISD::UABSDIFF, VT, Legal);
149   }
150   if (!VT.isFloatingPoint() &&
151       VT != MVT::v2i64 && VT != MVT::v1i64)
152     for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
153       setOperationAction(Opcode, VT, Legal);
154
155 }
156
157 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
158   addRegisterClass(VT, &ARM::DPRRegClass);
159   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
160 }
161
162 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
163   addRegisterClass(VT, &ARM::DPairRegClass);
164   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
165 }
166
167 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM,
168                                      const ARMSubtarget &STI)
169     : TargetLowering(TM), Subtarget(&STI) {
170   RegInfo = Subtarget->getRegisterInfo();
171   Itins = Subtarget->getInstrItineraryData();
172
173   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
174
175   if (Subtarget->isTargetMachO()) {
176     // Uses VFP for Thumb libfuncs if available.
177     if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
178         Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) {
179       static const struct {
180         const RTLIB::Libcall Op;
181         const char * const Name;
182         const ISD::CondCode Cond;
183       } LibraryCalls[] = {
184         // Single-precision floating-point arithmetic.
185         { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID },
186         { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID },
187         { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID },
188         { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID },
189
190         // Double-precision floating-point arithmetic.
191         { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID },
192         { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID },
193         { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID },
194         { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID },
195
196         // Single-precision comparisons.
197         { RTLIB::OEQ_F32, "__eqsf2vfp",    ISD::SETNE },
198         { RTLIB::UNE_F32, "__nesf2vfp",    ISD::SETNE },
199         { RTLIB::OLT_F32, "__ltsf2vfp",    ISD::SETNE },
200         { RTLIB::OLE_F32, "__lesf2vfp",    ISD::SETNE },
201         { RTLIB::OGE_F32, "__gesf2vfp",    ISD::SETNE },
202         { RTLIB::OGT_F32, "__gtsf2vfp",    ISD::SETNE },
203         { RTLIB::UO_F32,  "__unordsf2vfp", ISD::SETNE },
204         { RTLIB::O_F32,   "__unordsf2vfp", ISD::SETEQ },
205
206         // Double-precision comparisons.
207         { RTLIB::OEQ_F64, "__eqdf2vfp",    ISD::SETNE },
208         { RTLIB::UNE_F64, "__nedf2vfp",    ISD::SETNE },
209         { RTLIB::OLT_F64, "__ltdf2vfp",    ISD::SETNE },
210         { RTLIB::OLE_F64, "__ledf2vfp",    ISD::SETNE },
211         { RTLIB::OGE_F64, "__gedf2vfp",    ISD::SETNE },
212         { RTLIB::OGT_F64, "__gtdf2vfp",    ISD::SETNE },
213         { RTLIB::UO_F64,  "__unorddf2vfp", ISD::SETNE },
214         { RTLIB::O_F64,   "__unorddf2vfp", ISD::SETEQ },
215
216         // Floating-point to integer conversions.
217         // i64 conversions are done via library routines even when generating VFP
218         // instructions, so use the same ones.
219         { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp",    ISD::SETCC_INVALID },
220         { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID },
221         { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp",    ISD::SETCC_INVALID },
222         { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID },
223
224         // Conversions between floating types.
225         { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp",  ISD::SETCC_INVALID },
226         { RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp", ISD::SETCC_INVALID },
227
228         // Integer to floating-point conversions.
229         // i64 conversions are done via library routines even when generating VFP
230         // instructions, so use the same ones.
231         // FIXME: There appears to be some naming inconsistency in ARM libgcc:
232         // e.g., __floatunsidf vs. __floatunssidfvfp.
233         { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp",    ISD::SETCC_INVALID },
234         { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID },
235         { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp",    ISD::SETCC_INVALID },
236         { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID },
237       };
238
239       for (const auto &LC : LibraryCalls) {
240         setLibcallName(LC.Op, LC.Name);
241         if (LC.Cond != ISD::SETCC_INVALID)
242           setCmpLibcallCC(LC.Op, LC.Cond);
243       }
244     }
245
246     // Set the correct calling convention for ARMv7k WatchOS. It's just
247     // AAPCS_VFP for functions as simple as libcalls.
248     if (Subtarget->isTargetWatchOS()) {
249       for (int i = 0; i < RTLIB::UNKNOWN_LIBCALL; ++i)
250         setLibcallCallingConv((RTLIB::Libcall)i, CallingConv::ARM_AAPCS_VFP);
251     }
252   }
253
254   // These libcalls are not available in 32-bit.
255   setLibcallName(RTLIB::SHL_I128, nullptr);
256   setLibcallName(RTLIB::SRL_I128, nullptr);
257   setLibcallName(RTLIB::SRA_I128, nullptr);
258
259   // RTLIB
260   if (Subtarget->isAAPCS_ABI() &&
261       (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() ||
262        Subtarget->isTargetAndroid())) {
263     static const struct {
264       const RTLIB::Libcall Op;
265       const char * const Name;
266       const CallingConv::ID CC;
267       const ISD::CondCode Cond;
268     } LibraryCalls[] = {
269       // Double-precision floating-point arithmetic helper functions
270       // RTABI chapter 4.1.2, Table 2
271       { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
272       { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
273       { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
274       { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
275
276       // Double-precision floating-point comparison helper functions
277       // RTABI chapter 4.1.2, Table 3
278       { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
279       { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
280       { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
281       { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
282       { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
283       { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
284       { RTLIB::UO_F64,  "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
285       { RTLIB::O_F64,   "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
286
287       // Single-precision floating-point arithmetic helper functions
288       // RTABI chapter 4.1.2, Table 4
289       { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
290       { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
291       { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
292       { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
293
294       // Single-precision floating-point comparison helper functions
295       // RTABI chapter 4.1.2, Table 5
296       { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
297       { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
298       { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
299       { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
300       { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
301       { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
302       { RTLIB::UO_F32,  "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
303       { RTLIB::O_F32,   "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
304
305       // Floating-point to integer conversions.
306       // RTABI chapter 4.1.2, Table 6
307       { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
308       { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
309       { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
310       { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
311       { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
312       { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
313       { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
314       { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
315
316       // Conversions between floating types.
317       // RTABI chapter 4.1.2, Table 7
318       { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
319       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
320       { RTLIB::FPEXT_F32_F64,   "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
321
322       // Integer to floating-point conversions.
323       // RTABI chapter 4.1.2, Table 8
324       { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
325       { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
326       { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
327       { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
328       { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
329       { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
330       { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
331       { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
332
333       // Long long helper functions
334       // RTABI chapter 4.2, Table 9
335       { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
336       { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
337       { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
338       { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
339
340       // Integer division functions
341       // RTABI chapter 4.3.1
342       { RTLIB::SDIV_I8,  "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
343       { RTLIB::SDIV_I16, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
344       { RTLIB::SDIV_I32, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
345       { RTLIB::SDIV_I64, "__aeabi_ldivmod",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
346       { RTLIB::UDIV_I8,  "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
347       { RTLIB::UDIV_I16, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
348       { RTLIB::UDIV_I32, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
349       { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
350     };
351
352     for (const auto &LC : LibraryCalls) {
353       setLibcallName(LC.Op, LC.Name);
354       setLibcallCallingConv(LC.Op, LC.CC);
355       if (LC.Cond != ISD::SETCC_INVALID)
356         setCmpLibcallCC(LC.Op, LC.Cond);
357     }
358
359     // EABI dependent RTLIB
360     if (TM.Options.EABIVersion == EABI::EABI4 ||
361         TM.Options.EABIVersion == EABI::EABI5) {
362       static const struct {
363         const RTLIB::Libcall Op;
364         const char *const Name;
365         const CallingConv::ID CC;
366         const ISD::CondCode Cond;
367       } MemOpsLibraryCalls[] = {
368         // Memory operations
369         // RTABI chapter 4.3.4
370         { RTLIB::MEMCPY,  "__aeabi_memcpy",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
371         { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
372         { RTLIB::MEMSET,  "__aeabi_memset",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
373       };
374
375       for (const auto &LC : MemOpsLibraryCalls) {
376         setLibcallName(LC.Op, LC.Name);
377         setLibcallCallingConv(LC.Op, LC.CC);
378         if (LC.Cond != ISD::SETCC_INVALID)
379           setCmpLibcallCC(LC.Op, LC.Cond);
380       }
381     }
382   }
383
384   if (Subtarget->isTargetWindows()) {
385     static const struct {
386       const RTLIB::Libcall Op;
387       const char * const Name;
388       const CallingConv::ID CC;
389     } LibraryCalls[] = {
390       { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
391       { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
392       { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
393       { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
394       { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
395       { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
396       { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
397       { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
398     };
399
400     for (const auto &LC : LibraryCalls) {
401       setLibcallName(LC.Op, LC.Name);
402       setLibcallCallingConv(LC.Op, LC.CC);
403     }
404   }
405
406   // Use divmod compiler-rt calls for iOS 5.0 and later.
407   if (Subtarget->isTargetWatchOS() ||
408       (Subtarget->isTargetIOS() &&
409        !Subtarget->getTargetTriple().isOSVersionLT(5, 0))) {
410     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
411     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
412   }
413
414   // The half <-> float conversion functions are always soft-float, but are
415   // needed for some targets which use a hard-float calling convention by
416   // default.
417   if (Subtarget->isAAPCS_ABI()) {
418     setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
419     setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
420     setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
421   } else {
422     setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
423     setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
424     setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
425   }
426
427   // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have
428   // a __gnu_ prefix (which is the default).
429   if (Subtarget->isTargetAEABI()) {
430     setLibcallName(RTLIB::FPROUND_F32_F16, "__aeabi_f2h");
431     setLibcallName(RTLIB::FPROUND_F64_F16, "__aeabi_d2h");
432     setLibcallName(RTLIB::FPEXT_F16_F32,   "__aeabi_h2f");
433   }
434
435   if (Subtarget->isThumb1Only())
436     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
437   else
438     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
439   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
440       !Subtarget->isThumb1Only()) {
441     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
442     addRegisterClass(MVT::f64, &ARM::DPRRegClass);
443   }
444
445   for (MVT VT : MVT::vector_valuetypes()) {
446     for (MVT InnerVT : MVT::vector_valuetypes()) {
447       setTruncStoreAction(VT, InnerVT, Expand);
448       setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
449       setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
450       setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
451     }
452
453     setOperationAction(ISD::MULHS, VT, Expand);
454     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
455     setOperationAction(ISD::MULHU, VT, Expand);
456     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
457
458     setOperationAction(ISD::BSWAP, VT, Expand);
459   }
460
461   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
462   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
463
464   setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
465   setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
466
467   if (Subtarget->hasNEON()) {
468     addDRTypeForNEON(MVT::v2f32);
469     addDRTypeForNEON(MVT::v8i8);
470     addDRTypeForNEON(MVT::v4i16);
471     addDRTypeForNEON(MVT::v2i32);
472     addDRTypeForNEON(MVT::v1i64);
473
474     addQRTypeForNEON(MVT::v4f32);
475     addQRTypeForNEON(MVT::v2f64);
476     addQRTypeForNEON(MVT::v16i8);
477     addQRTypeForNEON(MVT::v8i16);
478     addQRTypeForNEON(MVT::v4i32);
479     addQRTypeForNEON(MVT::v2i64);
480
481     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
482     // neither Neon nor VFP support any arithmetic operations on it.
483     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
484     // supported for v4f32.
485     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
486     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
487     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
488     // FIXME: Code duplication: FDIV and FREM are expanded always, see
489     // ARMTargetLowering::addTypeForNEON method for details.
490     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
491     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
492     // FIXME: Create unittest.
493     // In another words, find a way when "copysign" appears in DAG with vector
494     // operands.
495     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
496     // FIXME: Code duplication: SETCC has custom operation action, see
497     // ARMTargetLowering::addTypeForNEON method for details.
498     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
499     // FIXME: Create unittest for FNEG and for FABS.
500     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
501     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
502     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
503     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
504     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
505     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
506     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
507     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
508     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
509     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
510     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
511     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
512     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
513     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
514     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
515     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
516     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
517     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
518     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
519
520     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
521     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
522     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
523     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
524     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
525     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
526     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
527     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
528     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
529     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
530     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
531     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
532     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
533     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
534     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
535
536     // Mark v2f32 intrinsics.
537     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
538     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
539     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
540     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
541     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
542     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
543     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
544     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
545     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
546     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
547     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
548     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
549     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
550     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
551     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
552
553     // Neon does not support some operations on v1i64 and v2i64 types.
554     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
555     // Custom handling for some quad-vector types to detect VMULL.
556     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
557     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
558     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
559     // Custom handling for some vector types to avoid expensive expansions
560     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
561     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
562     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
563     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
564     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
565     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
566     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
567     // a destination type that is wider than the source, and nor does
568     // it have a FP_TO_[SU]INT instruction with a narrower destination than
569     // source.
570     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
571     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
572     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
573     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
574
575     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
576     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
577
578     // NEON does not have single instruction CTPOP for vectors with element
579     // types wider than 8-bits.  However, custom lowering can leverage the
580     // v8i8/v16i8 vcnt instruction.
581     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
582     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
583     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
584     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
585
586     // NEON does not have single instruction CTTZ for vectors.
587     setOperationAction(ISD::CTTZ, MVT::v8i8, Custom);
588     setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
589     setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
590     setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
591
592     setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
593     setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
594     setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
595     setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
596
597     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom);
598     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom);
599     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom);
600     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom);
601
602     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
603     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
604     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
605     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
606
607     // NEON only has FMA instructions as of VFP4.
608     if (!Subtarget->hasVFP4()) {
609       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
610       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
611     }
612
613     setTargetDAGCombine(ISD::INTRINSIC_VOID);
614     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
615     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
616     setTargetDAGCombine(ISD::SHL);
617     setTargetDAGCombine(ISD::SRL);
618     setTargetDAGCombine(ISD::SRA);
619     setTargetDAGCombine(ISD::SIGN_EXTEND);
620     setTargetDAGCombine(ISD::ZERO_EXTEND);
621     setTargetDAGCombine(ISD::ANY_EXTEND);
622     setTargetDAGCombine(ISD::BUILD_VECTOR);
623     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
624     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
625     setTargetDAGCombine(ISD::STORE);
626     setTargetDAGCombine(ISD::FP_TO_SINT);
627     setTargetDAGCombine(ISD::FP_TO_UINT);
628     setTargetDAGCombine(ISD::FDIV);
629     setTargetDAGCombine(ISD::LOAD);
630
631     // It is legal to extload from v4i8 to v4i16 or v4i32.
632     for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
633                    MVT::v2i32}) {
634       for (MVT VT : MVT::integer_vector_valuetypes()) {
635         setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
636         setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
637         setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
638       }
639     }
640   }
641
642   // ARM and Thumb2 support UMLAL/SMLAL.
643   if (!Subtarget->isThumb1Only())
644     setTargetDAGCombine(ISD::ADDC);
645
646   if (Subtarget->isFPOnlySP()) {
647     // When targeting a floating-point unit with only single-precision
648     // operations, f64 is legal for the few double-precision instructions which
649     // are present However, no double-precision operations other than moves,
650     // loads and stores are provided by the hardware.
651     setOperationAction(ISD::FADD,       MVT::f64, Expand);
652     setOperationAction(ISD::FSUB,       MVT::f64, Expand);
653     setOperationAction(ISD::FMUL,       MVT::f64, Expand);
654     setOperationAction(ISD::FMA,        MVT::f64, Expand);
655     setOperationAction(ISD::FDIV,       MVT::f64, Expand);
656     setOperationAction(ISD::FREM,       MVT::f64, Expand);
657     setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
658     setOperationAction(ISD::FGETSIGN,   MVT::f64, Expand);
659     setOperationAction(ISD::FNEG,       MVT::f64, Expand);
660     setOperationAction(ISD::FABS,       MVT::f64, Expand);
661     setOperationAction(ISD::FSQRT,      MVT::f64, Expand);
662     setOperationAction(ISD::FSIN,       MVT::f64, Expand);
663     setOperationAction(ISD::FCOS,       MVT::f64, Expand);
664     setOperationAction(ISD::FPOWI,      MVT::f64, Expand);
665     setOperationAction(ISD::FPOW,       MVT::f64, Expand);
666     setOperationAction(ISD::FLOG,       MVT::f64, Expand);
667     setOperationAction(ISD::FLOG2,      MVT::f64, Expand);
668     setOperationAction(ISD::FLOG10,     MVT::f64, Expand);
669     setOperationAction(ISD::FEXP,       MVT::f64, Expand);
670     setOperationAction(ISD::FEXP2,      MVT::f64, Expand);
671     setOperationAction(ISD::FCEIL,      MVT::f64, Expand);
672     setOperationAction(ISD::FTRUNC,     MVT::f64, Expand);
673     setOperationAction(ISD::FRINT,      MVT::f64, Expand);
674     setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
675     setOperationAction(ISD::FFLOOR,     MVT::f64, Expand);
676     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
677     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
678     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
679     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
680     setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
681     setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
682     setOperationAction(ISD::FP_ROUND,   MVT::f32, Custom);
683     setOperationAction(ISD::FP_EXTEND,  MVT::f64, Custom);
684   }
685
686   computeRegisterProperties(Subtarget->getRegisterInfo());
687
688   // ARM does not have floating-point extending loads.
689   for (MVT VT : MVT::fp_valuetypes()) {
690     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
691     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
692   }
693
694   // ... or truncating stores
695   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
696   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
697   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
698
699   // ARM does not have i1 sign extending load.
700   for (MVT VT : MVT::integer_valuetypes())
701     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
702
703   // ARM supports all 4 flavors of integer indexed load / store.
704   if (!Subtarget->isThumb1Only()) {
705     for (unsigned im = (unsigned)ISD::PRE_INC;
706          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
707       setIndexedLoadAction(im,  MVT::i1,  Legal);
708       setIndexedLoadAction(im,  MVT::i8,  Legal);
709       setIndexedLoadAction(im,  MVT::i16, Legal);
710       setIndexedLoadAction(im,  MVT::i32, Legal);
711       setIndexedStoreAction(im, MVT::i1,  Legal);
712       setIndexedStoreAction(im, MVT::i8,  Legal);
713       setIndexedStoreAction(im, MVT::i16, Legal);
714       setIndexedStoreAction(im, MVT::i32, Legal);
715     }
716   }
717
718   setOperationAction(ISD::SADDO, MVT::i32, Custom);
719   setOperationAction(ISD::UADDO, MVT::i32, Custom);
720   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
721   setOperationAction(ISD::USUBO, MVT::i32, Custom);
722
723   // i64 operation support.
724   setOperationAction(ISD::MUL,     MVT::i64, Expand);
725   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
726   if (Subtarget->isThumb1Only()) {
727     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
728     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
729   }
730   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
731       || (Subtarget->isThumb2() && !Subtarget->hasDSP()))
732     setOperationAction(ISD::MULHS, MVT::i32, Expand);
733
734   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
735   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
736   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
737   setOperationAction(ISD::SRL,       MVT::i64, Custom);
738   setOperationAction(ISD::SRA,       MVT::i64, Custom);
739
740   if (!Subtarget->isThumb1Only()) {
741     // FIXME: We should do this for Thumb1 as well.
742     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
743     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
744     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
745     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
746   }
747
748   if (!Subtarget->isThumb1Only())
749     setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
750
751   // ARM does not have ROTL.
752   setOperationAction(ISD::ROTL, MVT::i32, Expand);
753   for (MVT VT : MVT::vector_valuetypes()) {
754     setOperationAction(ISD::ROTL, VT, Expand);
755     setOperationAction(ISD::ROTR, VT, Expand);
756   }
757   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
758   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
759   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
760     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
761
762   // These just redirect to CTTZ and CTLZ on ARM.
763   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
764   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
765
766   // @llvm.readcyclecounter requires the Performance Monitors extension.
767   // Default to the 0 expansion on unsupported platforms.
768   // FIXME: Technically there are older ARM CPUs that have
769   // implementation-specific ways of obtaining this information.
770   if (Subtarget->hasPerfMon())
771     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
772
773   // Only ARMv6 has BSWAP.
774   if (!Subtarget->hasV6Ops())
775     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
776
777   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
778       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
779     // These are expanded into libcalls if the cpu doesn't have HW divider.
780     setOperationAction(ISD::SDIV,  MVT::i32, LibCall);
781     setOperationAction(ISD::UDIV,  MVT::i32, LibCall);
782   }
783
784   if (Subtarget->isTargetWindows() && !Subtarget->hasDivide()) {
785     setOperationAction(ISD::SDIV, MVT::i32, Custom);
786     setOperationAction(ISD::UDIV, MVT::i32, Custom);
787
788     setOperationAction(ISD::SDIV, MVT::i64, Custom);
789     setOperationAction(ISD::UDIV, MVT::i64, Custom);
790   }
791
792   setOperationAction(ISD::SREM,  MVT::i32, Expand);
793   setOperationAction(ISD::UREM,  MVT::i32, Expand);
794   // Register based DivRem for AEABI (RTABI 4.2)
795   if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid()) {
796     setOperationAction(ISD::SREM, MVT::i64, Custom);
797     setOperationAction(ISD::UREM, MVT::i64, Custom);
798
799     setLibcallName(RTLIB::SDIVREM_I8,  "__aeabi_idivmod");
800     setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
801     setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
802     setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
803     setLibcallName(RTLIB::UDIVREM_I8,  "__aeabi_uidivmod");
804     setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
805     setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
806     setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
807
808     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
809     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
810     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
811     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
812     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
813     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
814     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
815     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
816
817     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
818     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
819   } else {
820     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
821     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
822   }
823
824   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
825   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
826   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
827   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
828
829   setOperationAction(ISD::TRAP, MVT::Other, Legal);
830
831   // Use the default implementation.
832   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
833   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
834   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
835   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
836   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
837   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
838
839   if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
840     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
841   else
842     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
843
844   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
845   // the default expansion. If we are targeting a single threaded system,
846   // then set them all for expand so we can lower them later into their
847   // non-atomic form.
848   if (TM.Options.ThreadModel == ThreadModel::Single)
849     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
850   else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
851     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
852     // to ldrex/strex loops already.
853     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
854
855     // On v8, we have particularly efficient implementations of atomic fences
856     // if they can be combined with nearby atomic loads and stores.
857     if (!Subtarget->hasV8Ops()) {
858       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
859       setInsertFencesForAtomic(true);
860     }
861   } else {
862     // If there's anything we can use as a barrier, go through custom lowering
863     // for ATOMIC_FENCE.
864     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
865                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
866
867     // Set them all for expansion, which will force libcalls.
868     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
869     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
870     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
871     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
872     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
873     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
874     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
875     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
876     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
877     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
878     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
879     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
880     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
881     // Unordered/Monotonic case.
882     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
883     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
884   }
885
886   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
887
888   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
889   if (!Subtarget->hasV6Ops()) {
890     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
891     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
892   }
893   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
894
895   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
896       !Subtarget->isThumb1Only()) {
897     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
898     // iff target supports vfp2.
899     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
900     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
901   }
902
903   // We want to custom lower some of our intrinsics.
904   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
905   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
906   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
907   setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
908   if (Subtarget->useSjLjEH())
909     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
910
911   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
912   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
913   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
914   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
915   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
916   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
917   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
918   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
919   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
920
921   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
922   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
923   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
924   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
925   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
926
927   // We don't support sin/cos/fmod/copysign/pow
928   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
929   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
930   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
931   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
932   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
933   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
934   setOperationAction(ISD::FREM,      MVT::f64, Expand);
935   setOperationAction(ISD::FREM,      MVT::f32, Expand);
936   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
937       !Subtarget->isThumb1Only()) {
938     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
939     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
940   }
941   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
942   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
943
944   if (!Subtarget->hasVFP4()) {
945     setOperationAction(ISD::FMA, MVT::f64, Expand);
946     setOperationAction(ISD::FMA, MVT::f32, Expand);
947   }
948
949   // Various VFP goodness
950   if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
951     // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
952     if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
953       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
954       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
955     }
956
957     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
958     if (!Subtarget->hasFP16()) {
959       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
960       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
961     }
962   }
963
964   // Combine sin / cos into one node or libcall if possible.
965   if (Subtarget->hasSinCos()) {
966     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
967     setLibcallName(RTLIB::SINCOS_F64, "sincos");
968     if (Subtarget->isTargetWatchOS()) {
969       setLibcallCallingConv(RTLIB::SINCOS_F32, CallingConv::ARM_AAPCS_VFP);
970       setLibcallCallingConv(RTLIB::SINCOS_F64, CallingConv::ARM_AAPCS_VFP);
971     }
972     if (Subtarget->isTargetIOS() || Subtarget->isTargetWatchOS()) {
973       // For iOS, we don't want to the normal expansion of a libcall to
974       // sincos. We want to issue a libcall to __sincos_stret.
975       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
976       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
977     }
978   }
979
980   // FP-ARMv8 implements a lot of rounding-like FP operations.
981   if (Subtarget->hasFPARMv8()) {
982     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
983     setOperationAction(ISD::FCEIL, MVT::f32, Legal);
984     setOperationAction(ISD::FROUND, MVT::f32, Legal);
985     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
986     setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
987     setOperationAction(ISD::FRINT, MVT::f32, Legal);
988     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
989     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
990     setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
991     setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
992     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
993     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
994
995     if (!Subtarget->isFPOnlySP()) {
996       setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
997       setOperationAction(ISD::FCEIL, MVT::f64, Legal);
998       setOperationAction(ISD::FROUND, MVT::f64, Legal);
999       setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1000       setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1001       setOperationAction(ISD::FRINT, MVT::f64, Legal);
1002       setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
1003       setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
1004     }
1005   }
1006
1007   if (Subtarget->hasNEON()) {
1008     // vmin and vmax aren't available in a scalar form, so we use
1009     // a NEON instruction with an undef lane instead.
1010     setOperationAction(ISD::FMINNAN, MVT::f32, Legal);
1011     setOperationAction(ISD::FMAXNAN, MVT::f32, Legal);
1012     setOperationAction(ISD::FMINNAN, MVT::v2f32, Legal);
1013     setOperationAction(ISD::FMAXNAN, MVT::v2f32, Legal);
1014     setOperationAction(ISD::FMINNAN, MVT::v4f32, Legal);
1015     setOperationAction(ISD::FMAXNAN, MVT::v4f32, Legal);
1016   }
1017
1018   // We have target-specific dag combine patterns for the following nodes:
1019   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
1020   setTargetDAGCombine(ISD::ADD);
1021   setTargetDAGCombine(ISD::SUB);
1022   setTargetDAGCombine(ISD::MUL);
1023   setTargetDAGCombine(ISD::AND);
1024   setTargetDAGCombine(ISD::OR);
1025   setTargetDAGCombine(ISD::XOR);
1026
1027   if (Subtarget->hasV6Ops())
1028     setTargetDAGCombine(ISD::SRL);
1029
1030   setStackPointerRegisterToSaveRestore(ARM::SP);
1031
1032   if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
1033       !Subtarget->hasVFP2())
1034     setSchedulingPreference(Sched::RegPressure);
1035   else
1036     setSchedulingPreference(Sched::Hybrid);
1037
1038   //// temporary - rewrite interface to use type
1039   MaxStoresPerMemset = 8;
1040   MaxStoresPerMemsetOptSize = 4;
1041   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
1042   MaxStoresPerMemcpyOptSize = 2;
1043   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
1044   MaxStoresPerMemmoveOptSize = 2;
1045
1046   // On ARM arguments smaller than 4 bytes are extended, so all arguments
1047   // are at least 4 bytes aligned.
1048   setMinStackArgumentAlignment(4);
1049
1050   // Prefer likely predicted branches to selects on out-of-order cores.
1051   PredictableSelectIsExpensive = Subtarget->isLikeA9();
1052
1053   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
1054 }
1055
1056 bool ARMTargetLowering::useSoftFloat() const {
1057   return Subtarget->useSoftFloat();
1058 }
1059
1060 // FIXME: It might make sense to define the representative register class as the
1061 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1062 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1063 // SPR's representative would be DPR_VFP2. This should work well if register
1064 // pressure tracking were modified such that a register use would increment the
1065 // pressure of the register class's representative and all of it's super
1066 // classes' representatives transitively. We have not implemented this because
1067 // of the difficulty prior to coalescing of modeling operand register classes
1068 // due to the common occurrence of cross class copies and subregister insertions
1069 // and extractions.
1070 std::pair<const TargetRegisterClass *, uint8_t>
1071 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1072                                            MVT VT) const {
1073   const TargetRegisterClass *RRC = nullptr;
1074   uint8_t Cost = 1;
1075   switch (VT.SimpleTy) {
1076   default:
1077     return TargetLowering::findRepresentativeClass(TRI, VT);
1078   // Use DPR as representative register class for all floating point
1079   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1080   // the cost is 1 for both f32 and f64.
1081   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1082   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1083     RRC = &ARM::DPRRegClass;
1084     // When NEON is used for SP, only half of the register file is available
1085     // because operations that define both SP and DP results will be constrained
1086     // to the VFP2 class (D0-D15). We currently model this constraint prior to
1087     // coalescing by double-counting the SP regs. See the FIXME above.
1088     if (Subtarget->useNEONForSinglePrecisionFP())
1089       Cost = 2;
1090     break;
1091   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1092   case MVT::v4f32: case MVT::v2f64:
1093     RRC = &ARM::DPRRegClass;
1094     Cost = 2;
1095     break;
1096   case MVT::v4i64:
1097     RRC = &ARM::DPRRegClass;
1098     Cost = 4;
1099     break;
1100   case MVT::v8i64:
1101     RRC = &ARM::DPRRegClass;
1102     Cost = 8;
1103     break;
1104   }
1105   return std::make_pair(RRC, Cost);
1106 }
1107
1108 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1109   switch ((ARMISD::NodeType)Opcode) {
1110   case ARMISD::FIRST_NUMBER:  break;
1111   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1112   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1113   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1114   case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1115   case ARMISD::CALL:          return "ARMISD::CALL";
1116   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1117   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1118   case ARMISD::tCALL:         return "ARMISD::tCALL";
1119   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1120   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1121   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1122   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1123   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1124   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1125   case ARMISD::CMP:           return "ARMISD::CMP";
1126   case ARMISD::CMN:           return "ARMISD::CMN";
1127   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1128   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1129   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1130   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1131   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1132
1133   case ARMISD::CMOV:          return "ARMISD::CMOV";
1134
1135   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1136   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1137   case ARMISD::RRX:           return "ARMISD::RRX";
1138
1139   case ARMISD::ADDC:          return "ARMISD::ADDC";
1140   case ARMISD::ADDE:          return "ARMISD::ADDE";
1141   case ARMISD::SUBC:          return "ARMISD::SUBC";
1142   case ARMISD::SUBE:          return "ARMISD::SUBE";
1143
1144   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1145   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1146
1147   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1148   case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1149   case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1150
1151   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1152
1153   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1154
1155   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1156
1157   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1158
1159   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1160
1161   case ARMISD::WIN__CHKSTK:   return "ARMISD:::WIN__CHKSTK";
1162   case ARMISD::WIN__DBZCHK:   return "ARMISD::WIN__DBZCHK";
1163
1164   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1165   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1166   case ARMISD::VCGE:          return "ARMISD::VCGE";
1167   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1168   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1169   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1170   case ARMISD::VCGT:          return "ARMISD::VCGT";
1171   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1172   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1173   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1174   case ARMISD::VTST:          return "ARMISD::VTST";
1175
1176   case ARMISD::VSHL:          return "ARMISD::VSHL";
1177   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1178   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1179   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1180   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1181   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1182   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1183   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1184   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1185   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1186   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1187   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1188   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1189   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1190   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1191   case ARMISD::VSLI:          return "ARMISD::VSLI";
1192   case ARMISD::VSRI:          return "ARMISD::VSRI";
1193   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1194   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1195   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1196   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1197   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1198   case ARMISD::VDUP:          return "ARMISD::VDUP";
1199   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1200   case ARMISD::VEXT:          return "ARMISD::VEXT";
1201   case ARMISD::VREV64:        return "ARMISD::VREV64";
1202   case ARMISD::VREV32:        return "ARMISD::VREV32";
1203   case ARMISD::VREV16:        return "ARMISD::VREV16";
1204   case ARMISD::VZIP:          return "ARMISD::VZIP";
1205   case ARMISD::VUZP:          return "ARMISD::VUZP";
1206   case ARMISD::VTRN:          return "ARMISD::VTRN";
1207   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1208   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1209   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1210   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1211   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1212   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1213   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1214   case ARMISD::BFI:           return "ARMISD::BFI";
1215   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1216   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1217   case ARMISD::VBSL:          return "ARMISD::VBSL";
1218   case ARMISD::MEMCPY:        return "ARMISD::MEMCPY";
1219   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1220   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1221   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1222   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1223   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1224   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1225   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1226   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1227   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1228   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1229   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1230   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1231   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1232   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1233   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1234   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1235   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1236   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1237   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1238   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1239   }
1240   return nullptr;
1241 }
1242
1243 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1244                                           EVT VT) const {
1245   if (!VT.isVector())
1246     return getPointerTy(DL);
1247   return VT.changeVectorElementTypeToInteger();
1248 }
1249
1250 /// getRegClassFor - Return the register class that should be used for the
1251 /// specified value type.
1252 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1253   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1254   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1255   // load / store 4 to 8 consecutive D registers.
1256   if (Subtarget->hasNEON()) {
1257     if (VT == MVT::v4i64)
1258       return &ARM::QQPRRegClass;
1259     if (VT == MVT::v8i64)
1260       return &ARM::QQQQPRRegClass;
1261   }
1262   return TargetLowering::getRegClassFor(VT);
1263 }
1264
1265 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1266 // source/dest is aligned and the copy size is large enough. We therefore want
1267 // to align such objects passed to memory intrinsics.
1268 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1269                                                unsigned &PrefAlign) const {
1270   if (!isa<MemIntrinsic>(CI))
1271     return false;
1272   MinSize = 8;
1273   // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1274   // cycle faster than 4-byte aligned LDM.
1275   PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1276   return true;
1277 }
1278
1279 // Create a fast isel object.
1280 FastISel *
1281 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1282                                   const TargetLibraryInfo *libInfo) const {
1283   return ARM::createFastISel(funcInfo, libInfo);
1284 }
1285
1286 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1287   unsigned NumVals = N->getNumValues();
1288   if (!NumVals)
1289     return Sched::RegPressure;
1290
1291   for (unsigned i = 0; i != NumVals; ++i) {
1292     EVT VT = N->getValueType(i);
1293     if (VT == MVT::Glue || VT == MVT::Other)
1294       continue;
1295     if (VT.isFloatingPoint() || VT.isVector())
1296       return Sched::ILP;
1297   }
1298
1299   if (!N->isMachineOpcode())
1300     return Sched::RegPressure;
1301
1302   // Load are scheduled for latency even if there instruction itinerary
1303   // is not available.
1304   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1305   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1306
1307   if (MCID.getNumDefs() == 0)
1308     return Sched::RegPressure;
1309   if (!Itins->isEmpty() &&
1310       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1311     return Sched::ILP;
1312
1313   return Sched::RegPressure;
1314 }
1315
1316 //===----------------------------------------------------------------------===//
1317 // Lowering Code
1318 //===----------------------------------------------------------------------===//
1319
1320 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1321 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1322   switch (CC) {
1323   default: llvm_unreachable("Unknown condition code!");
1324   case ISD::SETNE:  return ARMCC::NE;
1325   case ISD::SETEQ:  return ARMCC::EQ;
1326   case ISD::SETGT:  return ARMCC::GT;
1327   case ISD::SETGE:  return ARMCC::GE;
1328   case ISD::SETLT:  return ARMCC::LT;
1329   case ISD::SETLE:  return ARMCC::LE;
1330   case ISD::SETUGT: return ARMCC::HI;
1331   case ISD::SETUGE: return ARMCC::HS;
1332   case ISD::SETULT: return ARMCC::LO;
1333   case ISD::SETULE: return ARMCC::LS;
1334   }
1335 }
1336
1337 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1338 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1339                         ARMCC::CondCodes &CondCode2) {
1340   CondCode2 = ARMCC::AL;
1341   switch (CC) {
1342   default: llvm_unreachable("Unknown FP condition!");
1343   case ISD::SETEQ:
1344   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1345   case ISD::SETGT:
1346   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1347   case ISD::SETGE:
1348   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1349   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1350   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1351   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1352   case ISD::SETO:   CondCode = ARMCC::VC; break;
1353   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1354   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1355   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1356   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1357   case ISD::SETLT:
1358   case ISD::SETULT: CondCode = ARMCC::LT; break;
1359   case ISD::SETLE:
1360   case ISD::SETULE: CondCode = ARMCC::LE; break;
1361   case ISD::SETNE:
1362   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1363   }
1364 }
1365
1366 //===----------------------------------------------------------------------===//
1367 //                      Calling Convention Implementation
1368 //===----------------------------------------------------------------------===//
1369
1370 #include "ARMGenCallingConv.inc"
1371
1372 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1373 /// account presence of floating point hardware and calling convention
1374 /// limitations, such as support for variadic functions.
1375 CallingConv::ID
1376 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1377                                            bool isVarArg) const {
1378   switch (CC) {
1379   default:
1380     llvm_unreachable("Unsupported calling convention");
1381   case CallingConv::ARM_AAPCS:
1382   case CallingConv::ARM_APCS:
1383   case CallingConv::GHC:
1384     return CC;
1385   case CallingConv::ARM_AAPCS_VFP:
1386     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1387   case CallingConv::C:
1388     if (!Subtarget->isAAPCS_ABI())
1389       return CallingConv::ARM_APCS;
1390     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1391              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1392              !isVarArg)
1393       return CallingConv::ARM_AAPCS_VFP;
1394     else
1395       return CallingConv::ARM_AAPCS;
1396   case CallingConv::Fast:
1397     if (!Subtarget->isAAPCS_ABI()) {
1398       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1399         return CallingConv::Fast;
1400       return CallingConv::ARM_APCS;
1401     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1402       return CallingConv::ARM_AAPCS_VFP;
1403     else
1404       return CallingConv::ARM_AAPCS;
1405   }
1406 }
1407
1408 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1409 /// CallingConvention.
1410 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1411                                                  bool Return,
1412                                                  bool isVarArg) const {
1413   switch (getEffectiveCallingConv(CC, isVarArg)) {
1414   default:
1415     llvm_unreachable("Unsupported calling convention");
1416   case CallingConv::ARM_APCS:
1417     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1418   case CallingConv::ARM_AAPCS:
1419     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1420   case CallingConv::ARM_AAPCS_VFP:
1421     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1422   case CallingConv::Fast:
1423     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1424   case CallingConv::GHC:
1425     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1426   }
1427 }
1428
1429 /// LowerCallResult - Lower the result values of a call into the
1430 /// appropriate copies out of appropriate physical registers.
1431 SDValue
1432 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1433                                    CallingConv::ID CallConv, bool isVarArg,
1434                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1435                                    SDLoc dl, SelectionDAG &DAG,
1436                                    SmallVectorImpl<SDValue> &InVals,
1437                                    bool isThisReturn, SDValue ThisVal) const {
1438
1439   // Assign locations to each value returned by this call.
1440   SmallVector<CCValAssign, 16> RVLocs;
1441   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1442                     *DAG.getContext(), Call);
1443   CCInfo.AnalyzeCallResult(Ins,
1444                            CCAssignFnForNode(CallConv, /* Return*/ true,
1445                                              isVarArg));
1446
1447   // Copy all of the result registers out of their specified physreg.
1448   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1449     CCValAssign VA = RVLocs[i];
1450
1451     // Pass 'this' value directly from the argument to return value, to avoid
1452     // reg unit interference
1453     if (i == 0 && isThisReturn) {
1454       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1455              "unexpected return calling convention register assignment");
1456       InVals.push_back(ThisVal);
1457       continue;
1458     }
1459
1460     SDValue Val;
1461     if (VA.needsCustom()) {
1462       // Handle f64 or half of a v2f64.
1463       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1464                                       InFlag);
1465       Chain = Lo.getValue(1);
1466       InFlag = Lo.getValue(2);
1467       VA = RVLocs[++i]; // skip ahead to next loc
1468       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1469                                       InFlag);
1470       Chain = Hi.getValue(1);
1471       InFlag = Hi.getValue(2);
1472       if (!Subtarget->isLittle())
1473         std::swap (Lo, Hi);
1474       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1475
1476       if (VA.getLocVT() == MVT::v2f64) {
1477         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1478         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1479                           DAG.getConstant(0, dl, MVT::i32));
1480
1481         VA = RVLocs[++i]; // skip ahead to next loc
1482         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1483         Chain = Lo.getValue(1);
1484         InFlag = Lo.getValue(2);
1485         VA = RVLocs[++i]; // skip ahead to next loc
1486         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1487         Chain = Hi.getValue(1);
1488         InFlag = Hi.getValue(2);
1489         if (!Subtarget->isLittle())
1490           std::swap (Lo, Hi);
1491         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1492         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1493                           DAG.getConstant(1, dl, MVT::i32));
1494       }
1495     } else {
1496       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1497                                InFlag);
1498       Chain = Val.getValue(1);
1499       InFlag = Val.getValue(2);
1500     }
1501
1502     switch (VA.getLocInfo()) {
1503     default: llvm_unreachable("Unknown loc info!");
1504     case CCValAssign::Full: break;
1505     case CCValAssign::BCvt:
1506       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1507       break;
1508     }
1509
1510     InVals.push_back(Val);
1511   }
1512
1513   return Chain;
1514 }
1515
1516 /// LowerMemOpCallTo - Store the argument to the stack.
1517 SDValue
1518 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1519                                     SDValue StackPtr, SDValue Arg,
1520                                     SDLoc dl, SelectionDAG &DAG,
1521                                     const CCValAssign &VA,
1522                                     ISD::ArgFlagsTy Flags) const {
1523   unsigned LocMemOffset = VA.getLocMemOffset();
1524   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1525   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1526                        StackPtr, PtrOff);
1527   return DAG.getStore(
1528       Chain, dl, Arg, PtrOff,
1529       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
1530       false, false, 0);
1531 }
1532
1533 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1534                                          SDValue Chain, SDValue &Arg,
1535                                          RegsToPassVector &RegsToPass,
1536                                          CCValAssign &VA, CCValAssign &NextVA,
1537                                          SDValue &StackPtr,
1538                                          SmallVectorImpl<SDValue> &MemOpChains,
1539                                          ISD::ArgFlagsTy Flags) const {
1540
1541   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1542                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1543   unsigned id = Subtarget->isLittle() ? 0 : 1;
1544   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1545
1546   if (NextVA.isRegLoc())
1547     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1548   else {
1549     assert(NextVA.isMemLoc());
1550     if (!StackPtr.getNode())
1551       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
1552                                     getPointerTy(DAG.getDataLayout()));
1553
1554     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1555                                            dl, DAG, NextVA,
1556                                            Flags));
1557   }
1558 }
1559
1560 /// LowerCall - Lowering a call into a callseq_start <-
1561 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1562 /// nodes.
1563 SDValue
1564 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1565                              SmallVectorImpl<SDValue> &InVals) const {
1566   SelectionDAG &DAG                     = CLI.DAG;
1567   SDLoc &dl                             = CLI.DL;
1568   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1569   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1570   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1571   SDValue Chain                         = CLI.Chain;
1572   SDValue Callee                        = CLI.Callee;
1573   bool &isTailCall                      = CLI.IsTailCall;
1574   CallingConv::ID CallConv              = CLI.CallConv;
1575   bool doesNotRet                       = CLI.DoesNotReturn;
1576   bool isVarArg                         = CLI.IsVarArg;
1577
1578   MachineFunction &MF = DAG.getMachineFunction();
1579   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1580   bool isThisReturn   = false;
1581   bool isSibCall      = false;
1582   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
1583
1584   // Disable tail calls if they're not supported.
1585   if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
1586     isTailCall = false;
1587
1588   if (isTailCall) {
1589     // Check if it's really possible to do a tail call.
1590     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1591                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1592                                                    Outs, OutVals, Ins, DAG);
1593     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1594       report_fatal_error("failed to perform tail call elimination on a call "
1595                          "site marked musttail");
1596     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1597     // detected sibcalls.
1598     if (isTailCall) {
1599       ++NumTailCalls;
1600       isSibCall = true;
1601     }
1602   }
1603
1604   // Analyze operands of the call, assigning locations to each operand.
1605   SmallVector<CCValAssign, 16> ArgLocs;
1606   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1607                     *DAG.getContext(), Call);
1608   CCInfo.AnalyzeCallOperands(Outs,
1609                              CCAssignFnForNode(CallConv, /* Return*/ false,
1610                                                isVarArg));
1611
1612   // Get a count of how many bytes are to be pushed on the stack.
1613   unsigned NumBytes = CCInfo.getNextStackOffset();
1614
1615   // For tail calls, memory operands are available in our caller's stack.
1616   if (isSibCall)
1617     NumBytes = 0;
1618
1619   // Adjust the stack pointer for the new arguments...
1620   // These operations are automatically eliminated by the prolog/epilog pass
1621   if (!isSibCall)
1622     Chain = DAG.getCALLSEQ_START(Chain,
1623                                  DAG.getIntPtrConstant(NumBytes, dl, true), dl);
1624
1625   SDValue StackPtr =
1626       DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
1627
1628   RegsToPassVector RegsToPass;
1629   SmallVector<SDValue, 8> MemOpChains;
1630
1631   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1632   // of tail call optimization, arguments are handled later.
1633   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1634        i != e;
1635        ++i, ++realArgIdx) {
1636     CCValAssign &VA = ArgLocs[i];
1637     SDValue Arg = OutVals[realArgIdx];
1638     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1639     bool isByVal = Flags.isByVal();
1640
1641     // Promote the value if needed.
1642     switch (VA.getLocInfo()) {
1643     default: llvm_unreachable("Unknown loc info!");
1644     case CCValAssign::Full: break;
1645     case CCValAssign::SExt:
1646       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1647       break;
1648     case CCValAssign::ZExt:
1649       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1650       break;
1651     case CCValAssign::AExt:
1652       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1653       break;
1654     case CCValAssign::BCvt:
1655       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1656       break;
1657     }
1658
1659     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1660     if (VA.needsCustom()) {
1661       if (VA.getLocVT() == MVT::v2f64) {
1662         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1663                                   DAG.getConstant(0, dl, MVT::i32));
1664         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1665                                   DAG.getConstant(1, dl, MVT::i32));
1666
1667         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1668                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1669
1670         VA = ArgLocs[++i]; // skip ahead to next loc
1671         if (VA.isRegLoc()) {
1672           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1673                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1674         } else {
1675           assert(VA.isMemLoc());
1676
1677           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1678                                                  dl, DAG, VA, Flags));
1679         }
1680       } else {
1681         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1682                          StackPtr, MemOpChains, Flags);
1683       }
1684     } else if (VA.isRegLoc()) {
1685       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1686         assert(VA.getLocVT() == MVT::i32 &&
1687                "unexpected calling convention register assignment");
1688         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1689                "unexpected use of 'returned'");
1690         isThisReturn = true;
1691       }
1692       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1693     } else if (isByVal) {
1694       assert(VA.isMemLoc());
1695       unsigned offset = 0;
1696
1697       // True if this byval aggregate will be split between registers
1698       // and memory.
1699       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1700       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1701
1702       if (CurByValIdx < ByValArgsCount) {
1703
1704         unsigned RegBegin, RegEnd;
1705         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1706
1707         EVT PtrVT =
1708             DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
1709         unsigned int i, j;
1710         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1711           SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1712           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1713           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1714                                      MachinePointerInfo(),
1715                                      false, false, false,
1716                                      DAG.InferPtrAlignment(AddArg));
1717           MemOpChains.push_back(Load.getValue(1));
1718           RegsToPass.push_back(std::make_pair(j, Load));
1719         }
1720
1721         // If parameter size outsides register area, "offset" value
1722         // helps us to calculate stack slot for remained part properly.
1723         offset = RegEnd - RegBegin;
1724
1725         CCInfo.nextInRegsParam();
1726       }
1727
1728       if (Flags.getByValSize() > 4*offset) {
1729         auto PtrVT = getPointerTy(DAG.getDataLayout());
1730         unsigned LocMemOffset = VA.getLocMemOffset();
1731         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1732         SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
1733         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1734         SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
1735         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1736                                            MVT::i32);
1737         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1738                                             MVT::i32);
1739
1740         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1741         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1742         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1743                                           Ops));
1744       }
1745     } else if (!isSibCall) {
1746       assert(VA.isMemLoc());
1747
1748       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1749                                              dl, DAG, VA, Flags));
1750     }
1751   }
1752
1753   if (!MemOpChains.empty())
1754     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1755
1756   // Build a sequence of copy-to-reg nodes chained together with token chain
1757   // and flag operands which copy the outgoing args into the appropriate regs.
1758   SDValue InFlag;
1759   // Tail call byval lowering might overwrite argument registers so in case of
1760   // tail call optimization the copies to registers are lowered later.
1761   if (!isTailCall)
1762     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1763       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1764                                RegsToPass[i].second, InFlag);
1765       InFlag = Chain.getValue(1);
1766     }
1767
1768   // For tail calls lower the arguments to the 'real' stack slot.
1769   if (isTailCall) {
1770     // Force all the incoming stack arguments to be loaded from the stack
1771     // before any new outgoing arguments are stored to the stack, because the
1772     // outgoing stack slots may alias the incoming argument stack slots, and
1773     // the alias isn't otherwise explicit. This is slightly more conservative
1774     // than necessary, because it means that each store effectively depends
1775     // on every argument instead of just those arguments it would clobber.
1776
1777     // Do not flag preceding copytoreg stuff together with the following stuff.
1778     InFlag = SDValue();
1779     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1780       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1781                                RegsToPass[i].second, InFlag);
1782       InFlag = Chain.getValue(1);
1783     }
1784     InFlag = SDValue();
1785   }
1786
1787   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1788   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1789   // node so that legalize doesn't hack it.
1790   bool isDirect = false;
1791   bool isARMFunc = false;
1792   bool isLocalARMFunc = false;
1793   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1794   auto PtrVt = getPointerTy(DAG.getDataLayout());
1795
1796   if (Subtarget->genLongCalls()) {
1797     assert((Subtarget->isTargetWindows() ||
1798             getTargetMachine().getRelocationModel() == Reloc::Static) &&
1799            "long-calls with non-static relocation model!");
1800     // Handle a global address or an external symbol. If it's not one of
1801     // those, the target's already in a register, so we don't need to do
1802     // anything extra.
1803     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1804       const GlobalValue *GV = G->getGlobal();
1805       // Create a constant pool entry for the callee address
1806       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1807       ARMConstantPoolValue *CPV =
1808         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1809
1810       // Get the address of the callee into a register
1811       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1812       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1813       Callee = DAG.getLoad(
1814           PtrVt, dl, DAG.getEntryNode(), CPAddr,
1815           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1816           false, false, 0);
1817     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1818       const char *Sym = S->getSymbol();
1819
1820       // Create a constant pool entry for the callee address
1821       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1822       ARMConstantPoolValue *CPV =
1823         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1824                                       ARMPCLabelIndex, 0);
1825       // Get the address of the callee into a register
1826       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1827       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1828       Callee = DAG.getLoad(
1829           PtrVt, dl, DAG.getEntryNode(), CPAddr,
1830           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1831           false, false, 0);
1832     }
1833   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1834     const GlobalValue *GV = G->getGlobal();
1835     isDirect = true;
1836     bool isDef = GV->isStrongDefinitionForLinker();
1837     bool isStub = (!isDef && Subtarget->isTargetMachO()) &&
1838                    getTargetMachine().getRelocationModel() != Reloc::Static;
1839     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1840     // ARM call to a local ARM function is predicable.
1841     isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
1842     // tBX takes a register source operand.
1843     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1844       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1845       Callee = DAG.getNode(
1846           ARMISD::WrapperPIC, dl, PtrVt,
1847           DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
1848       Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), Callee,
1849                            MachinePointerInfo::getGOT(DAG.getMachineFunction()),
1850                            false, false, true, 0);
1851     } else if (Subtarget->isTargetCOFF()) {
1852       assert(Subtarget->isTargetWindows() &&
1853              "Windows is the only supported COFF target");
1854       unsigned TargetFlags = GV->hasDLLImportStorageClass()
1855                                  ? ARMII::MO_DLLIMPORT
1856                                  : ARMII::MO_NO_FLAG;
1857       Callee =
1858           DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0, TargetFlags);
1859       if (GV->hasDLLImportStorageClass())
1860         Callee =
1861             DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
1862                         DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
1863                         MachinePointerInfo::getGOT(DAG.getMachineFunction()),
1864                         false, false, false, 0);
1865     } else {
1866       // On ELF targets for PIC code, direct calls should go through the PLT
1867       unsigned OpFlags = 0;
1868       if (Subtarget->isTargetELF() &&
1869           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1870         OpFlags = ARMII::MO_PLT;
1871       Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, OpFlags);
1872     }
1873   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1874     isDirect = true;
1875     bool isStub = Subtarget->isTargetMachO() &&
1876                   getTargetMachine().getRelocationModel() != Reloc::Static;
1877     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1878     // tBX takes a register source operand.
1879     const char *Sym = S->getSymbol();
1880     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1881       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1882       ARMConstantPoolValue *CPV =
1883         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1884                                       ARMPCLabelIndex, 4);
1885       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1886       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1887       Callee = DAG.getLoad(
1888           PtrVt, dl, DAG.getEntryNode(), CPAddr,
1889           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1890           false, false, 0);
1891       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
1892       Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
1893     } else {
1894       unsigned OpFlags = 0;
1895       // On ELF targets for PIC code, direct calls should go through the PLT
1896       if (Subtarget->isTargetELF() &&
1897                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1898         OpFlags = ARMII::MO_PLT;
1899       Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, OpFlags);
1900     }
1901   }
1902
1903   // FIXME: handle tail calls differently.
1904   unsigned CallOpc;
1905   if (Subtarget->isThumb()) {
1906     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1907       CallOpc = ARMISD::CALL_NOLINK;
1908     else
1909       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1910   } else {
1911     if (!isDirect && !Subtarget->hasV5TOps())
1912       CallOpc = ARMISD::CALL_NOLINK;
1913     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1914              // Emit regular call when code size is the priority
1915              !MF.getFunction()->optForMinSize())
1916       // "mov lr, pc; b _foo" to avoid confusing the RSP
1917       CallOpc = ARMISD::CALL_NOLINK;
1918     else
1919       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1920   }
1921
1922   std::vector<SDValue> Ops;
1923   Ops.push_back(Chain);
1924   Ops.push_back(Callee);
1925
1926   // Add argument registers to the end of the list so that they are known live
1927   // into the call.
1928   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1929     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1930                                   RegsToPass[i].second.getValueType()));
1931
1932   // Add a register mask operand representing the call-preserved registers.
1933   if (!isTailCall) {
1934     const uint32_t *Mask;
1935     const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
1936     if (isThisReturn) {
1937       // For 'this' returns, use the R0-preserving mask if applicable
1938       Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
1939       if (!Mask) {
1940         // Set isThisReturn to false if the calling convention is not one that
1941         // allows 'returned' to be modeled in this way, so LowerCallResult does
1942         // not try to pass 'this' straight through
1943         isThisReturn = false;
1944         Mask = ARI->getCallPreservedMask(MF, CallConv);
1945       }
1946     } else
1947       Mask = ARI->getCallPreservedMask(MF, CallConv);
1948
1949     assert(Mask && "Missing call preserved mask for calling convention");
1950     Ops.push_back(DAG.getRegisterMask(Mask));
1951   }
1952
1953   if (InFlag.getNode())
1954     Ops.push_back(InFlag);
1955
1956   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1957   if (isTailCall) {
1958     MF.getFrameInfo()->setHasTailCall();
1959     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1960   }
1961
1962   // Returns a chain and a flag for retval copy to use.
1963   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1964   InFlag = Chain.getValue(1);
1965
1966   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
1967                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
1968   if (!Ins.empty())
1969     InFlag = Chain.getValue(1);
1970
1971   // Handle result values, copying them out of physregs into vregs that we
1972   // return.
1973   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1974                          InVals, isThisReturn,
1975                          isThisReturn ? OutVals[0] : SDValue());
1976 }
1977
1978 /// HandleByVal - Every parameter *after* a byval parameter is passed
1979 /// on the stack.  Remember the next parameter register to allocate,
1980 /// and then confiscate the rest of the parameter registers to insure
1981 /// this.
1982 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
1983                                     unsigned Align) const {
1984   assert((State->getCallOrPrologue() == Prologue ||
1985           State->getCallOrPrologue() == Call) &&
1986          "unhandled ParmContext");
1987
1988   // Byval (as with any stack) slots are always at least 4 byte aligned.
1989   Align = std::max(Align, 4U);
1990
1991   unsigned Reg = State->AllocateReg(GPRArgRegs);
1992   if (!Reg)
1993     return;
1994
1995   unsigned AlignInRegs = Align / 4;
1996   unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
1997   for (unsigned i = 0; i < Waste; ++i)
1998     Reg = State->AllocateReg(GPRArgRegs);
1999
2000   if (!Reg)
2001     return;
2002
2003   unsigned Excess = 4 * (ARM::R4 - Reg);
2004
2005   // Special case when NSAA != SP and parameter size greater than size of
2006   // all remained GPR regs. In that case we can't split parameter, we must
2007   // send it to stack. We also must set NCRN to R4, so waste all
2008   // remained registers.
2009   const unsigned NSAAOffset = State->getNextStackOffset();
2010   if (NSAAOffset != 0 && Size > Excess) {
2011     while (State->AllocateReg(GPRArgRegs))
2012       ;
2013     return;
2014   }
2015
2016   // First register for byval parameter is the first register that wasn't
2017   // allocated before this method call, so it would be "reg".
2018   // If parameter is small enough to be saved in range [reg, r4), then
2019   // the end (first after last) register would be reg + param-size-in-regs,
2020   // else parameter would be splitted between registers and stack,
2021   // end register would be r4 in this case.
2022   unsigned ByValRegBegin = Reg;
2023   unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
2024   State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
2025   // Note, first register is allocated in the beginning of function already,
2026   // allocate remained amount of registers we need.
2027   for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
2028     State->AllocateReg(GPRArgRegs);
2029   // A byval parameter that is split between registers and memory needs its
2030   // size truncated here.
2031   // In the case where the entire structure fits in registers, we set the
2032   // size in memory to zero.
2033   Size = std::max<int>(Size - Excess, 0);
2034 }
2035
2036 /// MatchingStackOffset - Return true if the given stack call argument is
2037 /// already available in the same position (relatively) of the caller's
2038 /// incoming argument stack.
2039 static
2040 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2041                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2042                          const TargetInstrInfo *TII) {
2043   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2044   int FI = INT_MAX;
2045   if (Arg.getOpcode() == ISD::CopyFromReg) {
2046     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2047     if (!TargetRegisterInfo::isVirtualRegister(VR))
2048       return false;
2049     MachineInstr *Def = MRI->getVRegDef(VR);
2050     if (!Def)
2051       return false;
2052     if (!Flags.isByVal()) {
2053       if (!TII->isLoadFromStackSlot(Def, FI))
2054         return false;
2055     } else {
2056       return false;
2057     }
2058   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2059     if (Flags.isByVal())
2060       // ByVal argument is passed in as a pointer but it's now being
2061       // dereferenced. e.g.
2062       // define @foo(%struct.X* %A) {
2063       //   tail call @bar(%struct.X* byval %A)
2064       // }
2065       return false;
2066     SDValue Ptr = Ld->getBasePtr();
2067     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2068     if (!FINode)
2069       return false;
2070     FI = FINode->getIndex();
2071   } else
2072     return false;
2073
2074   assert(FI != INT_MAX);
2075   if (!MFI->isFixedObjectIndex(FI))
2076     return false;
2077   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2078 }
2079
2080 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2081 /// for tail call optimization. Targets which want to do tail call
2082 /// optimization should implement this function.
2083 bool
2084 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2085                                                      CallingConv::ID CalleeCC,
2086                                                      bool isVarArg,
2087                                                      bool isCalleeStructRet,
2088                                                      bool isCallerStructRet,
2089                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2090                                     const SmallVectorImpl<SDValue> &OutVals,
2091                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2092                                                      SelectionDAG& DAG) const {
2093   const Function *CallerF = DAG.getMachineFunction().getFunction();
2094   CallingConv::ID CallerCC = CallerF->getCallingConv();
2095   bool CCMatch = CallerCC == CalleeCC;
2096
2097   assert(Subtarget->supportsTailCall());
2098
2099   // Look for obvious safe cases to perform tail call optimization that do not
2100   // require ABI changes. This is what gcc calls sibcall.
2101
2102   // Do not sibcall optimize vararg calls unless the call site is not passing
2103   // any arguments.
2104   if (isVarArg && !Outs.empty())
2105     return false;
2106
2107   // Exception-handling functions need a special set of instructions to indicate
2108   // a return to the hardware. Tail-calling another function would probably
2109   // break this.
2110   if (CallerF->hasFnAttribute("interrupt"))
2111     return false;
2112
2113   // Also avoid sibcall optimization if either caller or callee uses struct
2114   // return semantics.
2115   if (isCalleeStructRet || isCallerStructRet)
2116     return false;
2117
2118   // Externally-defined functions with weak linkage should not be
2119   // tail-called on ARM when the OS does not support dynamic
2120   // pre-emption of symbols, as the AAELF spec requires normal calls
2121   // to undefined weak functions to be replaced with a NOP or jump to the
2122   // next instruction. The behaviour of branch instructions in this
2123   // situation (as used for tail calls) is implementation-defined, so we
2124   // cannot rely on the linker replacing the tail call with a return.
2125   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2126     const GlobalValue *GV = G->getGlobal();
2127     const Triple &TT = getTargetMachine().getTargetTriple();
2128     if (GV->hasExternalWeakLinkage() &&
2129         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2130       return false;
2131   }
2132
2133   // If the calling conventions do not match, then we'd better make sure the
2134   // results are returned in the same way as what the caller expects.
2135   if (!CCMatch) {
2136     SmallVector<CCValAssign, 16> RVLocs1;
2137     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2138                        *DAG.getContext(), Call);
2139     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2140
2141     SmallVector<CCValAssign, 16> RVLocs2;
2142     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2143                        *DAG.getContext(), Call);
2144     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2145
2146     if (RVLocs1.size() != RVLocs2.size())
2147       return false;
2148     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2149       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2150         return false;
2151       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2152         return false;
2153       if (RVLocs1[i].isRegLoc()) {
2154         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2155           return false;
2156       } else {
2157         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2158           return false;
2159       }
2160     }
2161   }
2162
2163   // If Caller's vararg or byval argument has been split between registers and
2164   // stack, do not perform tail call, since part of the argument is in caller's
2165   // local frame.
2166   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2167                                       getInfo<ARMFunctionInfo>();
2168   if (AFI_Caller->getArgRegsSaveSize())
2169     return false;
2170
2171   // If the callee takes no arguments then go on to check the results of the
2172   // call.
2173   if (!Outs.empty()) {
2174     // Check if stack adjustment is needed. For now, do not do this if any
2175     // argument is passed on the stack.
2176     SmallVector<CCValAssign, 16> ArgLocs;
2177     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2178                       *DAG.getContext(), Call);
2179     CCInfo.AnalyzeCallOperands(Outs,
2180                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2181     if (CCInfo.getNextStackOffset()) {
2182       MachineFunction &MF = DAG.getMachineFunction();
2183
2184       // Check if the arguments are already laid out in the right way as
2185       // the caller's fixed stack objects.
2186       MachineFrameInfo *MFI = MF.getFrameInfo();
2187       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2188       const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2189       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2190            i != e;
2191            ++i, ++realArgIdx) {
2192         CCValAssign &VA = ArgLocs[i];
2193         EVT RegVT = VA.getLocVT();
2194         SDValue Arg = OutVals[realArgIdx];
2195         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2196         if (VA.getLocInfo() == CCValAssign::Indirect)
2197           return false;
2198         if (VA.needsCustom()) {
2199           // f64 and vector types are split into multiple registers or
2200           // register/stack-slot combinations.  The types will not match
2201           // the registers; give up on memory f64 refs until we figure
2202           // out what to do about this.
2203           if (!VA.isRegLoc())
2204             return false;
2205           if (!ArgLocs[++i].isRegLoc())
2206             return false;
2207           if (RegVT == MVT::v2f64) {
2208             if (!ArgLocs[++i].isRegLoc())
2209               return false;
2210             if (!ArgLocs[++i].isRegLoc())
2211               return false;
2212           }
2213         } else if (!VA.isRegLoc()) {
2214           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2215                                    MFI, MRI, TII))
2216             return false;
2217         }
2218       }
2219     }
2220   }
2221
2222   return true;
2223 }
2224
2225 bool
2226 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2227                                   MachineFunction &MF, bool isVarArg,
2228                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2229                                   LLVMContext &Context) const {
2230   SmallVector<CCValAssign, 16> RVLocs;
2231   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2232   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2233                                                     isVarArg));
2234 }
2235
2236 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2237                                     SDLoc DL, SelectionDAG &DAG) {
2238   const MachineFunction &MF = DAG.getMachineFunction();
2239   const Function *F = MF.getFunction();
2240
2241   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2242
2243   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2244   // version of the "preferred return address". These offsets affect the return
2245   // instruction if this is a return from PL1 without hypervisor extensions.
2246   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2247   //    SWI:     0      "subs pc, lr, #0"
2248   //    ABORT:   +4     "subs pc, lr, #4"
2249   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2250   // UNDEF varies depending on where the exception came from ARM or Thumb
2251   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2252
2253   int64_t LROffset;
2254   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2255       IntKind == "ABORT")
2256     LROffset = 4;
2257   else if (IntKind == "SWI" || IntKind == "UNDEF")
2258     LROffset = 0;
2259   else
2260     report_fatal_error("Unsupported interrupt attribute. If present, value "
2261                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2262
2263   RetOps.insert(RetOps.begin() + 1,
2264                 DAG.getConstant(LROffset, DL, MVT::i32, false));
2265
2266   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2267 }
2268
2269 SDValue
2270 ARMTargetLowering::LowerReturn(SDValue Chain,
2271                                CallingConv::ID CallConv, bool isVarArg,
2272                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2273                                const SmallVectorImpl<SDValue> &OutVals,
2274                                SDLoc dl, SelectionDAG &DAG) const {
2275
2276   // CCValAssign - represent the assignment of the return value to a location.
2277   SmallVector<CCValAssign, 16> RVLocs;
2278
2279   // CCState - Info about the registers and stack slots.
2280   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2281                     *DAG.getContext(), Call);
2282
2283   // Analyze outgoing return values.
2284   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2285                                                isVarArg));
2286
2287   SDValue Flag;
2288   SmallVector<SDValue, 4> RetOps;
2289   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2290   bool isLittleEndian = Subtarget->isLittle();
2291
2292   MachineFunction &MF = DAG.getMachineFunction();
2293   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2294   AFI->setReturnRegsCount(RVLocs.size());
2295
2296   // Copy the result values into the output registers.
2297   for (unsigned i = 0, realRVLocIdx = 0;
2298        i != RVLocs.size();
2299        ++i, ++realRVLocIdx) {
2300     CCValAssign &VA = RVLocs[i];
2301     assert(VA.isRegLoc() && "Can only return in registers!");
2302
2303     SDValue Arg = OutVals[realRVLocIdx];
2304
2305     switch (VA.getLocInfo()) {
2306     default: llvm_unreachable("Unknown loc info!");
2307     case CCValAssign::Full: break;
2308     case CCValAssign::BCvt:
2309       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2310       break;
2311     }
2312
2313     if (VA.needsCustom()) {
2314       if (VA.getLocVT() == MVT::v2f64) {
2315         // Extract the first half and return it in two registers.
2316         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2317                                    DAG.getConstant(0, dl, MVT::i32));
2318         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2319                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2320
2321         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2322                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2323                                  Flag);
2324         Flag = Chain.getValue(1);
2325         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2326         VA = RVLocs[++i]; // skip ahead to next loc
2327         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2328                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2329                                  Flag);
2330         Flag = Chain.getValue(1);
2331         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2332         VA = RVLocs[++i]; // skip ahead to next loc
2333
2334         // Extract the 2nd half and fall through to handle it as an f64 value.
2335         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2336                           DAG.getConstant(1, dl, MVT::i32));
2337       }
2338       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2339       // available.
2340       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2341                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2342       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2343                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2344                                Flag);
2345       Flag = Chain.getValue(1);
2346       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2347       VA = RVLocs[++i]; // skip ahead to next loc
2348       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2349                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2350                                Flag);
2351     } else
2352       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2353
2354     // Guarantee that all emitted copies are
2355     // stuck together, avoiding something bad.
2356     Flag = Chain.getValue(1);
2357     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2358   }
2359
2360   // Update chain and glue.
2361   RetOps[0] = Chain;
2362   if (Flag.getNode())
2363     RetOps.push_back(Flag);
2364
2365   // CPUs which aren't M-class use a special sequence to return from
2366   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2367   // though we use "subs pc, lr, #N").
2368   //
2369   // M-class CPUs actually use a normal return sequence with a special
2370   // (hardware-provided) value in LR, so the normal code path works.
2371   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2372       !Subtarget->isMClass()) {
2373     if (Subtarget->isThumb1Only())
2374       report_fatal_error("interrupt attribute is not supported in Thumb1");
2375     return LowerInterruptReturn(RetOps, dl, DAG);
2376   }
2377
2378   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2379 }
2380
2381 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2382   if (N->getNumValues() != 1)
2383     return false;
2384   if (!N->hasNUsesOfValue(1, 0))
2385     return false;
2386
2387   SDValue TCChain = Chain;
2388   SDNode *Copy = *N->use_begin();
2389   if (Copy->getOpcode() == ISD::CopyToReg) {
2390     // If the copy has a glue operand, we conservatively assume it isn't safe to
2391     // perform a tail call.
2392     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2393       return false;
2394     TCChain = Copy->getOperand(0);
2395   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2396     SDNode *VMov = Copy;
2397     // f64 returned in a pair of GPRs.
2398     SmallPtrSet<SDNode*, 2> Copies;
2399     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2400          UI != UE; ++UI) {
2401       if (UI->getOpcode() != ISD::CopyToReg)
2402         return false;
2403       Copies.insert(*UI);
2404     }
2405     if (Copies.size() > 2)
2406       return false;
2407
2408     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2409          UI != UE; ++UI) {
2410       SDValue UseChain = UI->getOperand(0);
2411       if (Copies.count(UseChain.getNode()))
2412         // Second CopyToReg
2413         Copy = *UI;
2414       else {
2415         // We are at the top of this chain.
2416         // If the copy has a glue operand, we conservatively assume it
2417         // isn't safe to perform a tail call.
2418         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2419           return false;
2420         // First CopyToReg
2421         TCChain = UseChain;
2422       }
2423     }
2424   } else if (Copy->getOpcode() == ISD::BITCAST) {
2425     // f32 returned in a single GPR.
2426     if (!Copy->hasOneUse())
2427       return false;
2428     Copy = *Copy->use_begin();
2429     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2430       return false;
2431     // If the copy has a glue operand, we conservatively assume it isn't safe to
2432     // perform a tail call.
2433     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2434       return false;
2435     TCChain = Copy->getOperand(0);
2436   } else {
2437     return false;
2438   }
2439
2440   bool HasRet = false;
2441   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2442        UI != UE; ++UI) {
2443     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2444         UI->getOpcode() != ARMISD::INTRET_FLAG)
2445       return false;
2446     HasRet = true;
2447   }
2448
2449   if (!HasRet)
2450     return false;
2451
2452   Chain = TCChain;
2453   return true;
2454 }
2455
2456 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2457   if (!Subtarget->supportsTailCall())
2458     return false;
2459
2460   auto Attr =
2461       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2462   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2463     return false;
2464
2465   return true;
2466 }
2467
2468 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2469 // and pass the lower and high parts through.
2470 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2471   SDLoc DL(Op);
2472   SDValue WriteValue = Op->getOperand(2);
2473
2474   // This function is only supposed to be called for i64 type argument.
2475   assert(WriteValue.getValueType() == MVT::i64
2476           && "LowerWRITE_REGISTER called for non-i64 type argument.");
2477
2478   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2479                            DAG.getConstant(0, DL, MVT::i32));
2480   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2481                            DAG.getConstant(1, DL, MVT::i32));
2482   SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2483   return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2484 }
2485
2486 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2487 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2488 // one of the above mentioned nodes. It has to be wrapped because otherwise
2489 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2490 // be used to form addressing mode. These wrapped nodes will be selected
2491 // into MOVi.
2492 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2493   EVT PtrVT = Op.getValueType();
2494   // FIXME there is no actual debug info here
2495   SDLoc dl(Op);
2496   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2497   SDValue Res;
2498   if (CP->isMachineConstantPoolEntry())
2499     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2500                                     CP->getAlignment());
2501   else
2502     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2503                                     CP->getAlignment());
2504   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2505 }
2506
2507 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2508   return MachineJumpTableInfo::EK_Inline;
2509 }
2510
2511 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2512                                              SelectionDAG &DAG) const {
2513   MachineFunction &MF = DAG.getMachineFunction();
2514   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2515   unsigned ARMPCLabelIndex = 0;
2516   SDLoc DL(Op);
2517   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2518   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2519   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2520   SDValue CPAddr;
2521   if (RelocM == Reloc::Static) {
2522     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2523   } else {
2524     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2525     ARMPCLabelIndex = AFI->createPICLabelUId();
2526     ARMConstantPoolValue *CPV =
2527       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2528                                       ARMCP::CPBlockAddress, PCAdj);
2529     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2530   }
2531   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2532   SDValue Result =
2533       DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2534                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2535                   false, false, false, 0);
2536   if (RelocM == Reloc::Static)
2537     return Result;
2538   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2539   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2540 }
2541
2542 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2543 SDValue
2544 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2545                                                  SelectionDAG &DAG) const {
2546   SDLoc dl(GA);
2547   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2548   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2549   MachineFunction &MF = DAG.getMachineFunction();
2550   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2551   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2552   ARMConstantPoolValue *CPV =
2553     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2554                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2555   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2556   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2557   Argument =
2558       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2559                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2560                   false, false, false, 0);
2561   SDValue Chain = Argument.getValue(1);
2562
2563   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2564   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2565
2566   // call __tls_get_addr.
2567   ArgListTy Args;
2568   ArgListEntry Entry;
2569   Entry.Node = Argument;
2570   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2571   Args.push_back(Entry);
2572
2573   // FIXME: is there useful debug info available here?
2574   TargetLowering::CallLoweringInfo CLI(DAG);
2575   CLI.setDebugLoc(dl).setChain(Chain)
2576     .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2577                DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2578                0);
2579
2580   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2581   return CallResult.first;
2582 }
2583
2584 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2585 // "local exec" model.
2586 SDValue
2587 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2588                                         SelectionDAG &DAG,
2589                                         TLSModel::Model model) const {
2590   const GlobalValue *GV = GA->getGlobal();
2591   SDLoc dl(GA);
2592   SDValue Offset;
2593   SDValue Chain = DAG.getEntryNode();
2594   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2595   // Get the Thread Pointer
2596   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2597
2598   if (model == TLSModel::InitialExec) {
2599     MachineFunction &MF = DAG.getMachineFunction();
2600     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2601     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2602     // Initial exec model.
2603     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2604     ARMConstantPoolValue *CPV =
2605       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2606                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2607                                       true);
2608     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2609     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2610     Offset = DAG.getLoad(
2611         PtrVT, dl, Chain, Offset,
2612         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2613         false, false, 0);
2614     Chain = Offset.getValue(1);
2615
2616     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2617     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2618
2619     Offset = DAG.getLoad(
2620         PtrVT, dl, Chain, Offset,
2621         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2622         false, false, 0);
2623   } else {
2624     // local exec model
2625     assert(model == TLSModel::LocalExec);
2626     ARMConstantPoolValue *CPV =
2627       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2628     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2629     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2630     Offset = DAG.getLoad(
2631         PtrVT, dl, Chain, Offset,
2632         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2633         false, false, 0);
2634   }
2635
2636   // The address of the thread local variable is the add of the thread
2637   // pointer with the offset of the variable.
2638   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2639 }
2640
2641 SDValue
2642 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2643   // TODO: implement the "local dynamic" model
2644   assert(Subtarget->isTargetELF() &&
2645          "TLS not implemented for non-ELF targets");
2646   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2647   if (DAG.getTarget().Options.EmulatedTLS)
2648     return LowerToTLSEmulatedModel(GA, DAG);
2649
2650   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2651
2652   switch (model) {
2653     case TLSModel::GeneralDynamic:
2654     case TLSModel::LocalDynamic:
2655       return LowerToTLSGeneralDynamicModel(GA, DAG);
2656     case TLSModel::InitialExec:
2657     case TLSModel::LocalExec:
2658       return LowerToTLSExecModels(GA, DAG, model);
2659   }
2660   llvm_unreachable("bogus TLS model");
2661 }
2662
2663 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2664                                                  SelectionDAG &DAG) const {
2665   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2666   SDLoc dl(Op);
2667   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2668   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2669     bool UseGOT_PREL =
2670         !(GV->hasHiddenVisibility() || GV->hasLocalLinkage());
2671
2672     MachineFunction &MF = DAG.getMachineFunction();
2673     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2674     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2675     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2676     SDLoc dl(Op);
2677     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2678     ARMConstantPoolValue *CPV = ARMConstantPoolConstant::Create(
2679         GV, ARMPCLabelIndex, ARMCP::CPValue, PCAdj,
2680         UseGOT_PREL ? ARMCP::GOT_PREL : ARMCP::no_modifier,
2681         /*AddCurrentAddress=*/UseGOT_PREL);
2682     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2683     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2684     SDValue Result = DAG.getLoad(
2685         PtrVT, dl, DAG.getEntryNode(), CPAddr,
2686         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2687         false, false, 0);
2688     SDValue Chain = Result.getValue(1);
2689     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2690     Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2691     if (UseGOT_PREL)
2692       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2693                            MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2694                            false, false, false, 0);
2695     return Result;
2696   }
2697
2698   // If we have T2 ops, we can materialize the address directly via movt/movw
2699   // pair. This is always cheaper.
2700   if (Subtarget->useMovt(DAG.getMachineFunction())) {
2701     ++NumMovwMovt;
2702     // FIXME: Once remat is capable of dealing with instructions with register
2703     // operands, expand this into two nodes.
2704     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2705                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2706   } else {
2707     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2708     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2709     return DAG.getLoad(
2710         PtrVT, dl, DAG.getEntryNode(), CPAddr,
2711         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2712         false, false, 0);
2713   }
2714 }
2715
2716 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2717                                                     SelectionDAG &DAG) const {
2718   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2719   SDLoc dl(Op);
2720   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2721   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2722
2723   if (Subtarget->useMovt(DAG.getMachineFunction()))
2724     ++NumMovwMovt;
2725
2726   // FIXME: Once remat is capable of dealing with instructions with register
2727   // operands, expand this into multiple nodes
2728   unsigned Wrapper =
2729       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2730
2731   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2732   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2733
2734   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2735     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2736                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2737                          false, false, false, 0);
2738   return Result;
2739 }
2740
2741 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2742                                                      SelectionDAG &DAG) const {
2743   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2744   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2745          "Windows on ARM expects to use movw/movt");
2746
2747   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2748   const ARMII::TOF TargetFlags =
2749     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2750   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2751   SDValue Result;
2752   SDLoc DL(Op);
2753
2754   ++NumMovwMovt;
2755
2756   // FIXME: Once remat is capable of dealing with instructions with register
2757   // operands, expand this into two nodes.
2758   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2759                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2760                                                   TargetFlags));
2761   if (GV->hasDLLImportStorageClass())
2762     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2763                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2764                          false, false, false, 0);
2765   return Result;
2766 }
2767
2768 SDValue
2769 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2770   SDLoc dl(Op);
2771   SDValue Val = DAG.getConstant(0, dl, MVT::i32);
2772   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2773                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2774                      Op.getOperand(1), Val);
2775 }
2776
2777 SDValue
2778 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2779   SDLoc dl(Op);
2780   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2781                      Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
2782 }
2783
2784 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
2785                                                       SelectionDAG &DAG) const {
2786   SDLoc dl(Op);
2787   return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
2788                      Op.getOperand(0));
2789 }
2790
2791 SDValue
2792 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2793                                           const ARMSubtarget *Subtarget) const {
2794   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2795   SDLoc dl(Op);
2796   switch (IntNo) {
2797   default: return SDValue();    // Don't custom lower most intrinsics.
2798   case Intrinsic::arm_rbit: {
2799     assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2800            "RBIT intrinsic must have i32 type!");
2801     return DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, Op.getOperand(1));
2802   }
2803   case Intrinsic::arm_thread_pointer: {
2804     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2805     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2806   }
2807   case Intrinsic::eh_sjlj_lsda: {
2808     MachineFunction &MF = DAG.getMachineFunction();
2809     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2810     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2811     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2812     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2813     SDValue CPAddr;
2814     unsigned PCAdj = (RelocM != Reloc::PIC_)
2815       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2816     ARMConstantPoolValue *CPV =
2817       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2818                                       ARMCP::CPLSDA, PCAdj);
2819     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2820     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2821     SDValue Result = DAG.getLoad(
2822         PtrVT, dl, DAG.getEntryNode(), CPAddr,
2823         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2824         false, false, 0);
2825
2826     if (RelocM == Reloc::PIC_) {
2827       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2828       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2829     }
2830     return Result;
2831   }
2832   case Intrinsic::arm_neon_vmulls:
2833   case Intrinsic::arm_neon_vmullu: {
2834     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2835       ? ARMISD::VMULLs : ARMISD::VMULLu;
2836     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2837                        Op.getOperand(1), Op.getOperand(2));
2838   }
2839   case Intrinsic::arm_neon_vminnm:
2840   case Intrinsic::arm_neon_vmaxnm: {
2841     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
2842       ? ISD::FMINNUM : ISD::FMAXNUM;
2843     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2844                        Op.getOperand(1), Op.getOperand(2));
2845   }
2846   case Intrinsic::arm_neon_vminu:
2847   case Intrinsic::arm_neon_vmaxu: {
2848     if (Op.getValueType().isFloatingPoint())
2849       return SDValue();
2850     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
2851       ? ISD::UMIN : ISD::UMAX;
2852     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2853                          Op.getOperand(1), Op.getOperand(2));
2854   }
2855   case Intrinsic::arm_neon_vmins:
2856   case Intrinsic::arm_neon_vmaxs: {
2857     // v{min,max}s is overloaded between signed integers and floats.
2858     if (!Op.getValueType().isFloatingPoint()) {
2859       unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
2860         ? ISD::SMIN : ISD::SMAX;
2861       return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2862                          Op.getOperand(1), Op.getOperand(2));
2863     }
2864     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
2865       ? ISD::FMINNAN : ISD::FMAXNAN;
2866     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2867                        Op.getOperand(1), Op.getOperand(2));
2868   }
2869   }
2870 }
2871
2872 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2873                                  const ARMSubtarget *Subtarget) {
2874   // FIXME: handle "fence singlethread" more efficiently.
2875   SDLoc dl(Op);
2876   if (!Subtarget->hasDataBarrier()) {
2877     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2878     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2879     // here.
2880     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2881            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2882     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2883                        DAG.getConstant(0, dl, MVT::i32));
2884   }
2885
2886   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2887   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2888   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
2889   if (Subtarget->isMClass()) {
2890     // Only a full system barrier exists in the M-class architectures.
2891     Domain = ARM_MB::SY;
2892   } else if (Subtarget->isSwift() && Ord == Release) {
2893     // Swift happens to implement ISHST barriers in a way that's compatible with
2894     // Release semantics but weaker than ISH so we'd be fools not to use
2895     // it. Beware: other processors probably don't!
2896     Domain = ARM_MB::ISHST;
2897   }
2898
2899   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2900                      DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
2901                      DAG.getConstant(Domain, dl, MVT::i32));
2902 }
2903
2904 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2905                              const ARMSubtarget *Subtarget) {
2906   // ARM pre v5TE and Thumb1 does not have preload instructions.
2907   if (!(Subtarget->isThumb2() ||
2908         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2909     // Just preserve the chain.
2910     return Op.getOperand(0);
2911
2912   SDLoc dl(Op);
2913   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2914   if (!isRead &&
2915       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2916     // ARMv7 with MP extension has PLDW.
2917     return Op.getOperand(0);
2918
2919   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2920   if (Subtarget->isThumb()) {
2921     // Invert the bits.
2922     isRead = ~isRead & 1;
2923     isData = ~isData & 1;
2924   }
2925
2926   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2927                      Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
2928                      DAG.getConstant(isData, dl, MVT::i32));
2929 }
2930
2931 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2932   MachineFunction &MF = DAG.getMachineFunction();
2933   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2934
2935   // vastart just stores the address of the VarArgsFrameIndex slot into the
2936   // memory location argument.
2937   SDLoc dl(Op);
2938   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2939   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2940   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2941   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2942                       MachinePointerInfo(SV), false, false, 0);
2943 }
2944
2945 SDValue
2946 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2947                                         SDValue &Root, SelectionDAG &DAG,
2948                                         SDLoc dl) const {
2949   MachineFunction &MF = DAG.getMachineFunction();
2950   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2951
2952   const TargetRegisterClass *RC;
2953   if (AFI->isThumb1OnlyFunction())
2954     RC = &ARM::tGPRRegClass;
2955   else
2956     RC = &ARM::GPRRegClass;
2957
2958   // Transform the arguments stored in physical registers into virtual ones.
2959   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2960   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2961
2962   SDValue ArgValue2;
2963   if (NextVA.isMemLoc()) {
2964     MachineFrameInfo *MFI = MF.getFrameInfo();
2965     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2966
2967     // Create load node to retrieve arguments from the stack.
2968     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2969     ArgValue2 = DAG.getLoad(
2970         MVT::i32, dl, Root, FIN,
2971         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
2972         false, false, 0);
2973   } else {
2974     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2975     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2976   }
2977   if (!Subtarget->isLittle())
2978     std::swap (ArgValue, ArgValue2);
2979   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2980 }
2981
2982 // The remaining GPRs hold either the beginning of variable-argument
2983 // data, or the beginning of an aggregate passed by value (usually
2984 // byval).  Either way, we allocate stack slots adjacent to the data
2985 // provided by our caller, and store the unallocated registers there.
2986 // If this is a variadic function, the va_list pointer will begin with
2987 // these values; otherwise, this reassembles a (byval) structure that
2988 // was split between registers and memory.
2989 // Return: The frame index registers were stored into.
2990 int
2991 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2992                                   SDLoc dl, SDValue &Chain,
2993                                   const Value *OrigArg,
2994                                   unsigned InRegsParamRecordIdx,
2995                                   int ArgOffset,
2996                                   unsigned ArgSize) const {
2997   // Currently, two use-cases possible:
2998   // Case #1. Non-var-args function, and we meet first byval parameter.
2999   //          Setup first unallocated register as first byval register;
3000   //          eat all remained registers
3001   //          (these two actions are performed by HandleByVal method).
3002   //          Then, here, we initialize stack frame with
3003   //          "store-reg" instructions.
3004   // Case #2. Var-args function, that doesn't contain byval parameters.
3005   //          The same: eat all remained unallocated registers,
3006   //          initialize stack frame.
3007
3008   MachineFunction &MF = DAG.getMachineFunction();
3009   MachineFrameInfo *MFI = MF.getFrameInfo();
3010   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3011   unsigned RBegin, REnd;
3012   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
3013     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
3014   } else {
3015     unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3016     RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
3017     REnd = ARM::R4;
3018   }
3019
3020   if (REnd != RBegin)
3021     ArgOffset = -4 * (ARM::R4 - RBegin);
3022
3023   auto PtrVT = getPointerTy(DAG.getDataLayout());
3024   int FrameIndex = MFI->CreateFixedObject(ArgSize, ArgOffset, false);
3025   SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
3026
3027   SmallVector<SDValue, 4> MemOps;
3028   const TargetRegisterClass *RC =
3029       AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
3030
3031   for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
3032     unsigned VReg = MF.addLiveIn(Reg, RC);
3033     SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3034     SDValue Store =
3035         DAG.getStore(Val.getValue(1), dl, Val, FIN,
3036                      MachinePointerInfo(OrigArg, 4 * i), false, false, 0);
3037     MemOps.push_back(Store);
3038     FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
3039   }
3040
3041   if (!MemOps.empty())
3042     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3043   return FrameIndex;
3044 }
3045
3046 // Setup stack frame, the va_list pointer will start from.
3047 void
3048 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
3049                                         SDLoc dl, SDValue &Chain,
3050                                         unsigned ArgOffset,
3051                                         unsigned TotalArgRegsSaveSize,
3052                                         bool ForceMutable) const {
3053   MachineFunction &MF = DAG.getMachineFunction();
3054   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3055
3056   // Try to store any remaining integer argument regs
3057   // to their spots on the stack so that they may be loaded by deferencing
3058   // the result of va_next.
3059   // If there is no regs to be stored, just point address after last
3060   // argument passed via stack.
3061   int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3062                                   CCInfo.getInRegsParamsCount(),
3063                                   CCInfo.getNextStackOffset(), 4);
3064   AFI->setVarArgsFrameIndex(FrameIndex);
3065 }
3066
3067 SDValue
3068 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
3069                                         CallingConv::ID CallConv, bool isVarArg,
3070                                         const SmallVectorImpl<ISD::InputArg>
3071                                           &Ins,
3072                                         SDLoc dl, SelectionDAG &DAG,
3073                                         SmallVectorImpl<SDValue> &InVals)
3074                                           const {
3075   MachineFunction &MF = DAG.getMachineFunction();
3076   MachineFrameInfo *MFI = MF.getFrameInfo();
3077
3078   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3079
3080   // Assign locations to all of the incoming arguments.
3081   SmallVector<CCValAssign, 16> ArgLocs;
3082   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3083                     *DAG.getContext(), Prologue);
3084   CCInfo.AnalyzeFormalArguments(Ins,
3085                                 CCAssignFnForNode(CallConv, /* Return*/ false,
3086                                                   isVarArg));
3087
3088   SmallVector<SDValue, 16> ArgValues;
3089   SDValue ArgValue;
3090   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3091   unsigned CurArgIdx = 0;
3092
3093   // Initially ArgRegsSaveSize is zero.
3094   // Then we increase this value each time we meet byval parameter.
3095   // We also increase this value in case of varargs function.
3096   AFI->setArgRegsSaveSize(0);
3097
3098   // Calculate the amount of stack space that we need to allocate to store
3099   // byval and variadic arguments that are passed in registers.
3100   // We need to know this before we allocate the first byval or variadic
3101   // argument, as they will be allocated a stack slot below the CFA (Canonical
3102   // Frame Address, the stack pointer at entry to the function).
3103   unsigned ArgRegBegin = ARM::R4;
3104   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3105     if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3106       break;
3107
3108     CCValAssign &VA = ArgLocs[i];
3109     unsigned Index = VA.getValNo();
3110     ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3111     if (!Flags.isByVal())
3112       continue;
3113
3114     assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3115     unsigned RBegin, REnd;
3116     CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3117     ArgRegBegin = std::min(ArgRegBegin, RBegin);
3118
3119     CCInfo.nextInRegsParam();
3120   }
3121   CCInfo.rewindByValRegsInfo();
3122
3123   int lastInsIndex = -1;
3124   if (isVarArg && MFI->hasVAStart()) {
3125     unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3126     if (RegIdx != array_lengthof(GPRArgRegs))
3127       ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3128   }
3129
3130   unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3131   AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3132   auto PtrVT = getPointerTy(DAG.getDataLayout());
3133
3134   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3135     CCValAssign &VA = ArgLocs[i];
3136     if (Ins[VA.getValNo()].isOrigArg()) {
3137       std::advance(CurOrigArg,
3138                    Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3139       CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3140     }
3141     // Arguments stored in registers.
3142     if (VA.isRegLoc()) {
3143       EVT RegVT = VA.getLocVT();
3144
3145       if (VA.needsCustom()) {
3146         // f64 and vector types are split up into multiple registers or
3147         // combinations of registers and stack slots.
3148         if (VA.getLocVT() == MVT::v2f64) {
3149           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3150                                                    Chain, DAG, dl);
3151           VA = ArgLocs[++i]; // skip ahead to next loc
3152           SDValue ArgValue2;
3153           if (VA.isMemLoc()) {
3154             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3155             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3156             ArgValue2 = DAG.getLoad(
3157                 MVT::f64, dl, Chain, FIN,
3158                 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3159                 false, false, false, 0);
3160           } else {
3161             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3162                                              Chain, DAG, dl);
3163           }
3164           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3165           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3166                                  ArgValue, ArgValue1,
3167                                  DAG.getIntPtrConstant(0, dl));
3168           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3169                                  ArgValue, ArgValue2,
3170                                  DAG.getIntPtrConstant(1, dl));
3171         } else
3172           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3173
3174       } else {
3175         const TargetRegisterClass *RC;
3176
3177         if (RegVT == MVT::f32)
3178           RC = &ARM::SPRRegClass;
3179         else if (RegVT == MVT::f64)
3180           RC = &ARM::DPRRegClass;
3181         else if (RegVT == MVT::v2f64)
3182           RC = &ARM::QPRRegClass;
3183         else if (RegVT == MVT::i32)
3184           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3185                                            : &ARM::GPRRegClass;
3186         else
3187           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3188
3189         // Transform the arguments in physical registers into virtual ones.
3190         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3191         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3192       }
3193
3194       // If this is an 8 or 16-bit value, it is really passed promoted
3195       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3196       // truncate to the right size.
3197       switch (VA.getLocInfo()) {
3198       default: llvm_unreachable("Unknown loc info!");
3199       case CCValAssign::Full: break;
3200       case CCValAssign::BCvt:
3201         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3202         break;
3203       case CCValAssign::SExt:
3204         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3205                                DAG.getValueType(VA.getValVT()));
3206         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3207         break;
3208       case CCValAssign::ZExt:
3209         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3210                                DAG.getValueType(VA.getValVT()));
3211         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3212         break;
3213       }
3214
3215       InVals.push_back(ArgValue);
3216
3217     } else { // VA.isRegLoc()
3218
3219       // sanity check
3220       assert(VA.isMemLoc());
3221       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3222
3223       int index = VA.getValNo();
3224
3225       // Some Ins[] entries become multiple ArgLoc[] entries.
3226       // Process them only once.
3227       if (index != lastInsIndex)
3228         {
3229           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3230           // FIXME: For now, all byval parameter objects are marked mutable.
3231           // This can be changed with more analysis.
3232           // In case of tail call optimization mark all arguments mutable.
3233           // Since they could be overwritten by lowering of arguments in case of
3234           // a tail call.
3235           if (Flags.isByVal()) {
3236             assert(Ins[index].isOrigArg() &&
3237                    "Byval arguments cannot be implicit");
3238             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3239
3240             int FrameIndex = StoreByValRegs(
3241                 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex,
3242                 VA.getLocMemOffset(), Flags.getByValSize());
3243             InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
3244             CCInfo.nextInRegsParam();
3245           } else {
3246             unsigned FIOffset = VA.getLocMemOffset();
3247             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3248                                             FIOffset, true);
3249
3250             // Create load nodes to retrieve arguments from the stack.
3251             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3252             InVals.push_back(DAG.getLoad(
3253                 VA.getValVT(), dl, Chain, FIN,
3254                 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3255                 false, false, false, 0));
3256           }
3257           lastInsIndex = index;
3258         }
3259     }
3260   }
3261
3262   // varargs
3263   if (isVarArg && MFI->hasVAStart())
3264     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3265                          CCInfo.getNextStackOffset(),
3266                          TotalArgRegsSaveSize);
3267
3268   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3269
3270   return Chain;
3271 }
3272
3273 /// isFloatingPointZero - Return true if this is +0.0.
3274 static bool isFloatingPointZero(SDValue Op) {
3275   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3276     return CFP->getValueAPF().isPosZero();
3277   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3278     // Maybe this has already been legalized into the constant pool?
3279     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3280       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3281       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3282         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3283           return CFP->getValueAPF().isPosZero();
3284     }
3285   } else if (Op->getOpcode() == ISD::BITCAST &&
3286              Op->getValueType(0) == MVT::f64) {
3287     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3288     // created by LowerConstantFP().
3289     SDValue BitcastOp = Op->getOperand(0);
3290     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM) {
3291       SDValue MoveOp = BitcastOp->getOperand(0);
3292       if (MoveOp->getOpcode() == ISD::TargetConstant &&
3293           cast<ConstantSDNode>(MoveOp)->getZExtValue() == 0) {
3294         return true;
3295       }
3296     }
3297   }
3298   return false;
3299 }
3300
3301 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3302 /// the given operands.
3303 SDValue
3304 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3305                              SDValue &ARMcc, SelectionDAG &DAG,
3306                              SDLoc dl) const {
3307   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3308     unsigned C = RHSC->getZExtValue();
3309     if (!isLegalICmpImmediate(C)) {
3310       // Constant does not fit, try adjusting it by one?
3311       switch (CC) {
3312       default: break;
3313       case ISD::SETLT:
3314       case ISD::SETGE:
3315         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3316           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3317           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3318         }
3319         break;
3320       case ISD::SETULT:
3321       case ISD::SETUGE:
3322         if (C != 0 && isLegalICmpImmediate(C-1)) {
3323           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3324           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3325         }
3326         break;
3327       case ISD::SETLE:
3328       case ISD::SETGT:
3329         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3330           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3331           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3332         }
3333         break;
3334       case ISD::SETULE:
3335       case ISD::SETUGT:
3336         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3337           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3338           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3339         }
3340         break;
3341       }
3342     }
3343   }
3344
3345   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3346   ARMISD::NodeType CompareType;
3347   switch (CondCode) {
3348   default:
3349     CompareType = ARMISD::CMP;
3350     break;
3351   case ARMCC::EQ:
3352   case ARMCC::NE:
3353     // Uses only Z Flag
3354     CompareType = ARMISD::CMPZ;
3355     break;
3356   }
3357   ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3358   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3359 }
3360
3361 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3362 SDValue
3363 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3364                              SDLoc dl) const {
3365   assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3366   SDValue Cmp;
3367   if (!isFloatingPointZero(RHS))
3368     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3369   else
3370     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3371   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3372 }
3373
3374 /// duplicateCmp - Glue values can have only one use, so this function
3375 /// duplicates a comparison node.
3376 SDValue
3377 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3378   unsigned Opc = Cmp.getOpcode();
3379   SDLoc DL(Cmp);
3380   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3381     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3382
3383   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3384   Cmp = Cmp.getOperand(0);
3385   Opc = Cmp.getOpcode();
3386   if (Opc == ARMISD::CMPFP)
3387     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3388   else {
3389     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3390     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3391   }
3392   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3393 }
3394
3395 std::pair<SDValue, SDValue>
3396 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3397                                  SDValue &ARMcc) const {
3398   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3399
3400   SDValue Value, OverflowCmp;
3401   SDValue LHS = Op.getOperand(0);
3402   SDValue RHS = Op.getOperand(1);
3403   SDLoc dl(Op);
3404
3405   // FIXME: We are currently always generating CMPs because we don't support
3406   // generating CMN through the backend. This is not as good as the natural
3407   // CMP case because it causes a register dependency and cannot be folded
3408   // later.
3409
3410   switch (Op.getOpcode()) {
3411   default:
3412     llvm_unreachable("Unknown overflow instruction!");
3413   case ISD::SADDO:
3414     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3415     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3416     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3417     break;
3418   case ISD::UADDO:
3419     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3420     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3421     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3422     break;
3423   case ISD::SSUBO:
3424     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3425     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3426     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3427     break;
3428   case ISD::USUBO:
3429     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3430     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3431     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3432     break;
3433   } // switch (...)
3434
3435   return std::make_pair(Value, OverflowCmp);
3436 }
3437
3438
3439 SDValue
3440 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3441   // Let legalize expand this if it isn't a legal type yet.
3442   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3443     return SDValue();
3444
3445   SDValue Value, OverflowCmp;
3446   SDValue ARMcc;
3447   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3448   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3449   SDLoc dl(Op);
3450   // We use 0 and 1 as false and true values.
3451   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3452   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3453   EVT VT = Op.getValueType();
3454
3455   SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
3456                                  ARMcc, CCR, OverflowCmp);
3457
3458   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3459   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
3460 }
3461
3462
3463 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3464   SDValue Cond = Op.getOperand(0);
3465   SDValue SelectTrue = Op.getOperand(1);
3466   SDValue SelectFalse = Op.getOperand(2);
3467   SDLoc dl(Op);
3468   unsigned Opc = Cond.getOpcode();
3469
3470   if (Cond.getResNo() == 1 &&
3471       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3472        Opc == ISD::USUBO)) {
3473     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3474       return SDValue();
3475
3476     SDValue Value, OverflowCmp;
3477     SDValue ARMcc;
3478     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3479     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3480     EVT VT = Op.getValueType();
3481
3482     return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
3483                    OverflowCmp, DAG);
3484   }
3485
3486   // Convert:
3487   //
3488   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3489   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3490   //
3491   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3492     const ConstantSDNode *CMOVTrue =
3493       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3494     const ConstantSDNode *CMOVFalse =
3495       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3496
3497     if (CMOVTrue && CMOVFalse) {
3498       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3499       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3500
3501       SDValue True;
3502       SDValue False;
3503       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3504         True = SelectTrue;
3505         False = SelectFalse;
3506       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3507         True = SelectFalse;
3508         False = SelectTrue;
3509       }
3510
3511       if (True.getNode() && False.getNode()) {
3512         EVT VT = Op.getValueType();
3513         SDValue ARMcc = Cond.getOperand(2);
3514         SDValue CCR = Cond.getOperand(3);
3515         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3516         assert(True.getValueType() == VT);
3517         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3518       }
3519     }
3520   }
3521
3522   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3523   // undefined bits before doing a full-word comparison with zero.
3524   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3525                      DAG.getConstant(1, dl, Cond.getValueType()));
3526
3527   return DAG.getSelectCC(dl, Cond,
3528                          DAG.getConstant(0, dl, Cond.getValueType()),
3529                          SelectTrue, SelectFalse, ISD::SETNE);
3530 }
3531
3532 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3533                                  bool &swpCmpOps, bool &swpVselOps) {
3534   // Start by selecting the GE condition code for opcodes that return true for
3535   // 'equality'
3536   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3537       CC == ISD::SETULE)
3538     CondCode = ARMCC::GE;
3539
3540   // and GT for opcodes that return false for 'equality'.
3541   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3542            CC == ISD::SETULT)
3543     CondCode = ARMCC::GT;
3544
3545   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3546   // to swap the compare operands.
3547   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3548       CC == ISD::SETULT)
3549     swpCmpOps = true;
3550
3551   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3552   // If we have an unordered opcode, we need to swap the operands to the VSEL
3553   // instruction (effectively negating the condition).
3554   //
3555   // This also has the effect of swapping which one of 'less' or 'greater'
3556   // returns true, so we also swap the compare operands. It also switches
3557   // whether we return true for 'equality', so we compensate by picking the
3558   // opposite condition code to our original choice.
3559   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3560       CC == ISD::SETUGT) {
3561     swpCmpOps = !swpCmpOps;
3562     swpVselOps = !swpVselOps;
3563     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3564   }
3565
3566   // 'ordered' is 'anything but unordered', so use the VS condition code and
3567   // swap the VSEL operands.
3568   if (CC == ISD::SETO) {
3569     CondCode = ARMCC::VS;
3570     swpVselOps = true;
3571   }
3572
3573   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3574   // code and swap the VSEL operands.
3575   if (CC == ISD::SETUNE) {
3576     CondCode = ARMCC::EQ;
3577     swpVselOps = true;
3578   }
3579 }
3580
3581 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3582                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3583                                    SDValue Cmp, SelectionDAG &DAG) const {
3584   if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3585     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3586                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3587     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3588                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3589
3590     SDValue TrueLow = TrueVal.getValue(0);
3591     SDValue TrueHigh = TrueVal.getValue(1);
3592     SDValue FalseLow = FalseVal.getValue(0);
3593     SDValue FalseHigh = FalseVal.getValue(1);
3594
3595     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3596                               ARMcc, CCR, Cmp);
3597     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3598                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
3599
3600     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3601   } else {
3602     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3603                        Cmp);
3604   }
3605 }
3606
3607 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3608   EVT VT = Op.getValueType();
3609   SDValue LHS = Op.getOperand(0);
3610   SDValue RHS = Op.getOperand(1);
3611   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3612   SDValue TrueVal = Op.getOperand(2);
3613   SDValue FalseVal = Op.getOperand(3);
3614   SDLoc dl(Op);
3615
3616   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3617     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3618                                                     dl);
3619
3620     // If softenSetCCOperands only returned one value, we should compare it to
3621     // zero.
3622     if (!RHS.getNode()) {
3623       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3624       CC = ISD::SETNE;
3625     }
3626   }
3627
3628   if (LHS.getValueType() == MVT::i32) {
3629     // Try to generate VSEL on ARMv8.
3630     // The VSEL instruction can't use all the usual ARM condition
3631     // codes: it only has two bits to select the condition code, so it's
3632     // constrained to use only GE, GT, VS and EQ.
3633     //
3634     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3635     // swap the operands of the previous compare instruction (effectively
3636     // inverting the compare condition, swapping 'less' and 'greater') and
3637     // sometimes need to swap the operands to the VSEL (which inverts the
3638     // condition in the sense of firing whenever the previous condition didn't)
3639     if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3640                                     TrueVal.getValueType() == MVT::f64)) {
3641       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3642       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3643           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3644         CC = ISD::getSetCCInverse(CC, true);
3645         std::swap(TrueVal, FalseVal);
3646       }
3647     }
3648
3649     SDValue ARMcc;
3650     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3651     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3652     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3653   }
3654
3655   ARMCC::CondCodes CondCode, CondCode2;
3656   FPCCToARMCC(CC, CondCode, CondCode2);
3657
3658   // Try to generate VMAXNM/VMINNM on ARMv8.
3659   if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3660                                   TrueVal.getValueType() == MVT::f64)) {
3661     bool swpCmpOps = false;
3662     bool swpVselOps = false;
3663     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3664
3665     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3666         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3667       if (swpCmpOps)
3668         std::swap(LHS, RHS);
3669       if (swpVselOps)
3670         std::swap(TrueVal, FalseVal);
3671     }
3672   }
3673
3674   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3675   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3676   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3677   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3678   if (CondCode2 != ARMCC::AL) {
3679     SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
3680     // FIXME: Needs another CMP because flag can have but one use.
3681     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3682     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3683   }
3684   return Result;
3685 }
3686
3687 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3688 /// to morph to an integer compare sequence.
3689 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3690                            const ARMSubtarget *Subtarget) {
3691   SDNode *N = Op.getNode();
3692   if (!N->hasOneUse())
3693     // Otherwise it requires moving the value from fp to integer registers.
3694     return false;
3695   if (!N->getNumValues())
3696     return false;
3697   EVT VT = Op.getValueType();
3698   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3699     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3700     // vmrs are very slow, e.g. cortex-a8.
3701     return false;
3702
3703   if (isFloatingPointZero(Op)) {
3704     SeenZero = true;
3705     return true;
3706   }
3707   return ISD::isNormalLoad(N);
3708 }
3709
3710 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3711   if (isFloatingPointZero(Op))
3712     return DAG.getConstant(0, SDLoc(Op), MVT::i32);
3713
3714   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3715     return DAG.getLoad(MVT::i32, SDLoc(Op),
3716                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3717                        Ld->isVolatile(), Ld->isNonTemporal(),
3718                        Ld->isInvariant(), Ld->getAlignment());
3719
3720   llvm_unreachable("Unknown VFP cmp argument!");
3721 }
3722
3723 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3724                            SDValue &RetVal1, SDValue &RetVal2) {
3725   SDLoc dl(Op);
3726
3727   if (isFloatingPointZero(Op)) {
3728     RetVal1 = DAG.getConstant(0, dl, MVT::i32);
3729     RetVal2 = DAG.getConstant(0, dl, MVT::i32);
3730     return;
3731   }
3732
3733   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3734     SDValue Ptr = Ld->getBasePtr();
3735     RetVal1 = DAG.getLoad(MVT::i32, dl,
3736                           Ld->getChain(), Ptr,
3737                           Ld->getPointerInfo(),
3738                           Ld->isVolatile(), Ld->isNonTemporal(),
3739                           Ld->isInvariant(), Ld->getAlignment());
3740
3741     EVT PtrType = Ptr.getValueType();
3742     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3743     SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
3744                                  PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
3745     RetVal2 = DAG.getLoad(MVT::i32, dl,
3746                           Ld->getChain(), NewPtr,
3747                           Ld->getPointerInfo().getWithOffset(4),
3748                           Ld->isVolatile(), Ld->isNonTemporal(),
3749                           Ld->isInvariant(), NewAlign);
3750     return;
3751   }
3752
3753   llvm_unreachable("Unknown VFP cmp argument!");
3754 }
3755
3756 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3757 /// f32 and even f64 comparisons to integer ones.
3758 SDValue
3759 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3760   SDValue Chain = Op.getOperand(0);
3761   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3762   SDValue LHS = Op.getOperand(2);
3763   SDValue RHS = Op.getOperand(3);
3764   SDValue Dest = Op.getOperand(4);
3765   SDLoc dl(Op);
3766
3767   bool LHSSeenZero = false;
3768   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3769   bool RHSSeenZero = false;
3770   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3771   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3772     // If unsafe fp math optimization is enabled and there are no other uses of
3773     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3774     // to an integer comparison.
3775     if (CC == ISD::SETOEQ)
3776       CC = ISD::SETEQ;
3777     else if (CC == ISD::SETUNE)
3778       CC = ISD::SETNE;
3779
3780     SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
3781     SDValue ARMcc;
3782     if (LHS.getValueType() == MVT::f32) {
3783       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3784                         bitcastf32Toi32(LHS, DAG), Mask);
3785       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3786                         bitcastf32Toi32(RHS, DAG), Mask);
3787       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3788       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3789       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3790                          Chain, Dest, ARMcc, CCR, Cmp);
3791     }
3792
3793     SDValue LHS1, LHS2;
3794     SDValue RHS1, RHS2;
3795     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3796     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3797     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3798     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3799     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3800     ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3801     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3802     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3803     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3804   }
3805
3806   return SDValue();
3807 }
3808
3809 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3810   SDValue Chain = Op.getOperand(0);
3811   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3812   SDValue LHS = Op.getOperand(2);
3813   SDValue RHS = Op.getOperand(3);
3814   SDValue Dest = Op.getOperand(4);
3815   SDLoc dl(Op);
3816
3817   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3818     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3819                                                     dl);
3820
3821     // If softenSetCCOperands only returned one value, we should compare it to
3822     // zero.
3823     if (!RHS.getNode()) {
3824       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3825       CC = ISD::SETNE;
3826     }
3827   }
3828
3829   if (LHS.getValueType() == MVT::i32) {
3830     SDValue ARMcc;
3831     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3832     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3833     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3834                        Chain, Dest, ARMcc, CCR, Cmp);
3835   }
3836
3837   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3838
3839   if (getTargetMachine().Options.UnsafeFPMath &&
3840       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3841        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3842     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3843     if (Result.getNode())
3844       return Result;
3845   }
3846
3847   ARMCC::CondCodes CondCode, CondCode2;
3848   FPCCToARMCC(CC, CondCode, CondCode2);
3849
3850   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3851   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3852   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3853   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3854   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3855   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3856   if (CondCode2 != ARMCC::AL) {
3857     ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
3858     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3859     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3860   }
3861   return Res;
3862 }
3863
3864 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3865   SDValue Chain = Op.getOperand(0);
3866   SDValue Table = Op.getOperand(1);
3867   SDValue Index = Op.getOperand(2);
3868   SDLoc dl(Op);
3869
3870   EVT PTy = getPointerTy(DAG.getDataLayout());
3871   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3872   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3873   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
3874   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
3875   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3876   if (Subtarget->isThumb2()) {
3877     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3878     // which does another jump to the destination. This also makes it easier
3879     // to translate it to TBB / TBH later.
3880     // FIXME: This might not work if the function is extremely large.
3881     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3882                        Addr, Op.getOperand(2), JTI);
3883   }
3884   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3885     Addr =
3886         DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3887                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()),
3888                     false, false, false, 0);
3889     Chain = Addr.getValue(1);
3890     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3891     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3892   } else {
3893     Addr =
3894         DAG.getLoad(PTy, dl, Chain, Addr,
3895                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()),
3896                     false, false, false, 0);
3897     Chain = Addr.getValue(1);
3898     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3899   }
3900 }
3901
3902 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3903   EVT VT = Op.getValueType();
3904   SDLoc dl(Op);
3905
3906   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3907     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3908       return Op;
3909     return DAG.UnrollVectorOp(Op.getNode());
3910   }
3911
3912   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3913          "Invalid type for custom lowering!");
3914   if (VT != MVT::v4i16)
3915     return DAG.UnrollVectorOp(Op.getNode());
3916
3917   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3918   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3919 }
3920
3921 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3922   EVT VT = Op.getValueType();
3923   if (VT.isVector())
3924     return LowerVectorFP_TO_INT(Op, DAG);
3925   if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3926     RTLIB::Libcall LC;
3927     if (Op.getOpcode() == ISD::FP_TO_SINT)
3928       LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
3929                               Op.getValueType());
3930     else
3931       LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
3932                               Op.getValueType());
3933     return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
3934                        /*isSigned*/ false, SDLoc(Op)).first;
3935   }
3936
3937   return Op;
3938 }
3939
3940 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3941   EVT VT = Op.getValueType();
3942   SDLoc dl(Op);
3943
3944   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3945     if (VT.getVectorElementType() == MVT::f32)
3946       return Op;
3947     return DAG.UnrollVectorOp(Op.getNode());
3948   }
3949
3950   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3951          "Invalid type for custom lowering!");
3952   if (VT != MVT::v4f32)
3953     return DAG.UnrollVectorOp(Op.getNode());
3954
3955   unsigned CastOpc;
3956   unsigned Opc;
3957   switch (Op.getOpcode()) {
3958   default: llvm_unreachable("Invalid opcode!");
3959   case ISD::SINT_TO_FP:
3960     CastOpc = ISD::SIGN_EXTEND;
3961     Opc = ISD::SINT_TO_FP;
3962     break;
3963   case ISD::UINT_TO_FP:
3964     CastOpc = ISD::ZERO_EXTEND;
3965     Opc = ISD::UINT_TO_FP;
3966     break;
3967   }
3968
3969   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3970   return DAG.getNode(Opc, dl, VT, Op);
3971 }
3972
3973 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
3974   EVT VT = Op.getValueType();
3975   if (VT.isVector())
3976     return LowerVectorINT_TO_FP(Op, DAG);
3977   if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
3978     RTLIB::Libcall LC;
3979     if (Op.getOpcode() == ISD::SINT_TO_FP)
3980       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
3981                               Op.getValueType());
3982     else
3983       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
3984                               Op.getValueType());
3985     return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
3986                        /*isSigned*/ false, SDLoc(Op)).first;
3987   }
3988
3989   return Op;
3990 }
3991
3992 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3993   // Implement fcopysign with a fabs and a conditional fneg.
3994   SDValue Tmp0 = Op.getOperand(0);
3995   SDValue Tmp1 = Op.getOperand(1);
3996   SDLoc dl(Op);
3997   EVT VT = Op.getValueType();
3998   EVT SrcVT = Tmp1.getValueType();
3999   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
4000     Tmp0.getOpcode() == ARMISD::VMOVDRR;
4001   bool UseNEON = !InGPR && Subtarget->hasNEON();
4002
4003   if (UseNEON) {
4004     // Use VBSL to copy the sign bit.
4005     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
4006     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
4007                                DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
4008     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
4009     if (VT == MVT::f64)
4010       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4011                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
4012                          DAG.getConstant(32, dl, MVT::i32));
4013     else /*if (VT == MVT::f32)*/
4014       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
4015     if (SrcVT == MVT::f32) {
4016       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4017       if (VT == MVT::f64)
4018         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4019                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4020                            DAG.getConstant(32, dl, MVT::i32));
4021     } else if (VT == MVT::f32)
4022       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4023                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4024                          DAG.getConstant(32, dl, MVT::i32));
4025     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4026     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4027
4028     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4029                                             dl, MVT::i32);
4030     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4031     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4032                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4033
4034     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4035                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4036                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4037     if (VT == MVT::f32) {
4038       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4039       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4040                         DAG.getConstant(0, dl, MVT::i32));
4041     } else {
4042       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4043     }
4044
4045     return Res;
4046   }
4047
4048   // Bitcast operand 1 to i32.
4049   if (SrcVT == MVT::f64)
4050     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4051                        Tmp1).getValue(1);
4052   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4053
4054   // Or in the signbit with integer operations.
4055   SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
4056   SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4057   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4058   if (VT == MVT::f32) {
4059     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4060                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4061     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4062                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4063   }
4064
4065   // f64: Or the high part with signbit and then combine two parts.
4066   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4067                      Tmp0);
4068   SDValue Lo = Tmp0.getValue(0);
4069   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4070   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4071   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4072 }
4073
4074 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4075   MachineFunction &MF = DAG.getMachineFunction();
4076   MachineFrameInfo *MFI = MF.getFrameInfo();
4077   MFI->setReturnAddressIsTaken(true);
4078
4079   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4080     return SDValue();
4081
4082   EVT VT = Op.getValueType();
4083   SDLoc dl(Op);
4084   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4085   if (Depth) {
4086     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4087     SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
4088     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4089                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4090                        MachinePointerInfo(), false, false, false, 0);
4091   }
4092
4093   // Return LR, which contains the return address. Mark it an implicit live-in.
4094   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4095   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4096 }
4097
4098 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4099   const ARMBaseRegisterInfo &ARI =
4100     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4101   MachineFunction &MF = DAG.getMachineFunction();
4102   MachineFrameInfo *MFI = MF.getFrameInfo();
4103   MFI->setFrameAddressIsTaken(true);
4104
4105   EVT VT = Op.getValueType();
4106   SDLoc dl(Op);  // FIXME probably not meaningful
4107   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4108   unsigned FrameReg = ARI.getFrameRegister(MF);
4109   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4110   while (Depth--)
4111     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4112                             MachinePointerInfo(),
4113                             false, false, false, 0);
4114   return FrameAddr;
4115 }
4116
4117 // FIXME? Maybe this could be a TableGen attribute on some registers and
4118 // this table could be generated automatically from RegInfo.
4119 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
4120                                               SelectionDAG &DAG) const {
4121   unsigned Reg = StringSwitch<unsigned>(RegName)
4122                        .Case("sp", ARM::SP)
4123                        .Default(0);
4124   if (Reg)
4125     return Reg;
4126   report_fatal_error(Twine("Invalid register name \""
4127                               + StringRef(RegName)  + "\"."));
4128 }
4129
4130 // Result is 64 bit value so split into two 32 bit values and return as a
4131 // pair of values.
4132 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
4133                                 SelectionDAG &DAG) {
4134   SDLoc DL(N);
4135
4136   // This function is only supposed to be called for i64 type destination.
4137   assert(N->getValueType(0) == MVT::i64
4138           && "ExpandREAD_REGISTER called for non-i64 type result.");
4139
4140   SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
4141                              DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
4142                              N->getOperand(0),
4143                              N->getOperand(1));
4144
4145   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
4146                     Read.getValue(1)));
4147   Results.push_back(Read.getOperand(0));
4148 }
4149
4150 /// ExpandBITCAST - If the target supports VFP, this function is called to
4151 /// expand a bit convert where either the source or destination type is i64 to
4152 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
4153 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4154 /// vectors), since the legalizer won't know what to do with that.
4155 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4156   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4157   SDLoc dl(N);
4158   SDValue Op = N->getOperand(0);
4159
4160   // This function is only supposed to be called for i64 types, either as the
4161   // source or destination of the bit convert.
4162   EVT SrcVT = Op.getValueType();
4163   EVT DstVT = N->getValueType(0);
4164   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4165          "ExpandBITCAST called for non-i64 type");
4166
4167   // Turn i64->f64 into VMOVDRR.
4168   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4169     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4170                              DAG.getConstant(0, dl, MVT::i32));
4171     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4172                              DAG.getConstant(1, dl, MVT::i32));
4173     return DAG.getNode(ISD::BITCAST, dl, DstVT,
4174                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4175   }
4176
4177   // Turn f64->i64 into VMOVRRD.
4178   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4179     SDValue Cvt;
4180     if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
4181         SrcVT.getVectorNumElements() > 1)
4182       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4183                         DAG.getVTList(MVT::i32, MVT::i32),
4184                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4185     else
4186       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4187                         DAG.getVTList(MVT::i32, MVT::i32), Op);
4188     // Merge the pieces into a single i64 value.
4189     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4190   }
4191
4192   return SDValue();
4193 }
4194
4195 /// getZeroVector - Returns a vector of specified type with all zero elements.
4196 /// Zero vectors are used to represent vector negation and in those cases
4197 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
4198 /// not support i64 elements, so sometimes the zero vectors will need to be
4199 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
4200 /// zero vector.
4201 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4202   assert(VT.isVector() && "Expected a vector type");
4203   // The canonical modified immediate encoding of a zero vector is....0!
4204   SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
4205   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4206   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4207   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4208 }
4209
4210 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4211 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4212 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4213                                                 SelectionDAG &DAG) const {
4214   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4215   EVT VT = Op.getValueType();
4216   unsigned VTBits = VT.getSizeInBits();
4217   SDLoc dl(Op);
4218   SDValue ShOpLo = Op.getOperand(0);
4219   SDValue ShOpHi = Op.getOperand(1);
4220   SDValue ShAmt  = Op.getOperand(2);
4221   SDValue ARMcc;
4222   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4223
4224   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4225
4226   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4227                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4228   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4229   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4230                                    DAG.getConstant(VTBits, dl, MVT::i32));
4231   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4232   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4233   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4234
4235   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4236   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4237                           ISD::SETGE, ARMcc, DAG, dl);
4238   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4239   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4240                            CCR, Cmp);
4241
4242   SDValue Ops[2] = { Lo, Hi };
4243   return DAG.getMergeValues(Ops, dl);
4244 }
4245
4246 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4247 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4248 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4249                                                SelectionDAG &DAG) const {
4250   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4251   EVT VT = Op.getValueType();
4252   unsigned VTBits = VT.getSizeInBits();
4253   SDLoc dl(Op);
4254   SDValue ShOpLo = Op.getOperand(0);
4255   SDValue ShOpHi = Op.getOperand(1);
4256   SDValue ShAmt  = Op.getOperand(2);
4257   SDValue ARMcc;
4258
4259   assert(Op.getOpcode() == ISD::SHL_PARTS);
4260   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4261                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4262   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4263   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4264                                    DAG.getConstant(VTBits, dl, MVT::i32));
4265   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4266   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4267
4268   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4269   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4270   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4271                           ISD::SETGE, ARMcc, DAG, dl);
4272   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4273   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4274                            CCR, Cmp);
4275
4276   SDValue Ops[2] = { Lo, Hi };
4277   return DAG.getMergeValues(Ops, dl);
4278 }
4279
4280 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4281                                             SelectionDAG &DAG) const {
4282   // The rounding mode is in bits 23:22 of the FPSCR.
4283   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4284   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4285   // so that the shift + and get folded into a bitfield extract.
4286   SDLoc dl(Op);
4287   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4288                               DAG.getConstant(Intrinsic::arm_get_fpscr, dl,
4289                                               MVT::i32));
4290   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4291                                   DAG.getConstant(1U << 22, dl, MVT::i32));
4292   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4293                               DAG.getConstant(22, dl, MVT::i32));
4294   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4295                      DAG.getConstant(3, dl, MVT::i32));
4296 }
4297
4298 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4299                          const ARMSubtarget *ST) {
4300   SDLoc dl(N);
4301   EVT VT = N->getValueType(0);
4302   if (VT.isVector()) {
4303     assert(ST->hasNEON());
4304
4305     // Compute the least significant set bit: LSB = X & -X
4306     SDValue X = N->getOperand(0);
4307     SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
4308     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
4309
4310     EVT ElemTy = VT.getVectorElementType();
4311
4312     if (ElemTy == MVT::i8) {
4313       // Compute with: cttz(x) = ctpop(lsb - 1)
4314       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4315                                 DAG.getTargetConstant(1, dl, ElemTy));
4316       SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4317       return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
4318     }
4319
4320     if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
4321         (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
4322       // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
4323       unsigned NumBits = ElemTy.getSizeInBits();
4324       SDValue WidthMinus1 =
4325           DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4326                       DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
4327       SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
4328       return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
4329     }
4330
4331     // Compute with: cttz(x) = ctpop(lsb - 1)
4332
4333     // Since we can only compute the number of bits in a byte with vcnt.8, we
4334     // have to gather the result with pairwise addition (vpaddl) for i16, i32,
4335     // and i64.
4336
4337     // Compute LSB - 1.
4338     SDValue Bits;
4339     if (ElemTy == MVT::i64) {
4340       // Load constant 0xffff'ffff'ffff'ffff to register.
4341       SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4342                                DAG.getTargetConstant(0x1eff, dl, MVT::i32));
4343       Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
4344     } else {
4345       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4346                                 DAG.getTargetConstant(1, dl, ElemTy));
4347       Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4348     }
4349
4350     // Count #bits with vcnt.8.
4351     EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4352     SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits);
4353     SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8);
4354
4355     // Gather the #bits with vpaddl (pairwise add.)
4356     EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4357     SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit,
4358         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4359         Cnt8);
4360     if (ElemTy == MVT::i16)
4361       return Cnt16;
4362
4363     EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32;
4364     SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit,
4365         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4366         Cnt16);
4367     if (ElemTy == MVT::i32)
4368       return Cnt32;
4369
4370     assert(ElemTy == MVT::i64);
4371     SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4372         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4373         Cnt32);
4374     return Cnt64;
4375   }
4376
4377   if (!ST->hasV6T2Ops())
4378     return SDValue();
4379
4380   SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0));
4381   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4382 }
4383
4384 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4385 /// for each 16-bit element from operand, repeated.  The basic idea is to
4386 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4387 ///
4388 /// Trace for v4i16:
4389 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
4390 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4391 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4392 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4393 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
4394 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
4395 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4396 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
4397 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4398   EVT VT = N->getValueType(0);
4399   SDLoc DL(N);
4400
4401   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4402   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4403   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4404   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4405   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4406   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4407 }
4408
4409 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4410 /// bit-count for each 16-bit element from the operand.  We need slightly
4411 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4412 /// 64/128-bit registers.
4413 ///
4414 /// Trace for v4i16:
4415 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
4416 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4417 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
4418 /// v4i16:Extracted = [k0    k1    k2    k3    ]
4419 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4420   EVT VT = N->getValueType(0);
4421   SDLoc DL(N);
4422
4423   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4424   if (VT.is64BitVector()) {
4425     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4426     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4427                        DAG.getIntPtrConstant(0, DL));
4428   } else {
4429     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4430                                     BitCounts, DAG.getIntPtrConstant(0, DL));
4431     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4432   }
4433 }
4434
4435 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4436 /// bit-count for each 32-bit element from the operand.  The idea here is
4437 /// to split the vector into 16-bit elements, leverage the 16-bit count
4438 /// routine, and then combine the results.
4439 ///
4440 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4441 /// input    = [v0    v1    ] (vi: 32-bit elements)
4442 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4443 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4444 /// vrev: N0 = [k1 k0 k3 k2 ]
4445 ///            [k0 k1 k2 k3 ]
4446 ///       N1 =+[k1 k0 k3 k2 ]
4447 ///            [k0 k2 k1 k3 ]
4448 ///       N2 =+[k1 k3 k0 k2 ]
4449 ///            [k0    k2    k1    k3    ]
4450 /// Extended =+[k1    k3    k0    k2    ]
4451 ///            [k0    k2    ]
4452 /// Extracted=+[k1    k3    ]
4453 ///
4454 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4455   EVT VT = N->getValueType(0);
4456   SDLoc DL(N);
4457
4458   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4459
4460   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4461   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4462   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4463   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4464   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4465
4466   if (VT.is64BitVector()) {
4467     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4468     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4469                        DAG.getIntPtrConstant(0, DL));
4470   } else {
4471     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4472                                     DAG.getIntPtrConstant(0, DL));
4473     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4474   }
4475 }
4476
4477 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4478                           const ARMSubtarget *ST) {
4479   EVT VT = N->getValueType(0);
4480
4481   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4482   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4483           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4484          "Unexpected type for custom ctpop lowering");
4485
4486   if (VT.getVectorElementType() == MVT::i32)
4487     return lowerCTPOP32BitElements(N, DAG);
4488   else
4489     return lowerCTPOP16BitElements(N, DAG);
4490 }
4491
4492 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4493                           const ARMSubtarget *ST) {
4494   EVT VT = N->getValueType(0);
4495   SDLoc dl(N);
4496
4497   if (!VT.isVector())
4498     return SDValue();
4499
4500   // Lower vector shifts on NEON to use VSHL.
4501   assert(ST->hasNEON() && "unexpected vector shift");
4502
4503   // Left shifts translate directly to the vshiftu intrinsic.
4504   if (N->getOpcode() == ISD::SHL)
4505     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4506                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
4507                                        MVT::i32),
4508                        N->getOperand(0), N->getOperand(1));
4509
4510   assert((N->getOpcode() == ISD::SRA ||
4511           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4512
4513   // NEON uses the same intrinsics for both left and right shifts.  For
4514   // right shifts, the shift amounts are negative, so negate the vector of
4515   // shift amounts.
4516   EVT ShiftVT = N->getOperand(1).getValueType();
4517   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4518                                      getZeroVector(ShiftVT, DAG, dl),
4519                                      N->getOperand(1));
4520   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4521                              Intrinsic::arm_neon_vshifts :
4522                              Intrinsic::arm_neon_vshiftu);
4523   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4524                      DAG.getConstant(vshiftInt, dl, MVT::i32),
4525                      N->getOperand(0), NegatedCount);
4526 }
4527
4528 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4529                                 const ARMSubtarget *ST) {
4530   EVT VT = N->getValueType(0);
4531   SDLoc dl(N);
4532
4533   // We can get here for a node like i32 = ISD::SHL i32, i64
4534   if (VT != MVT::i64)
4535     return SDValue();
4536
4537   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4538          "Unknown shift to lower!");
4539
4540   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4541   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4542       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4543     return SDValue();
4544
4545   // If we are in thumb mode, we don't have RRX.
4546   if (ST->isThumb1Only()) return SDValue();
4547
4548   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4549   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4550                            DAG.getConstant(0, dl, MVT::i32));
4551   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4552                            DAG.getConstant(1, dl, MVT::i32));
4553
4554   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4555   // captures the result into a carry flag.
4556   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4557   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4558
4559   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4560   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4561
4562   // Merge the pieces into a single i64 value.
4563  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4564 }
4565
4566 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4567   SDValue TmpOp0, TmpOp1;
4568   bool Invert = false;
4569   bool Swap = false;
4570   unsigned Opc = 0;
4571
4572   SDValue Op0 = Op.getOperand(0);
4573   SDValue Op1 = Op.getOperand(1);
4574   SDValue CC = Op.getOperand(2);
4575   EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
4576   EVT VT = Op.getValueType();
4577   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4578   SDLoc dl(Op);
4579
4580   if (CmpVT.getVectorElementType() == MVT::i64)
4581     // 64-bit comparisons are not legal. We've marked SETCC as non-Custom,
4582     // but it's possible that our operands are 64-bit but our result is 32-bit.
4583     // Bail in this case.
4584     return SDValue();
4585
4586   if (Op1.getValueType().isFloatingPoint()) {
4587     switch (SetCCOpcode) {
4588     default: llvm_unreachable("Illegal FP comparison");
4589     case ISD::SETUNE:
4590     case ISD::SETNE:  Invert = true; // Fallthrough
4591     case ISD::SETOEQ:
4592     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4593     case ISD::SETOLT:
4594     case ISD::SETLT: Swap = true; // Fallthrough
4595     case ISD::SETOGT:
4596     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4597     case ISD::SETOLE:
4598     case ISD::SETLE:  Swap = true; // Fallthrough
4599     case ISD::SETOGE:
4600     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4601     case ISD::SETUGE: Swap = true; // Fallthrough
4602     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4603     case ISD::SETUGT: Swap = true; // Fallthrough
4604     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4605     case ISD::SETUEQ: Invert = true; // Fallthrough
4606     case ISD::SETONE:
4607       // Expand this to (OLT | OGT).
4608       TmpOp0 = Op0;
4609       TmpOp1 = Op1;
4610       Opc = ISD::OR;
4611       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4612       Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
4613       break;
4614     case ISD::SETUO: Invert = true; // Fallthrough
4615     case ISD::SETO:
4616       // Expand this to (OLT | OGE).
4617       TmpOp0 = Op0;
4618       TmpOp1 = Op1;
4619       Opc = ISD::OR;
4620       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4621       Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
4622       break;
4623     }
4624   } else {
4625     // Integer comparisons.
4626     switch (SetCCOpcode) {
4627     default: llvm_unreachable("Illegal integer comparison");
4628     case ISD::SETNE:  Invert = true;
4629     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4630     case ISD::SETLT:  Swap = true;
4631     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4632     case ISD::SETLE:  Swap = true;
4633     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4634     case ISD::SETULT: Swap = true;
4635     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4636     case ISD::SETULE: Swap = true;
4637     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4638     }
4639
4640     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4641     if (Opc == ARMISD::VCEQ) {
4642
4643       SDValue AndOp;
4644       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4645         AndOp = Op0;
4646       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4647         AndOp = Op1;
4648
4649       // Ignore bitconvert.
4650       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4651         AndOp = AndOp.getOperand(0);
4652
4653       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4654         Opc = ARMISD::VTST;
4655         Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
4656         Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
4657         Invert = !Invert;
4658       }
4659     }
4660   }
4661
4662   if (Swap)
4663     std::swap(Op0, Op1);
4664
4665   // If one of the operands is a constant vector zero, attempt to fold the
4666   // comparison to a specialized compare-against-zero form.
4667   SDValue SingleOp;
4668   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4669     SingleOp = Op0;
4670   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4671     if (Opc == ARMISD::VCGE)
4672       Opc = ARMISD::VCLEZ;
4673     else if (Opc == ARMISD::VCGT)
4674       Opc = ARMISD::VCLTZ;
4675     SingleOp = Op1;
4676   }
4677
4678   SDValue Result;
4679   if (SingleOp.getNode()) {
4680     switch (Opc) {
4681     case ARMISD::VCEQ:
4682       Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
4683     case ARMISD::VCGE:
4684       Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
4685     case ARMISD::VCLEZ:
4686       Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
4687     case ARMISD::VCGT:
4688       Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
4689     case ARMISD::VCLTZ:
4690       Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
4691     default:
4692       Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4693     }
4694   } else {
4695      Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4696   }
4697
4698   Result = DAG.getSExtOrTrunc(Result, dl, VT);
4699
4700   if (Invert)
4701     Result = DAG.getNOT(dl, Result, VT);
4702
4703   return Result;
4704 }
4705
4706 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4707 /// valid vector constant for a NEON instruction with a "modified immediate"
4708 /// operand (e.g., VMOV).  If so, return the encoded value.
4709 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4710                                  unsigned SplatBitSize, SelectionDAG &DAG,
4711                                  SDLoc dl, EVT &VT, bool is128Bits,
4712                                  NEONModImmType type) {
4713   unsigned OpCmode, Imm;
4714
4715   // SplatBitSize is set to the smallest size that splats the vector, so a
4716   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4717   // immediate instructions others than VMOV do not support the 8-bit encoding
4718   // of a zero vector, and the default encoding of zero is supposed to be the
4719   // 32-bit version.
4720   if (SplatBits == 0)
4721     SplatBitSize = 32;
4722
4723   switch (SplatBitSize) {
4724   case 8:
4725     if (type != VMOVModImm)
4726       return SDValue();
4727     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4728     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4729     OpCmode = 0xe;
4730     Imm = SplatBits;
4731     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4732     break;
4733
4734   case 16:
4735     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4736     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4737     if ((SplatBits & ~0xff) == 0) {
4738       // Value = 0x00nn: Op=x, Cmode=100x.
4739       OpCmode = 0x8;
4740       Imm = SplatBits;
4741       break;
4742     }
4743     if ((SplatBits & ~0xff00) == 0) {
4744       // Value = 0xnn00: Op=x, Cmode=101x.
4745       OpCmode = 0xa;
4746       Imm = SplatBits >> 8;
4747       break;
4748     }
4749     return SDValue();
4750
4751   case 32:
4752     // NEON's 32-bit VMOV supports splat values where:
4753     // * only one byte is nonzero, or
4754     // * the least significant byte is 0xff and the second byte is nonzero, or
4755     // * the least significant 2 bytes are 0xff and the third is nonzero.
4756     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4757     if ((SplatBits & ~0xff) == 0) {
4758       // Value = 0x000000nn: Op=x, Cmode=000x.
4759       OpCmode = 0;
4760       Imm = SplatBits;
4761       break;
4762     }
4763     if ((SplatBits & ~0xff00) == 0) {
4764       // Value = 0x0000nn00: Op=x, Cmode=001x.
4765       OpCmode = 0x2;
4766       Imm = SplatBits >> 8;
4767       break;
4768     }
4769     if ((SplatBits & ~0xff0000) == 0) {
4770       // Value = 0x00nn0000: Op=x, Cmode=010x.
4771       OpCmode = 0x4;
4772       Imm = SplatBits >> 16;
4773       break;
4774     }
4775     if ((SplatBits & ~0xff000000) == 0) {
4776       // Value = 0xnn000000: Op=x, Cmode=011x.
4777       OpCmode = 0x6;
4778       Imm = SplatBits >> 24;
4779       break;
4780     }
4781
4782     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4783     if (type == OtherModImm) return SDValue();
4784
4785     if ((SplatBits & ~0xffff) == 0 &&
4786         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4787       // Value = 0x0000nnff: Op=x, Cmode=1100.
4788       OpCmode = 0xc;
4789       Imm = SplatBits >> 8;
4790       break;
4791     }
4792
4793     if ((SplatBits & ~0xffffff) == 0 &&
4794         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4795       // Value = 0x00nnffff: Op=x, Cmode=1101.
4796       OpCmode = 0xd;
4797       Imm = SplatBits >> 16;
4798       break;
4799     }
4800
4801     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4802     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4803     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4804     // and fall through here to test for a valid 64-bit splat.  But, then the
4805     // caller would also need to check and handle the change in size.
4806     return SDValue();
4807
4808   case 64: {
4809     if (type != VMOVModImm)
4810       return SDValue();
4811     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4812     uint64_t BitMask = 0xff;
4813     uint64_t Val = 0;
4814     unsigned ImmMask = 1;
4815     Imm = 0;
4816     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4817       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4818         Val |= BitMask;
4819         Imm |= ImmMask;
4820       } else if ((SplatBits & BitMask) != 0) {
4821         return SDValue();
4822       }
4823       BitMask <<= 8;
4824       ImmMask <<= 1;
4825     }
4826
4827     if (DAG.getDataLayout().isBigEndian())
4828       // swap higher and lower 32 bit word
4829       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4830
4831     // Op=1, Cmode=1110.
4832     OpCmode = 0x1e;
4833     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4834     break;
4835   }
4836
4837   default:
4838     llvm_unreachable("unexpected size for isNEONModifiedImm");
4839   }
4840
4841   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4842   return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
4843 }
4844
4845 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4846                                            const ARMSubtarget *ST) const {
4847   if (!ST->hasVFP3())
4848     return SDValue();
4849
4850   bool IsDouble = Op.getValueType() == MVT::f64;
4851   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4852
4853   // Use the default (constant pool) lowering for double constants when we have
4854   // an SP-only FPU
4855   if (IsDouble && Subtarget->isFPOnlySP())
4856     return SDValue();
4857
4858   // Try splatting with a VMOV.f32...
4859   APFloat FPVal = CFP->getValueAPF();
4860   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4861
4862   if (ImmVal != -1) {
4863     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4864       // We have code in place to select a valid ConstantFP already, no need to
4865       // do any mangling.
4866       return Op;
4867     }
4868
4869     // It's a float and we are trying to use NEON operations where
4870     // possible. Lower it to a splat followed by an extract.
4871     SDLoc DL(Op);
4872     SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
4873     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4874                                       NewVal);
4875     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4876                        DAG.getConstant(0, DL, MVT::i32));
4877   }
4878
4879   // The rest of our options are NEON only, make sure that's allowed before
4880   // proceeding..
4881   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4882     return SDValue();
4883
4884   EVT VMovVT;
4885   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4886
4887   // It wouldn't really be worth bothering for doubles except for one very
4888   // important value, which does happen to match: 0.0. So make sure we don't do
4889   // anything stupid.
4890   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4891     return SDValue();
4892
4893   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4894   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
4895                                      VMovVT, false, VMOVModImm);
4896   if (NewVal != SDValue()) {
4897     SDLoc DL(Op);
4898     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4899                                       NewVal);
4900     if (IsDouble)
4901       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4902
4903     // It's a float: cast and extract a vector element.
4904     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4905                                        VecConstant);
4906     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4907                        DAG.getConstant(0, DL, MVT::i32));
4908   }
4909
4910   // Finally, try a VMVN.i32
4911   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
4912                              false, VMVNModImm);
4913   if (NewVal != SDValue()) {
4914     SDLoc DL(Op);
4915     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4916
4917     if (IsDouble)
4918       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4919
4920     // It's a float: cast and extract a vector element.
4921     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4922                                        VecConstant);
4923     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4924                        DAG.getConstant(0, DL, MVT::i32));
4925   }
4926
4927   return SDValue();
4928 }
4929
4930 // check if an VEXT instruction can handle the shuffle mask when the
4931 // vector sources of the shuffle are the same.
4932 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4933   unsigned NumElts = VT.getVectorNumElements();
4934
4935   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4936   if (M[0] < 0)
4937     return false;
4938
4939   Imm = M[0];
4940
4941   // If this is a VEXT shuffle, the immediate value is the index of the first
4942   // element.  The other shuffle indices must be the successive elements after
4943   // the first one.
4944   unsigned ExpectedElt = Imm;
4945   for (unsigned i = 1; i < NumElts; ++i) {
4946     // Increment the expected index.  If it wraps around, just follow it
4947     // back to index zero and keep going.
4948     ++ExpectedElt;
4949     if (ExpectedElt == NumElts)
4950       ExpectedElt = 0;
4951
4952     if (M[i] < 0) continue; // ignore UNDEF indices
4953     if (ExpectedElt != static_cast<unsigned>(M[i]))
4954       return false;
4955   }
4956
4957   return true;
4958 }
4959
4960
4961 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4962                        bool &ReverseVEXT, unsigned &Imm) {
4963   unsigned NumElts = VT.getVectorNumElements();
4964   ReverseVEXT = false;
4965
4966   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4967   if (M[0] < 0)
4968     return false;
4969
4970   Imm = M[0];
4971
4972   // If this is a VEXT shuffle, the immediate value is the index of the first
4973   // element.  The other shuffle indices must be the successive elements after
4974   // the first one.
4975   unsigned ExpectedElt = Imm;
4976   for (unsigned i = 1; i < NumElts; ++i) {
4977     // Increment the expected index.  If it wraps around, it may still be
4978     // a VEXT but the source vectors must be swapped.
4979     ExpectedElt += 1;
4980     if (ExpectedElt == NumElts * 2) {
4981       ExpectedElt = 0;
4982       ReverseVEXT = true;
4983     }
4984
4985     if (M[i] < 0) continue; // ignore UNDEF indices
4986     if (ExpectedElt != static_cast<unsigned>(M[i]))
4987       return false;
4988   }
4989
4990   // Adjust the index value if the source operands will be swapped.
4991   if (ReverseVEXT)
4992     Imm -= NumElts;
4993
4994   return true;
4995 }
4996
4997 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4998 /// instruction with the specified blocksize.  (The order of the elements
4999 /// within each block of the vector is reversed.)
5000 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5001   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
5002          "Only possible block sizes for VREV are: 16, 32, 64");
5003
5004   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5005   if (EltSz == 64)
5006     return false;
5007
5008   unsigned NumElts = VT.getVectorNumElements();
5009   unsigned BlockElts = M[0] + 1;
5010   // If the first shuffle index is UNDEF, be optimistic.
5011   if (M[0] < 0)
5012     BlockElts = BlockSize / EltSz;
5013
5014   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5015     return false;
5016
5017   for (unsigned i = 0; i < NumElts; ++i) {
5018     if (M[i] < 0) continue; // ignore UNDEF indices
5019     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
5020       return false;
5021   }
5022
5023   return true;
5024 }
5025
5026 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
5027   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
5028   // range, then 0 is placed into the resulting vector. So pretty much any mask
5029   // of 8 elements can work here.
5030   return VT == MVT::v8i8 && M.size() == 8;
5031 }
5032
5033 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
5034 // checking that pairs of elements in the shuffle mask represent the same index
5035 // in each vector, incrementing the expected index by 2 at each step.
5036 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
5037 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
5038 //  v2={e,f,g,h}
5039 // WhichResult gives the offset for each element in the mask based on which
5040 // of the two results it belongs to.
5041 //
5042 // The transpose can be represented either as:
5043 // result1 = shufflevector v1, v2, result1_shuffle_mask
5044 // result2 = shufflevector v1, v2, result2_shuffle_mask
5045 // where v1/v2 and the shuffle masks have the same number of elements
5046 // (here WhichResult (see below) indicates which result is being checked)
5047 //
5048 // or as:
5049 // results = shufflevector v1, v2, shuffle_mask
5050 // where both results are returned in one vector and the shuffle mask has twice
5051 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
5052 // want to check the low half and high half of the shuffle mask as if it were
5053 // the other case
5054 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5055   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5056   if (EltSz == 64)
5057     return false;
5058
5059   unsigned NumElts = VT.getVectorNumElements();
5060   if (M.size() != NumElts && M.size() != NumElts*2)
5061     return false;
5062
5063   // If the mask is twice as long as the input vector then we need to check the
5064   // upper and lower parts of the mask with a matching value for WhichResult
5065   // FIXME: A mask with only even values will be rejected in case the first
5066   // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
5067   // M[0] is used to determine WhichResult
5068   for (unsigned i = 0; i < M.size(); i += NumElts) {
5069     if (M.size() == NumElts * 2)
5070       WhichResult = i / NumElts;
5071     else
5072       WhichResult = M[i] == 0 ? 0 : 1;
5073     for (unsigned j = 0; j < NumElts; j += 2) {
5074       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5075           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
5076         return false;
5077     }
5078   }
5079
5080   if (M.size() == NumElts*2)
5081     WhichResult = 0;
5082
5083   return true;
5084 }
5085
5086 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
5087 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5088 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5089 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5090   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5091   if (EltSz == 64)
5092     return false;
5093
5094   unsigned NumElts = VT.getVectorNumElements();
5095   if (M.size() != NumElts && M.size() != NumElts*2)
5096     return false;
5097
5098   for (unsigned i = 0; i < M.size(); i += NumElts) {
5099     if (M.size() == NumElts * 2)
5100       WhichResult = i / NumElts;
5101     else
5102       WhichResult = M[i] == 0 ? 0 : 1;
5103     for (unsigned j = 0; j < NumElts; j += 2) {
5104       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5105           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
5106         return false;
5107     }
5108   }
5109
5110   if (M.size() == NumElts*2)
5111     WhichResult = 0;
5112
5113   return true;
5114 }
5115
5116 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
5117 // that the mask elements are either all even and in steps of size 2 or all odd
5118 // and in steps of size 2.
5119 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
5120 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
5121 //  v2={e,f,g,h}
5122 // Requires similar checks to that of isVTRNMask with
5123 // respect the how results are returned.
5124 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5125   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5126   if (EltSz == 64)
5127     return false;
5128
5129   unsigned NumElts = VT.getVectorNumElements();
5130   if (M.size() != NumElts && M.size() != NumElts*2)
5131     return false;
5132
5133   for (unsigned i = 0; i < M.size(); i += NumElts) {
5134     WhichResult = M[i] == 0 ? 0 : 1;
5135     for (unsigned j = 0; j < NumElts; ++j) {
5136       if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
5137         return false;
5138     }
5139   }
5140
5141   if (M.size() == NumElts*2)
5142     WhichResult = 0;
5143
5144   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5145   if (VT.is64BitVector() && EltSz == 32)
5146     return false;
5147
5148   return true;
5149 }
5150
5151 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
5152 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5153 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5154 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5155   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5156   if (EltSz == 64)
5157     return false;
5158
5159   unsigned NumElts = VT.getVectorNumElements();
5160   if (M.size() != NumElts && M.size() != NumElts*2)
5161     return false;
5162
5163   unsigned Half = NumElts / 2;
5164   for (unsigned i = 0; i < M.size(); i += NumElts) {
5165     WhichResult = M[i] == 0 ? 0 : 1;
5166     for (unsigned j = 0; j < NumElts; j += Half) {
5167       unsigned Idx = WhichResult;
5168       for (unsigned k = 0; k < Half; ++k) {
5169         int MIdx = M[i + j + k];
5170         if (MIdx >= 0 && (unsigned) MIdx != Idx)
5171           return false;
5172         Idx += 2;
5173       }
5174     }
5175   }
5176
5177   if (M.size() == NumElts*2)
5178     WhichResult = 0;
5179
5180   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5181   if (VT.is64BitVector() && EltSz == 32)
5182     return false;
5183
5184   return true;
5185 }
5186
5187 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
5188 // that pairs of elements of the shufflemask represent the same index in each
5189 // vector incrementing sequentially through the vectors.
5190 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
5191 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
5192 //  v2={e,f,g,h}
5193 // Requires similar checks to that of isVTRNMask with respect the how results
5194 // are returned.
5195 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5196   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5197   if (EltSz == 64)
5198     return false;
5199
5200   unsigned NumElts = VT.getVectorNumElements();
5201   if (M.size() != NumElts && M.size() != NumElts*2)
5202     return false;
5203
5204   for (unsigned i = 0; i < M.size(); i += NumElts) {
5205     WhichResult = M[i] == 0 ? 0 : 1;
5206     unsigned Idx = WhichResult * NumElts / 2;
5207     for (unsigned j = 0; j < NumElts; j += 2) {
5208       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5209           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
5210         return false;
5211       Idx += 1;
5212     }
5213   }
5214
5215   if (M.size() == NumElts*2)
5216     WhichResult = 0;
5217
5218   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5219   if (VT.is64BitVector() && EltSz == 32)
5220     return false;
5221
5222   return true;
5223 }
5224
5225 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5226 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5227 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5228 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5229   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5230   if (EltSz == 64)
5231     return false;
5232
5233   unsigned NumElts = VT.getVectorNumElements();
5234   if (M.size() != NumElts && M.size() != NumElts*2)
5235     return false;
5236
5237   for (unsigned i = 0; i < M.size(); i += NumElts) {
5238     WhichResult = M[i] == 0 ? 0 : 1;
5239     unsigned Idx = WhichResult * NumElts / 2;
5240     for (unsigned j = 0; j < NumElts; j += 2) {
5241       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5242           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
5243         return false;
5244       Idx += 1;
5245     }
5246   }
5247
5248   if (M.size() == NumElts*2)
5249     WhichResult = 0;
5250
5251   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5252   if (VT.is64BitVector() && EltSz == 32)
5253     return false;
5254
5255   return true;
5256 }
5257
5258 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
5259 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
5260 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
5261                                            unsigned &WhichResult,
5262                                            bool &isV_UNDEF) {
5263   isV_UNDEF = false;
5264   if (isVTRNMask(ShuffleMask, VT, WhichResult))
5265     return ARMISD::VTRN;
5266   if (isVUZPMask(ShuffleMask, VT, WhichResult))
5267     return ARMISD::VUZP;
5268   if (isVZIPMask(ShuffleMask, VT, WhichResult))
5269     return ARMISD::VZIP;
5270
5271   isV_UNDEF = true;
5272   if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5273     return ARMISD::VTRN;
5274   if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5275     return ARMISD::VUZP;
5276   if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5277     return ARMISD::VZIP;
5278
5279   return 0;
5280 }
5281
5282 /// \return true if this is a reverse operation on an vector.
5283 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5284   unsigned NumElts = VT.getVectorNumElements();
5285   // Make sure the mask has the right size.
5286   if (NumElts != M.size())
5287       return false;
5288
5289   // Look for <15, ..., 3, -1, 1, 0>.
5290   for (unsigned i = 0; i != NumElts; ++i)
5291     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5292       return false;
5293
5294   return true;
5295 }
5296
5297 // If N is an integer constant that can be moved into a register in one
5298 // instruction, return an SDValue of such a constant (will become a MOV
5299 // instruction).  Otherwise return null.
5300 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5301                                      const ARMSubtarget *ST, SDLoc dl) {
5302   uint64_t Val;
5303   if (!isa<ConstantSDNode>(N))
5304     return SDValue();
5305   Val = cast<ConstantSDNode>(N)->getZExtValue();
5306
5307   if (ST->isThumb1Only()) {
5308     if (Val <= 255 || ~Val <= 255)
5309       return DAG.getConstant(Val, dl, MVT::i32);
5310   } else {
5311     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5312       return DAG.getConstant(Val, dl, MVT::i32);
5313   }
5314   return SDValue();
5315 }
5316
5317 // If this is a case we can't handle, return null and let the default
5318 // expansion code take care of it.
5319 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5320                                              const ARMSubtarget *ST) const {
5321   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5322   SDLoc dl(Op);
5323   EVT VT = Op.getValueType();
5324
5325   APInt SplatBits, SplatUndef;
5326   unsigned SplatBitSize;
5327   bool HasAnyUndefs;
5328   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5329     if (SplatBitSize <= 64) {
5330       // Check if an immediate VMOV works.
5331       EVT VmovVT;
5332       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5333                                       SplatUndef.getZExtValue(), SplatBitSize,
5334                                       DAG, dl, VmovVT, VT.is128BitVector(),
5335                                       VMOVModImm);
5336       if (Val.getNode()) {
5337         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5338         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5339       }
5340
5341       // Try an immediate VMVN.
5342       uint64_t NegatedImm = (~SplatBits).getZExtValue();
5343       Val = isNEONModifiedImm(NegatedImm,
5344                                       SplatUndef.getZExtValue(), SplatBitSize,
5345                                       DAG, dl, VmovVT, VT.is128BitVector(),
5346                                       VMVNModImm);
5347       if (Val.getNode()) {
5348         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5349         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5350       }
5351
5352       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5353       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5354         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5355         if (ImmVal != -1) {
5356           SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
5357           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5358         }
5359       }
5360     }
5361   }
5362
5363   // Scan through the operands to see if only one value is used.
5364   //
5365   // As an optimisation, even if more than one value is used it may be more
5366   // profitable to splat with one value then change some lanes.
5367   //
5368   // Heuristically we decide to do this if the vector has a "dominant" value,
5369   // defined as splatted to more than half of the lanes.
5370   unsigned NumElts = VT.getVectorNumElements();
5371   bool isOnlyLowElement = true;
5372   bool usesOnlyOneValue = true;
5373   bool hasDominantValue = false;
5374   bool isConstant = true;
5375
5376   // Map of the number of times a particular SDValue appears in the
5377   // element list.
5378   DenseMap<SDValue, unsigned> ValueCounts;
5379   SDValue Value;
5380   for (unsigned i = 0; i < NumElts; ++i) {
5381     SDValue V = Op.getOperand(i);
5382     if (V.getOpcode() == ISD::UNDEF)
5383       continue;
5384     if (i > 0)
5385       isOnlyLowElement = false;
5386     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5387       isConstant = false;
5388
5389     ValueCounts.insert(std::make_pair(V, 0));
5390     unsigned &Count = ValueCounts[V];
5391
5392     // Is this value dominant? (takes up more than half of the lanes)
5393     if (++Count > (NumElts / 2)) {
5394       hasDominantValue = true;
5395       Value = V;
5396     }
5397   }
5398   if (ValueCounts.size() != 1)
5399     usesOnlyOneValue = false;
5400   if (!Value.getNode() && ValueCounts.size() > 0)
5401     Value = ValueCounts.begin()->first;
5402
5403   if (ValueCounts.size() == 0)
5404     return DAG.getUNDEF(VT);
5405
5406   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5407   // Keep going if we are hitting this case.
5408   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5409     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5410
5411   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5412
5413   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
5414   // i32 and try again.
5415   if (hasDominantValue && EltSize <= 32) {
5416     if (!isConstant) {
5417       SDValue N;
5418
5419       // If we are VDUPing a value that comes directly from a vector, that will
5420       // cause an unnecessary move to and from a GPR, where instead we could
5421       // just use VDUPLANE. We can only do this if the lane being extracted
5422       // is at a constant index, as the VDUP from lane instructions only have
5423       // constant-index forms.
5424       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5425           isa<ConstantSDNode>(Value->getOperand(1))) {
5426         // We need to create a new undef vector to use for the VDUPLANE if the
5427         // size of the vector from which we get the value is different than the
5428         // size of the vector that we need to create. We will insert the element
5429         // such that the register coalescer will remove unnecessary copies.
5430         if (VT != Value->getOperand(0).getValueType()) {
5431           ConstantSDNode *constIndex;
5432           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5433           assert(constIndex && "The index is not a constant!");
5434           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5435                              VT.getVectorNumElements();
5436           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5437                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5438                         Value, DAG.getConstant(index, dl, MVT::i32)),
5439                            DAG.getConstant(index, dl, MVT::i32));
5440         } else
5441           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5442                         Value->getOperand(0), Value->getOperand(1));
5443       } else
5444         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5445
5446       if (!usesOnlyOneValue) {
5447         // The dominant value was splatted as 'N', but we now have to insert
5448         // all differing elements.
5449         for (unsigned I = 0; I < NumElts; ++I) {
5450           if (Op.getOperand(I) == Value)
5451             continue;
5452           SmallVector<SDValue, 3> Ops;
5453           Ops.push_back(N);
5454           Ops.push_back(Op.getOperand(I));
5455           Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
5456           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5457         }
5458       }
5459       return N;
5460     }
5461     if (VT.getVectorElementType().isFloatingPoint()) {
5462       SmallVector<SDValue, 8> Ops;
5463       for (unsigned i = 0; i < NumElts; ++i)
5464         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5465                                   Op.getOperand(i)));
5466       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5467       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5468       Val = LowerBUILD_VECTOR(Val, DAG, ST);
5469       if (Val.getNode())
5470         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5471     }
5472     if (usesOnlyOneValue) {
5473       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5474       if (isConstant && Val.getNode())
5475         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5476     }
5477   }
5478
5479   // If all elements are constants and the case above didn't get hit, fall back
5480   // to the default expansion, which will generate a load from the constant
5481   // pool.
5482   if (isConstant)
5483     return SDValue();
5484
5485   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5486   if (NumElts >= 4) {
5487     SDValue shuffle = ReconstructShuffle(Op, DAG);
5488     if (shuffle != SDValue())
5489       return shuffle;
5490   }
5491
5492   // Vectors with 32- or 64-bit elements can be built by directly assigning
5493   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
5494   // will be legalized.
5495   if (EltSize >= 32) {
5496     // Do the expansion with floating-point types, since that is what the VFP
5497     // registers are defined to use, and since i64 is not legal.
5498     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5499     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5500     SmallVector<SDValue, 8> Ops;
5501     for (unsigned i = 0; i < NumElts; ++i)
5502       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5503     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5504     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5505   }
5506
5507   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5508   // know the default expansion would otherwise fall back on something even
5509   // worse. For a vector with one or two non-undef values, that's
5510   // scalar_to_vector for the elements followed by a shuffle (provided the
5511   // shuffle is valid for the target) and materialization element by element
5512   // on the stack followed by a load for everything else.
5513   if (!isConstant && !usesOnlyOneValue) {
5514     SDValue Vec = DAG.getUNDEF(VT);
5515     for (unsigned i = 0 ; i < NumElts; ++i) {
5516       SDValue V = Op.getOperand(i);
5517       if (V.getOpcode() == ISD::UNDEF)
5518         continue;
5519       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
5520       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5521     }
5522     return Vec;
5523   }
5524
5525   return SDValue();
5526 }
5527
5528 // Gather data to see if the operation can be modelled as a
5529 // shuffle in combination with VEXTs.
5530 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5531                                               SelectionDAG &DAG) const {
5532   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
5533   SDLoc dl(Op);
5534   EVT VT = Op.getValueType();
5535   unsigned NumElts = VT.getVectorNumElements();
5536
5537   struct ShuffleSourceInfo {
5538     SDValue Vec;
5539     unsigned MinElt;
5540     unsigned MaxElt;
5541
5542     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
5543     // be compatible with the shuffle we intend to construct. As a result
5544     // ShuffleVec will be some sliding window into the original Vec.
5545     SDValue ShuffleVec;
5546
5547     // Code should guarantee that element i in Vec starts at element "WindowBase
5548     // + i * WindowScale in ShuffleVec".
5549     int WindowBase;
5550     int WindowScale;
5551
5552     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
5553     ShuffleSourceInfo(SDValue Vec)
5554         : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
5555           WindowScale(1) {}
5556   };
5557
5558   // First gather all vectors used as an immediate source for this BUILD_VECTOR
5559   // node.
5560   SmallVector<ShuffleSourceInfo, 2> Sources;
5561   for (unsigned i = 0; i < NumElts; ++i) {
5562     SDValue V = Op.getOperand(i);
5563     if (V.getOpcode() == ISD::UNDEF)
5564       continue;
5565     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5566       // A shuffle can only come from building a vector from various
5567       // elements of other vectors.
5568       return SDValue();
5569     } else if (!isa<ConstantSDNode>(V.getOperand(1))) {
5570       // Furthermore, shuffles require a constant mask, whereas extractelts
5571       // accept variable indices.
5572       return SDValue();
5573     }
5574
5575     // Add this element source to the list if it's not already there.
5576     SDValue SourceVec = V.getOperand(0);
5577     auto Source = std::find(Sources.begin(), Sources.end(), SourceVec);
5578     if (Source == Sources.end())
5579       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
5580
5581     // Update the minimum and maximum lane number seen.
5582     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5583     Source->MinElt = std::min(Source->MinElt, EltNo);
5584     Source->MaxElt = std::max(Source->MaxElt, EltNo);
5585   }
5586
5587   // Currently only do something sane when at most two source vectors
5588   // are involved.
5589   if (Sources.size() > 2)
5590     return SDValue();
5591
5592   // Find out the smallest element size among result and two sources, and use
5593   // it as element size to build the shuffle_vector.
5594   EVT SmallestEltTy = VT.getVectorElementType();
5595   for (auto &Source : Sources) {
5596     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
5597     if (SrcEltTy.bitsLT(SmallestEltTy))
5598       SmallestEltTy = SrcEltTy;
5599   }
5600   unsigned ResMultiplier =
5601       VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
5602   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
5603   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
5604
5605   // If the source vector is too wide or too narrow, we may nevertheless be able
5606   // to construct a compatible shuffle either by concatenating it with UNDEF or
5607   // extracting a suitable range of elements.
5608   for (auto &Src : Sources) {
5609     EVT SrcVT = Src.ShuffleVec.getValueType();
5610
5611     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
5612       continue;
5613
5614     // This stage of the search produces a source with the same element type as
5615     // the original, but with a total width matching the BUILD_VECTOR output.
5616     EVT EltVT = SrcVT.getVectorElementType();
5617     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
5618     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
5619
5620     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
5621       if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
5622         return SDValue();
5623       // We can pad out the smaller vector for free, so if it's part of a
5624       // shuffle...
5625       Src.ShuffleVec =
5626           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
5627                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
5628       continue;
5629     }
5630
5631     if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
5632       return SDValue();
5633
5634     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
5635       // Span too large for a VEXT to cope
5636       return SDValue();
5637     }
5638
5639     if (Src.MinElt >= NumSrcElts) {
5640       // The extraction can just take the second half
5641       Src.ShuffleVec =
5642           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5643                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
5644       Src.WindowBase = -NumSrcElts;
5645     } else if (Src.MaxElt < NumSrcElts) {
5646       // The extraction can just take the first half
5647       Src.ShuffleVec =
5648           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5649                       DAG.getConstant(0, dl, MVT::i32));
5650     } else {
5651       // An actual VEXT is needed
5652       SDValue VEXTSrc1 =
5653           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5654                       DAG.getConstant(0, dl, MVT::i32));
5655       SDValue VEXTSrc2 =
5656           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5657                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
5658
5659       Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
5660                                    VEXTSrc2,
5661                                    DAG.getConstant(Src.MinElt, dl, MVT::i32));
5662       Src.WindowBase = -Src.MinElt;
5663     }
5664   }
5665
5666   // Another possible incompatibility occurs from the vector element types. We
5667   // can fix this by bitcasting the source vectors to the same type we intend
5668   // for the shuffle.
5669   for (auto &Src : Sources) {
5670     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
5671     if (SrcEltTy == SmallestEltTy)
5672       continue;
5673     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
5674     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
5675     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
5676     Src.WindowBase *= Src.WindowScale;
5677   }
5678
5679   // Final sanity check before we try to actually produce a shuffle.
5680   DEBUG(
5681     for (auto Src : Sources)
5682       assert(Src.ShuffleVec.getValueType() == ShuffleVT);
5683   );
5684
5685   // The stars all align, our next step is to produce the mask for the shuffle.
5686   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
5687   int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
5688   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
5689     SDValue Entry = Op.getOperand(i);
5690     if (Entry.getOpcode() == ISD::UNDEF)
5691       continue;
5692
5693     auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0));
5694     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
5695
5696     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
5697     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
5698     // segment.
5699     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
5700     int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
5701                                VT.getVectorElementType().getSizeInBits());
5702     int LanesDefined = BitsDefined / BitsPerShuffleLane;
5703
5704     // This source is expected to fill ResMultiplier lanes of the final shuffle,
5705     // starting at the appropriate offset.
5706     int *LaneMask = &Mask[i * ResMultiplier];
5707
5708     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
5709     ExtractBase += NumElts * (Src - Sources.begin());
5710     for (int j = 0; j < LanesDefined; ++j)
5711       LaneMask[j] = ExtractBase + j;
5712   }
5713
5714   // Final check before we try to produce nonsense...
5715   if (!isShuffleMaskLegal(Mask, ShuffleVT))
5716     return SDValue();
5717
5718   // We can't handle more than two sources. This should have already
5719   // been checked before this point.
5720   assert(Sources.size() <= 2 && "Too many sources!");
5721
5722   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
5723   for (unsigned i = 0; i < Sources.size(); ++i)
5724     ShuffleOps[i] = Sources[i].ShuffleVec;
5725
5726   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
5727                                          ShuffleOps[1], &Mask[0]);
5728   return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
5729 }
5730
5731 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5732 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5733 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5734 /// are assumed to be legal.
5735 bool
5736 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5737                                       EVT VT) const {
5738   if (VT.getVectorNumElements() == 4 &&
5739       (VT.is128BitVector() || VT.is64BitVector())) {
5740     unsigned PFIndexes[4];
5741     for (unsigned i = 0; i != 4; ++i) {
5742       if (M[i] < 0)
5743         PFIndexes[i] = 8;
5744       else
5745         PFIndexes[i] = M[i];
5746     }
5747
5748     // Compute the index in the perfect shuffle table.
5749     unsigned PFTableIndex =
5750       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5751     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5752     unsigned Cost = (PFEntry >> 30);
5753
5754     if (Cost <= 4)
5755       return true;
5756   }
5757
5758   bool ReverseVEXT, isV_UNDEF;
5759   unsigned Imm, WhichResult;
5760
5761   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5762   return (EltSize >= 32 ||
5763           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5764           isVREVMask(M, VT, 64) ||
5765           isVREVMask(M, VT, 32) ||
5766           isVREVMask(M, VT, 16) ||
5767           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5768           isVTBLMask(M, VT) ||
5769           isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) ||
5770           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5771 }
5772
5773 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5774 /// the specified operations to build the shuffle.
5775 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5776                                       SDValue RHS, SelectionDAG &DAG,
5777                                       SDLoc dl) {
5778   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5779   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5780   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5781
5782   enum {
5783     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5784     OP_VREV,
5785     OP_VDUP0,
5786     OP_VDUP1,
5787     OP_VDUP2,
5788     OP_VDUP3,
5789     OP_VEXT1,
5790     OP_VEXT2,
5791     OP_VEXT3,
5792     OP_VUZPL, // VUZP, left result
5793     OP_VUZPR, // VUZP, right result
5794     OP_VZIPL, // VZIP, left result
5795     OP_VZIPR, // VZIP, right result
5796     OP_VTRNL, // VTRN, left result
5797     OP_VTRNR  // VTRN, right result
5798   };
5799
5800   if (OpNum == OP_COPY) {
5801     if (LHSID == (1*9+2)*9+3) return LHS;
5802     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5803     return RHS;
5804   }
5805
5806   SDValue OpLHS, OpRHS;
5807   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5808   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5809   EVT VT = OpLHS.getValueType();
5810
5811   switch (OpNum) {
5812   default: llvm_unreachable("Unknown shuffle opcode!");
5813   case OP_VREV:
5814     // VREV divides the vector in half and swaps within the half.
5815     if (VT.getVectorElementType() == MVT::i32 ||
5816         VT.getVectorElementType() == MVT::f32)
5817       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5818     // vrev <4 x i16> -> VREV32
5819     if (VT.getVectorElementType() == MVT::i16)
5820       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5821     // vrev <4 x i8> -> VREV16
5822     assert(VT.getVectorElementType() == MVT::i8);
5823     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5824   case OP_VDUP0:
5825   case OP_VDUP1:
5826   case OP_VDUP2:
5827   case OP_VDUP3:
5828     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5829                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
5830   case OP_VEXT1:
5831   case OP_VEXT2:
5832   case OP_VEXT3:
5833     return DAG.getNode(ARMISD::VEXT, dl, VT,
5834                        OpLHS, OpRHS,
5835                        DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
5836   case OP_VUZPL:
5837   case OP_VUZPR:
5838     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5839                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5840   case OP_VZIPL:
5841   case OP_VZIPR:
5842     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5843                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5844   case OP_VTRNL:
5845   case OP_VTRNR:
5846     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5847                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5848   }
5849 }
5850
5851 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5852                                        ArrayRef<int> ShuffleMask,
5853                                        SelectionDAG &DAG) {
5854   // Check to see if we can use the VTBL instruction.
5855   SDValue V1 = Op.getOperand(0);
5856   SDValue V2 = Op.getOperand(1);
5857   SDLoc DL(Op);
5858
5859   SmallVector<SDValue, 8> VTBLMask;
5860   for (ArrayRef<int>::iterator
5861          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5862     VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
5863
5864   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5865     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5866                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5867
5868   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5869                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5870 }
5871
5872 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5873                                                       SelectionDAG &DAG) {
5874   SDLoc DL(Op);
5875   SDValue OpLHS = Op.getOperand(0);
5876   EVT VT = OpLHS.getValueType();
5877
5878   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5879          "Expect an v8i16/v16i8 type");
5880   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5881   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5882   // extract the first 8 bytes into the top double word and the last 8 bytes
5883   // into the bottom double word. The v8i16 case is similar.
5884   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5885   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5886                      DAG.getConstant(ExtractNum, DL, MVT::i32));
5887 }
5888
5889 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5890   SDValue V1 = Op.getOperand(0);
5891   SDValue V2 = Op.getOperand(1);
5892   SDLoc dl(Op);
5893   EVT VT = Op.getValueType();
5894   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5895
5896   // Convert shuffles that are directly supported on NEON to target-specific
5897   // DAG nodes, instead of keeping them as shuffles and matching them again
5898   // during code selection.  This is more efficient and avoids the possibility
5899   // of inconsistencies between legalization and selection.
5900   // FIXME: floating-point vectors should be canonicalized to integer vectors
5901   // of the same time so that they get CSEd properly.
5902   ArrayRef<int> ShuffleMask = SVN->getMask();
5903
5904   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5905   if (EltSize <= 32) {
5906     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5907       int Lane = SVN->getSplatIndex();
5908       // If this is undef splat, generate it via "just" vdup, if possible.
5909       if (Lane == -1) Lane = 0;
5910
5911       // Test if V1 is a SCALAR_TO_VECTOR.
5912       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5913         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5914       }
5915       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5916       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5917       // reaches it).
5918       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5919           !isa<ConstantSDNode>(V1.getOperand(0))) {
5920         bool IsScalarToVector = true;
5921         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5922           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5923             IsScalarToVector = false;
5924             break;
5925           }
5926         if (IsScalarToVector)
5927           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5928       }
5929       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5930                          DAG.getConstant(Lane, dl, MVT::i32));
5931     }
5932
5933     bool ReverseVEXT;
5934     unsigned Imm;
5935     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5936       if (ReverseVEXT)
5937         std::swap(V1, V2);
5938       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5939                          DAG.getConstant(Imm, dl, MVT::i32));
5940     }
5941
5942     if (isVREVMask(ShuffleMask, VT, 64))
5943       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5944     if (isVREVMask(ShuffleMask, VT, 32))
5945       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5946     if (isVREVMask(ShuffleMask, VT, 16))
5947       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5948
5949     if (V2->getOpcode() == ISD::UNDEF &&
5950         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5951       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5952                          DAG.getConstant(Imm, dl, MVT::i32));
5953     }
5954
5955     // Check for Neon shuffles that modify both input vectors in place.
5956     // If both results are used, i.e., if there are two shuffles with the same
5957     // source operands and with masks corresponding to both results of one of
5958     // these operations, DAG memoization will ensure that a single node is
5959     // used for both shuffles.
5960     unsigned WhichResult;
5961     bool isV_UNDEF;
5962     if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
5963             ShuffleMask, VT, WhichResult, isV_UNDEF)) {
5964       if (isV_UNDEF)
5965         V2 = V1;
5966       return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
5967           .getValue(WhichResult);
5968     }
5969
5970     // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
5971     // shuffles that produce a result larger than their operands with:
5972     //   shuffle(concat(v1, undef), concat(v2, undef))
5973     // ->
5974     //   shuffle(concat(v1, v2), undef)
5975     // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
5976     //
5977     // This is useful in the general case, but there are special cases where
5978     // native shuffles produce larger results: the two-result ops.
5979     //
5980     // Look through the concat when lowering them:
5981     //   shuffle(concat(v1, v2), undef)
5982     // ->
5983     //   concat(VZIP(v1, v2):0, :1)
5984     //
5985     if (V1->getOpcode() == ISD::CONCAT_VECTORS &&
5986         V2->getOpcode() == ISD::UNDEF) {
5987       SDValue SubV1 = V1->getOperand(0);
5988       SDValue SubV2 = V1->getOperand(1);
5989       EVT SubVT = SubV1.getValueType();
5990
5991       // We expect these to have been canonicalized to -1.
5992       assert(std::all_of(ShuffleMask.begin(), ShuffleMask.end(), [&](int i) {
5993         return i < (int)VT.getVectorNumElements();
5994       }) && "Unexpected shuffle index into UNDEF operand!");
5995
5996       if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
5997               ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
5998         if (isV_UNDEF)
5999           SubV2 = SubV1;
6000         assert((WhichResult == 0) &&
6001                "In-place shuffle of concat can only have one result!");
6002         SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
6003                                   SubV1, SubV2);
6004         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
6005                            Res.getValue(1));
6006       }
6007     }
6008   }
6009
6010   // If the shuffle is not directly supported and it has 4 elements, use
6011   // the PerfectShuffle-generated table to synthesize it from other shuffles.
6012   unsigned NumElts = VT.getVectorNumElements();
6013   if (NumElts == 4) {
6014     unsigned PFIndexes[4];
6015     for (unsigned i = 0; i != 4; ++i) {
6016       if (ShuffleMask[i] < 0)
6017         PFIndexes[i] = 8;
6018       else
6019         PFIndexes[i] = ShuffleMask[i];
6020     }
6021
6022     // Compute the index in the perfect shuffle table.
6023     unsigned PFTableIndex =
6024       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6025     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6026     unsigned Cost = (PFEntry >> 30);
6027
6028     if (Cost <= 4)
6029       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6030   }
6031
6032   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
6033   if (EltSize >= 32) {
6034     // Do the expansion with floating-point types, since that is what the VFP
6035     // registers are defined to use, and since i64 is not legal.
6036     EVT EltVT = EVT::getFloatingPointVT(EltSize);
6037     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6038     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
6039     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
6040     SmallVector<SDValue, 8> Ops;
6041     for (unsigned i = 0; i < NumElts; ++i) {
6042       if (ShuffleMask[i] < 0)
6043         Ops.push_back(DAG.getUNDEF(EltVT));
6044       else
6045         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6046                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
6047                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
6048                                                   dl, MVT::i32)));
6049     }
6050     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6051     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6052   }
6053
6054   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
6055     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
6056
6057   if (VT == MVT::v8i8) {
6058     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
6059     if (NewOp.getNode())
6060       return NewOp;
6061   }
6062
6063   return SDValue();
6064 }
6065
6066 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6067   // INSERT_VECTOR_ELT is legal only for immediate indexes.
6068   SDValue Lane = Op.getOperand(2);
6069   if (!isa<ConstantSDNode>(Lane))
6070     return SDValue();
6071
6072   return Op;
6073 }
6074
6075 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6076   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
6077   SDValue Lane = Op.getOperand(1);
6078   if (!isa<ConstantSDNode>(Lane))
6079     return SDValue();
6080
6081   SDValue Vec = Op.getOperand(0);
6082   if (Op.getValueType() == MVT::i32 &&
6083       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
6084     SDLoc dl(Op);
6085     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
6086   }
6087
6088   return Op;
6089 }
6090
6091 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6092   // The only time a CONCAT_VECTORS operation can have legal types is when
6093   // two 64-bit vectors are concatenated to a 128-bit vector.
6094   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
6095          "unexpected CONCAT_VECTORS");
6096   SDLoc dl(Op);
6097   SDValue Val = DAG.getUNDEF(MVT::v2f64);
6098   SDValue Op0 = Op.getOperand(0);
6099   SDValue Op1 = Op.getOperand(1);
6100   if (Op0.getOpcode() != ISD::UNDEF)
6101     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6102                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
6103                       DAG.getIntPtrConstant(0, dl));
6104   if (Op1.getOpcode() != ISD::UNDEF)
6105     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6106                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
6107                       DAG.getIntPtrConstant(1, dl));
6108   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
6109 }
6110
6111 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
6112 /// element has been zero/sign-extended, depending on the isSigned parameter,
6113 /// from an integer type half its size.
6114 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
6115                                    bool isSigned) {
6116   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
6117   EVT VT = N->getValueType(0);
6118   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
6119     SDNode *BVN = N->getOperand(0).getNode();
6120     if (BVN->getValueType(0) != MVT::v4i32 ||
6121         BVN->getOpcode() != ISD::BUILD_VECTOR)
6122       return false;
6123     unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6124     unsigned HiElt = 1 - LoElt;
6125     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
6126     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
6127     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
6128     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
6129     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
6130       return false;
6131     if (isSigned) {
6132       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
6133           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
6134         return true;
6135     } else {
6136       if (Hi0->isNullValue() && Hi1->isNullValue())
6137         return true;
6138     }
6139     return false;
6140   }
6141
6142   if (N->getOpcode() != ISD::BUILD_VECTOR)
6143     return false;
6144
6145   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
6146     SDNode *Elt = N->getOperand(i).getNode();
6147     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
6148       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6149       unsigned HalfSize = EltSize / 2;
6150       if (isSigned) {
6151         if (!isIntN(HalfSize, C->getSExtValue()))
6152           return false;
6153       } else {
6154         if (!isUIntN(HalfSize, C->getZExtValue()))
6155           return false;
6156       }
6157       continue;
6158     }
6159     return false;
6160   }
6161
6162   return true;
6163 }
6164
6165 /// isSignExtended - Check if a node is a vector value that is sign-extended
6166 /// or a constant BUILD_VECTOR with sign-extended elements.
6167 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
6168   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
6169     return true;
6170   if (isExtendedBUILD_VECTOR(N, DAG, true))
6171     return true;
6172   return false;
6173 }
6174
6175 /// isZeroExtended - Check if a node is a vector value that is zero-extended
6176 /// or a constant BUILD_VECTOR with zero-extended elements.
6177 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
6178   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
6179     return true;
6180   if (isExtendedBUILD_VECTOR(N, DAG, false))
6181     return true;
6182   return false;
6183 }
6184
6185 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
6186   if (OrigVT.getSizeInBits() >= 64)
6187     return OrigVT;
6188
6189   assert(OrigVT.isSimple() && "Expecting a simple value type");
6190
6191   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
6192   switch (OrigSimpleTy) {
6193   default: llvm_unreachable("Unexpected Vector Type");
6194   case MVT::v2i8:
6195   case MVT::v2i16:
6196      return MVT::v2i32;
6197   case MVT::v4i8:
6198     return  MVT::v4i16;
6199   }
6200 }
6201
6202 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
6203 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
6204 /// We insert the required extension here to get the vector to fill a D register.
6205 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
6206                                             const EVT &OrigTy,
6207                                             const EVT &ExtTy,
6208                                             unsigned ExtOpcode) {
6209   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
6210   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
6211   // 64-bits we need to insert a new extension so that it will be 64-bits.
6212   assert(ExtTy.is128BitVector() && "Unexpected extension size");
6213   if (OrigTy.getSizeInBits() >= 64)
6214     return N;
6215
6216   // Must extend size to at least 64 bits to be used as an operand for VMULL.
6217   EVT NewVT = getExtensionTo64Bits(OrigTy);
6218
6219   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
6220 }
6221
6222 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
6223 /// does not do any sign/zero extension. If the original vector is less
6224 /// than 64 bits, an appropriate extension will be added after the load to
6225 /// reach a total size of 64 bits. We have to add the extension separately
6226 /// because ARM does not have a sign/zero extending load for vectors.
6227 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
6228   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
6229
6230   // The load already has the right type.
6231   if (ExtendedTy == LD->getMemoryVT())
6232     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
6233                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
6234                 LD->isNonTemporal(), LD->isInvariant(),
6235                 LD->getAlignment());
6236
6237   // We need to create a zextload/sextload. We cannot just create a load
6238   // followed by a zext/zext node because LowerMUL is also run during normal
6239   // operation legalization where we can't create illegal types.
6240   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
6241                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
6242                         LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
6243                         LD->isNonTemporal(), LD->getAlignment());
6244 }
6245
6246 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
6247 /// extending load, or BUILD_VECTOR with extended elements, return the
6248 /// unextended value. The unextended vector should be 64 bits so that it can
6249 /// be used as an operand to a VMULL instruction. If the original vector size
6250 /// before extension is less than 64 bits we add a an extension to resize
6251 /// the vector to 64 bits.
6252 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
6253   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
6254     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
6255                                         N->getOperand(0)->getValueType(0),
6256                                         N->getValueType(0),
6257                                         N->getOpcode());
6258
6259   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
6260     return SkipLoadExtensionForVMULL(LD, DAG);
6261
6262   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
6263   // have been legalized as a BITCAST from v4i32.
6264   if (N->getOpcode() == ISD::BITCAST) {
6265     SDNode *BVN = N->getOperand(0).getNode();
6266     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
6267            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
6268     unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6269     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
6270                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
6271   }
6272   // Construct a new BUILD_VECTOR with elements truncated to half the size.
6273   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
6274   EVT VT = N->getValueType(0);
6275   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
6276   unsigned NumElts = VT.getVectorNumElements();
6277   MVT TruncVT = MVT::getIntegerVT(EltSize);
6278   SmallVector<SDValue, 8> Ops;
6279   SDLoc dl(N);
6280   for (unsigned i = 0; i != NumElts; ++i) {
6281     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
6282     const APInt &CInt = C->getAPIntValue();
6283     // Element types smaller than 32 bits are not legal, so use i32 elements.
6284     // The values are implicitly truncated so sext vs. zext doesn't matter.
6285     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
6286   }
6287   return DAG.getNode(ISD::BUILD_VECTOR, dl,
6288                      MVT::getVectorVT(TruncVT, NumElts), Ops);
6289 }
6290
6291 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
6292   unsigned Opcode = N->getOpcode();
6293   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6294     SDNode *N0 = N->getOperand(0).getNode();
6295     SDNode *N1 = N->getOperand(1).getNode();
6296     return N0->hasOneUse() && N1->hasOneUse() &&
6297       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
6298   }
6299   return false;
6300 }
6301
6302 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
6303   unsigned Opcode = N->getOpcode();
6304   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6305     SDNode *N0 = N->getOperand(0).getNode();
6306     SDNode *N1 = N->getOperand(1).getNode();
6307     return N0->hasOneUse() && N1->hasOneUse() &&
6308       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
6309   }
6310   return false;
6311 }
6312
6313 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
6314   // Multiplications are only custom-lowered for 128-bit vectors so that
6315   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
6316   EVT VT = Op.getValueType();
6317   assert(VT.is128BitVector() && VT.isInteger() &&
6318          "unexpected type for custom-lowering ISD::MUL");
6319   SDNode *N0 = Op.getOperand(0).getNode();
6320   SDNode *N1 = Op.getOperand(1).getNode();
6321   unsigned NewOpc = 0;
6322   bool isMLA = false;
6323   bool isN0SExt = isSignExtended(N0, DAG);
6324   bool isN1SExt = isSignExtended(N1, DAG);
6325   if (isN0SExt && isN1SExt)
6326     NewOpc = ARMISD::VMULLs;
6327   else {
6328     bool isN0ZExt = isZeroExtended(N0, DAG);
6329     bool isN1ZExt = isZeroExtended(N1, DAG);
6330     if (isN0ZExt && isN1ZExt)
6331       NewOpc = ARMISD::VMULLu;
6332     else if (isN1SExt || isN1ZExt) {
6333       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
6334       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
6335       if (isN1SExt && isAddSubSExt(N0, DAG)) {
6336         NewOpc = ARMISD::VMULLs;
6337         isMLA = true;
6338       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
6339         NewOpc = ARMISD::VMULLu;
6340         isMLA = true;
6341       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
6342         std::swap(N0, N1);
6343         NewOpc = ARMISD::VMULLu;
6344         isMLA = true;
6345       }
6346     }
6347
6348     if (!NewOpc) {
6349       if (VT == MVT::v2i64)
6350         // Fall through to expand this.  It is not legal.
6351         return SDValue();
6352       else
6353         // Other vector multiplications are legal.
6354         return Op;
6355     }
6356   }
6357
6358   // Legalize to a VMULL instruction.
6359   SDLoc DL(Op);
6360   SDValue Op0;
6361   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
6362   if (!isMLA) {
6363     Op0 = SkipExtensionForVMULL(N0, DAG);
6364     assert(Op0.getValueType().is64BitVector() &&
6365            Op1.getValueType().is64BitVector() &&
6366            "unexpected types for extended operands to VMULL");
6367     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
6368   }
6369
6370   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
6371   // isel lowering to take advantage of no-stall back to back vmul + vmla.
6372   //   vmull q0, d4, d6
6373   //   vmlal q0, d5, d6
6374   // is faster than
6375   //   vaddl q0, d4, d5
6376   //   vmovl q1, d6
6377   //   vmul  q0, q0, q1
6378   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
6379   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
6380   EVT Op1VT = Op1.getValueType();
6381   return DAG.getNode(N0->getOpcode(), DL, VT,
6382                      DAG.getNode(NewOpc, DL, VT,
6383                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
6384                      DAG.getNode(NewOpc, DL, VT,
6385                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
6386 }
6387
6388 static SDValue
6389 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
6390   // TODO: Should this propagate fast-math-flags?
6391
6392   // Convert to float
6393   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
6394   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
6395   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
6396   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
6397   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
6398   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
6399   // Get reciprocal estimate.
6400   // float4 recip = vrecpeq_f32(yf);
6401   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6402                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6403                    Y);
6404   // Because char has a smaller range than uchar, we can actually get away
6405   // without any newton steps.  This requires that we use a weird bias
6406   // of 0xb000, however (again, this has been exhaustively tested).
6407   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
6408   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
6409   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
6410   Y = DAG.getConstant(0xb000, dl, MVT::i32);
6411   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
6412   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6413   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6414   // Convert back to short.
6415   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6416   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6417   return X;
6418 }
6419
6420 static SDValue
6421 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
6422   // TODO: Should this propagate fast-math-flags?
6423
6424   SDValue N2;
6425   // Convert to float.
6426   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6427   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6428   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6429   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6430   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6431   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6432
6433   // Use reciprocal estimate and one refinement step.
6434   // float4 recip = vrecpeq_f32(yf);
6435   // recip *= vrecpsq_f32(yf, recip);
6436   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6437                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6438                    N1);
6439   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6440                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6441                    N1, N2);
6442   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6443   // Because short has a smaller range than ushort, we can actually get away
6444   // with only a single newton step.  This requires that we use a weird bias
6445   // of 89, however (again, this has been exhaustively tested).
6446   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6447   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6448   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6449   N1 = DAG.getConstant(0x89, dl, MVT::i32);
6450   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6451   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6452   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6453   // Convert back to integer and return.
6454   // return vmovn_s32(vcvt_s32_f32(result));
6455   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6456   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6457   return N0;
6458 }
6459
6460 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6461   EVT VT = Op.getValueType();
6462   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6463          "unexpected type for custom-lowering ISD::SDIV");
6464
6465   SDLoc dl(Op);
6466   SDValue N0 = Op.getOperand(0);
6467   SDValue N1 = Op.getOperand(1);
6468   SDValue N2, N3;
6469
6470   if (VT == MVT::v8i8) {
6471     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6472     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6473
6474     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6475                      DAG.getIntPtrConstant(4, dl));
6476     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6477                      DAG.getIntPtrConstant(4, dl));
6478     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6479                      DAG.getIntPtrConstant(0, dl));
6480     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6481                      DAG.getIntPtrConstant(0, dl));
6482
6483     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6484     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6485
6486     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6487     N0 = LowerCONCAT_VECTORS(N0, DAG);
6488
6489     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6490     return N0;
6491   }
6492   return LowerSDIV_v4i16(N0, N1, dl, DAG);
6493 }
6494
6495 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6496   // TODO: Should this propagate fast-math-flags?
6497   EVT VT = Op.getValueType();
6498   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6499          "unexpected type for custom-lowering ISD::UDIV");
6500
6501   SDLoc dl(Op);
6502   SDValue N0 = Op.getOperand(0);
6503   SDValue N1 = Op.getOperand(1);
6504   SDValue N2, N3;
6505
6506   if (VT == MVT::v8i8) {
6507     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6508     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6509
6510     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6511                      DAG.getIntPtrConstant(4, dl));
6512     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6513                      DAG.getIntPtrConstant(4, dl));
6514     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6515                      DAG.getIntPtrConstant(0, dl));
6516     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6517                      DAG.getIntPtrConstant(0, dl));
6518
6519     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6520     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6521
6522     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6523     N0 = LowerCONCAT_VECTORS(N0, DAG);
6524
6525     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6526                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
6527                                      MVT::i32),
6528                      N0);
6529     return N0;
6530   }
6531
6532   // v4i16 sdiv ... Convert to float.
6533   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6534   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6535   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6536   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6537   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6538   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6539
6540   // Use reciprocal estimate and two refinement steps.
6541   // float4 recip = vrecpeq_f32(yf);
6542   // recip *= vrecpsq_f32(yf, recip);
6543   // recip *= vrecpsq_f32(yf, recip);
6544   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6545                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6546                    BN1);
6547   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6548                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6549                    BN1, N2);
6550   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6551   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6552                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6553                    BN1, N2);
6554   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6555   // Simply multiplying by the reciprocal estimate can leave us a few ulps
6556   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6557   // and that it will never cause us to return an answer too large).
6558   // float4 result = as_float4(as_int4(xf*recip) + 2);
6559   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6560   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6561   N1 = DAG.getConstant(2, dl, MVT::i32);
6562   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6563   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6564   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6565   // Convert back to integer and return.
6566   // return vmovn_u32(vcvt_s32_f32(result));
6567   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6568   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6569   return N0;
6570 }
6571
6572 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6573   EVT VT = Op.getNode()->getValueType(0);
6574   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6575
6576   unsigned Opc;
6577   bool ExtraOp = false;
6578   switch (Op.getOpcode()) {
6579   default: llvm_unreachable("Invalid code");
6580   case ISD::ADDC: Opc = ARMISD::ADDC; break;
6581   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6582   case ISD::SUBC: Opc = ARMISD::SUBC; break;
6583   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6584   }
6585
6586   if (!ExtraOp)
6587     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6588                        Op.getOperand(1));
6589   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6590                      Op.getOperand(1), Op.getOperand(2));
6591 }
6592
6593 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6594   assert(Subtarget->isTargetDarwin());
6595
6596   // For iOS, we want to call an alternative entry point: __sincos_stret,
6597   // return values are passed via sret.
6598   SDLoc dl(Op);
6599   SDValue Arg = Op.getOperand(0);
6600   EVT ArgVT = Arg.getValueType();
6601   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6602   auto PtrVT = getPointerTy(DAG.getDataLayout());
6603
6604   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6605   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6606
6607   // Pair of floats / doubles used to pass the result.
6608   Type *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
6609   auto &DL = DAG.getDataLayout();
6610
6611   ArgListTy Args;
6612   bool ShouldUseSRet = Subtarget->isAPCS_ABI();
6613   SDValue SRet;
6614   if (ShouldUseSRet) {
6615     // Create stack object for sret.
6616     const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
6617     const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
6618     int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6619     SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL));
6620
6621     ArgListEntry Entry;
6622     Entry.Node = SRet;
6623     Entry.Ty = RetTy->getPointerTo();
6624     Entry.isSExt = false;
6625     Entry.isZExt = false;
6626     Entry.isSRet = true;
6627     Args.push_back(Entry);
6628     RetTy = Type::getVoidTy(*DAG.getContext());
6629   }
6630
6631   ArgListEntry Entry;
6632   Entry.Node = Arg;
6633   Entry.Ty = ArgTy;
6634   Entry.isSExt = false;
6635   Entry.isZExt = false;
6636   Args.push_back(Entry);
6637
6638   const char *LibcallName =
6639       (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
6640   RTLIB::Libcall LC =
6641       (ArgVT == MVT::f64) ? RTLIB::SINCOS_F64 : RTLIB::SINCOS_F32;
6642   CallingConv::ID CC = getLibcallCallingConv(LC);
6643   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
6644
6645   TargetLowering::CallLoweringInfo CLI(DAG);
6646   CLI.setDebugLoc(dl)
6647       .setChain(DAG.getEntryNode())
6648       .setCallee(CC, RetTy, Callee, std::move(Args), 0)
6649       .setDiscardResult(ShouldUseSRet);
6650   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6651
6652   if (!ShouldUseSRet)
6653     return CallResult.first;
6654
6655   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6656                                 MachinePointerInfo(), false, false, false, 0);
6657
6658   // Address of cos field.
6659   SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
6660                             DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
6661   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6662                                 MachinePointerInfo(), false, false, false, 0);
6663
6664   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6665   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6666                      LoadSin.getValue(0), LoadCos.getValue(0));
6667 }
6668
6669 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
6670                                                   bool Signed,
6671                                                   SDValue &Chain) const {
6672   EVT VT = Op.getValueType();
6673   assert((VT == MVT::i32 || VT == MVT::i64) &&
6674          "unexpected type for custom lowering DIV");
6675   SDLoc dl(Op);
6676
6677   const auto &DL = DAG.getDataLayout();
6678   const auto &TLI = DAG.getTargetLoweringInfo();
6679
6680   const char *Name = nullptr;
6681   if (Signed)
6682     Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64";
6683   else
6684     Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64";
6685
6686   SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL));
6687
6688   ARMTargetLowering::ArgListTy Args;
6689
6690   for (auto AI : {1, 0}) {
6691     ArgListEntry Arg;
6692     Arg.Node = Op.getOperand(AI);
6693     Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext());
6694     Args.push_back(Arg);
6695   }
6696
6697   CallLoweringInfo CLI(DAG);
6698   CLI.setDebugLoc(dl)
6699     .setChain(Chain)
6700     .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()),
6701                ES, std::move(Args), 0);
6702
6703   return LowerCallTo(CLI).first;
6704 }
6705
6706 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG,
6707                                             bool Signed) const {
6708   assert(Op.getValueType() == MVT::i32 &&
6709          "unexpected type for custom lowering DIV");
6710   SDLoc dl(Op);
6711
6712   SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other,
6713                                DAG.getEntryNode(), Op.getOperand(1));
6714
6715   return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
6716 }
6717
6718 void ARMTargetLowering::ExpandDIV_Windows(
6719     SDValue Op, SelectionDAG &DAG, bool Signed,
6720     SmallVectorImpl<SDValue> &Results) const {
6721   const auto &DL = DAG.getDataLayout();
6722   const auto &TLI = DAG.getTargetLoweringInfo();
6723
6724   assert(Op.getValueType() == MVT::i64 &&
6725          "unexpected type for custom lowering DIV");
6726   SDLoc dl(Op);
6727
6728   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op.getOperand(1),
6729                            DAG.getConstant(0, dl, MVT::i32));
6730   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op.getOperand(1),
6731                            DAG.getConstant(1, dl, MVT::i32));
6732   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i32, Lo, Hi);
6733
6734   SDValue DBZCHK =
6735       DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, DAG.getEntryNode(), Or);
6736
6737   SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
6738
6739   SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result);
6740   SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result,
6741                               DAG.getConstant(32, dl, TLI.getPointerTy(DL)));
6742   Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper);
6743
6744   Results.push_back(Lower);
6745   Results.push_back(Upper);
6746 }
6747
6748 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6749   // Monotonic load/store is legal for all targets
6750   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6751     return Op;
6752
6753   // Acquire/Release load/store is not legal for targets without a
6754   // dmb or equivalent available.
6755   return SDValue();
6756 }
6757
6758 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6759                                     SmallVectorImpl<SDValue> &Results,
6760                                     SelectionDAG &DAG,
6761                                     const ARMSubtarget *Subtarget) {
6762   SDLoc DL(N);
6763   // Under Power Management extensions, the cycle-count is:
6764   //    mrc p15, #0, <Rt>, c9, c13, #0
6765   SDValue Ops[] = { N->getOperand(0), // Chain
6766                     DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
6767                     DAG.getConstant(15, DL, MVT::i32),
6768                     DAG.getConstant(0, DL, MVT::i32),
6769                     DAG.getConstant(9, DL, MVT::i32),
6770                     DAG.getConstant(13, DL, MVT::i32),
6771                     DAG.getConstant(0, DL, MVT::i32)
6772   };
6773
6774   SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6775                                  DAG.getVTList(MVT::i32, MVT::Other), Ops);
6776   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32,
6777                                 DAG.getConstant(0, DL, MVT::i32)));
6778   Results.push_back(Cycles32.getValue(1));
6779 }
6780
6781 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6782   switch (Op.getOpcode()) {
6783   default: llvm_unreachable("Don't know how to custom lower this!");
6784   case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
6785   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6786   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6787   case ISD::GlobalAddress:
6788     switch (Subtarget->getTargetTriple().getObjectFormat()) {
6789     default: llvm_unreachable("unknown object format");
6790     case Triple::COFF:
6791       return LowerGlobalAddressWindows(Op, DAG);
6792     case Triple::ELF:
6793       return LowerGlobalAddressELF(Op, DAG);
6794     case Triple::MachO:
6795       return LowerGlobalAddressDarwin(Op, DAG);
6796     }
6797   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6798   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6799   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6800   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6801   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6802   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6803   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6804   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6805   case ISD::SINT_TO_FP:
6806   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6807   case ISD::FP_TO_SINT:
6808   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6809   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6810   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6811   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6812   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6813   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6814   case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
6815   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6816                                                                Subtarget);
6817   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6818   case ISD::SHL:
6819   case ISD::SRL:
6820   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6821   case ISD::SREM:          return LowerREM(Op.getNode(), DAG);
6822   case ISD::UREM:          return LowerREM(Op.getNode(), DAG);
6823   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6824   case ISD::SRL_PARTS:
6825   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6826   case ISD::CTTZ:
6827   case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6828   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6829   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6830   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6831   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6832   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6833   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6834   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6835   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6836   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6837   case ISD::MUL:           return LowerMUL(Op, DAG);
6838   case ISD::SDIV:
6839     if (Subtarget->isTargetWindows())
6840       return LowerDIV_Windows(Op, DAG, /* Signed */ true);
6841     return LowerSDIV(Op, DAG);
6842   case ISD::UDIV:
6843     if (Subtarget->isTargetWindows())
6844       return LowerDIV_Windows(Op, DAG, /* Signed */ false);
6845     return LowerUDIV(Op, DAG);
6846   case ISD::ADDC:
6847   case ISD::ADDE:
6848   case ISD::SUBC:
6849   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6850   case ISD::SADDO:
6851   case ISD::UADDO:
6852   case ISD::SSUBO:
6853   case ISD::USUBO:
6854     return LowerXALUO(Op, DAG);
6855   case ISD::ATOMIC_LOAD:
6856   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6857   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6858   case ISD::SDIVREM:
6859   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6860   case ISD::DYNAMIC_STACKALLOC:
6861     if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6862       return LowerDYNAMIC_STACKALLOC(Op, DAG);
6863     llvm_unreachable("Don't know how to custom lower this!");
6864   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6865   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6866   case ARMISD::WIN__DBZCHK: return SDValue();
6867   }
6868 }
6869
6870 /// ReplaceNodeResults - Replace the results of node with an illegal result
6871 /// type with new values built out of custom code.
6872 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6873                                            SmallVectorImpl<SDValue> &Results,
6874                                            SelectionDAG &DAG) const {
6875   SDValue Res;
6876   switch (N->getOpcode()) {
6877   default:
6878     llvm_unreachable("Don't know how to custom expand this!");
6879   case ISD::READ_REGISTER:
6880     ExpandREAD_REGISTER(N, Results, DAG);
6881     break;
6882   case ISD::BITCAST:
6883     Res = ExpandBITCAST(N, DAG);
6884     break;
6885   case ISD::SRL:
6886   case ISD::SRA:
6887     Res = Expand64BitShift(N, DAG, Subtarget);
6888     break;
6889   case ISD::SREM:
6890   case ISD::UREM:
6891     Res = LowerREM(N, DAG);
6892     break;
6893   case ISD::READCYCLECOUNTER:
6894     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6895     return;
6896   case ISD::UDIV:
6897   case ISD::SDIV:
6898     assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows");
6899     return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV,
6900                              Results);
6901   }
6902   if (Res.getNode())
6903     Results.push_back(Res);
6904 }
6905
6906 //===----------------------------------------------------------------------===//
6907 //                           ARM Scheduler Hooks
6908 //===----------------------------------------------------------------------===//
6909
6910 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6911 /// registers the function context.
6912 void ARMTargetLowering::
6913 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6914                        MachineBasicBlock *DispatchBB, int FI) const {
6915   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6916   DebugLoc dl = MI->getDebugLoc();
6917   MachineFunction *MF = MBB->getParent();
6918   MachineRegisterInfo *MRI = &MF->getRegInfo();
6919   MachineConstantPool *MCP = MF->getConstantPool();
6920   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6921   const Function *F = MF->getFunction();
6922
6923   bool isThumb = Subtarget->isThumb();
6924   bool isThumb2 = Subtarget->isThumb2();
6925
6926   unsigned PCLabelId = AFI->createPICLabelUId();
6927   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6928   ARMConstantPoolValue *CPV =
6929     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6930   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6931
6932   const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
6933                                            : &ARM::GPRRegClass;
6934
6935   // Grab constant pool and fixed stack memory operands.
6936   MachineMemOperand *CPMMO =
6937       MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
6938                                MachineMemOperand::MOLoad, 4, 4);
6939
6940   MachineMemOperand *FIMMOSt =
6941       MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
6942                                MachineMemOperand::MOStore, 4, 4);
6943
6944   // Load the address of the dispatch MBB into the jump buffer.
6945   if (isThumb2) {
6946     // Incoming value: jbuf
6947     //   ldr.n  r5, LCPI1_1
6948     //   orr    r5, r5, #1
6949     //   add    r5, pc
6950     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6951     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6952     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6953                    .addConstantPoolIndex(CPI)
6954                    .addMemOperand(CPMMO));
6955     // Set the low bit because of thumb mode.
6956     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6957     AddDefaultCC(
6958       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6959                      .addReg(NewVReg1, RegState::Kill)
6960                      .addImm(0x01)));
6961     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6962     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6963       .addReg(NewVReg2, RegState::Kill)
6964       .addImm(PCLabelId);
6965     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6966                    .addReg(NewVReg3, RegState::Kill)
6967                    .addFrameIndex(FI)
6968                    .addImm(36)  // &jbuf[1] :: pc
6969                    .addMemOperand(FIMMOSt));
6970   } else if (isThumb) {
6971     // Incoming value: jbuf
6972     //   ldr.n  r1, LCPI1_4
6973     //   add    r1, pc
6974     //   mov    r2, #1
6975     //   orrs   r1, r2
6976     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6977     //   str    r1, [r2]
6978     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6979     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6980                    .addConstantPoolIndex(CPI)
6981                    .addMemOperand(CPMMO));
6982     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6983     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6984       .addReg(NewVReg1, RegState::Kill)
6985       .addImm(PCLabelId);
6986     // Set the low bit because of thumb mode.
6987     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6988     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6989                    .addReg(ARM::CPSR, RegState::Define)
6990                    .addImm(1));
6991     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6992     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6993                    .addReg(ARM::CPSR, RegState::Define)
6994                    .addReg(NewVReg2, RegState::Kill)
6995                    .addReg(NewVReg3, RegState::Kill));
6996     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6997     BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
6998             .addFrameIndex(FI)
6999             .addImm(36); // &jbuf[1] :: pc
7000     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
7001                    .addReg(NewVReg4, RegState::Kill)
7002                    .addReg(NewVReg5, RegState::Kill)
7003                    .addImm(0)
7004                    .addMemOperand(FIMMOSt));
7005   } else {
7006     // Incoming value: jbuf
7007     //   ldr  r1, LCPI1_1
7008     //   add  r1, pc, r1
7009     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
7010     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7011     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
7012                    .addConstantPoolIndex(CPI)
7013                    .addImm(0)
7014                    .addMemOperand(CPMMO));
7015     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7016     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
7017                    .addReg(NewVReg1, RegState::Kill)
7018                    .addImm(PCLabelId));
7019     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
7020                    .addReg(NewVReg2, RegState::Kill)
7021                    .addFrameIndex(FI)
7022                    .addImm(36)  // &jbuf[1] :: pc
7023                    .addMemOperand(FIMMOSt));
7024   }
7025 }
7026
7027 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr *MI,
7028                                               MachineBasicBlock *MBB) const {
7029   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7030   DebugLoc dl = MI->getDebugLoc();
7031   MachineFunction *MF = MBB->getParent();
7032   MachineRegisterInfo *MRI = &MF->getRegInfo();
7033   MachineFrameInfo *MFI = MF->getFrameInfo();
7034   int FI = MFI->getFunctionContextIndex();
7035
7036   const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
7037                                                         : &ARM::GPRnopcRegClass;
7038
7039   // Get a mapping of the call site numbers to all of the landing pads they're
7040   // associated with.
7041   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
7042   unsigned MaxCSNum = 0;
7043   MachineModuleInfo &MMI = MF->getMMI();
7044   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
7045        ++BB) {
7046     if (!BB->isEHPad()) continue;
7047
7048     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
7049     // pad.
7050     for (MachineBasicBlock::iterator
7051            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
7052       if (!II->isEHLabel()) continue;
7053
7054       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
7055       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
7056
7057       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
7058       for (SmallVectorImpl<unsigned>::iterator
7059              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
7060            CSI != CSE; ++CSI) {
7061         CallSiteNumToLPad[*CSI].push_back(&*BB);
7062         MaxCSNum = std::max(MaxCSNum, *CSI);
7063       }
7064       break;
7065     }
7066   }
7067
7068   // Get an ordered list of the machine basic blocks for the jump table.
7069   std::vector<MachineBasicBlock*> LPadList;
7070   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
7071   LPadList.reserve(CallSiteNumToLPad.size());
7072   for (unsigned I = 1; I <= MaxCSNum; ++I) {
7073     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
7074     for (SmallVectorImpl<MachineBasicBlock*>::iterator
7075            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
7076       LPadList.push_back(*II);
7077       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
7078     }
7079   }
7080
7081   assert(!LPadList.empty() &&
7082          "No landing pad destinations for the dispatch jump table!");
7083
7084   // Create the jump table and associated information.
7085   MachineJumpTableInfo *JTI =
7086     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
7087   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
7088   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
7089
7090   // Create the MBBs for the dispatch code.
7091
7092   // Shove the dispatch's address into the return slot in the function context.
7093   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
7094   DispatchBB->setIsEHPad();
7095
7096   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
7097   unsigned trap_opcode;
7098   if (Subtarget->isThumb())
7099     trap_opcode = ARM::tTRAP;
7100   else
7101     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
7102
7103   BuildMI(TrapBB, dl, TII->get(trap_opcode));
7104   DispatchBB->addSuccessor(TrapBB);
7105
7106   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
7107   DispatchBB->addSuccessor(DispContBB);
7108
7109   // Insert and MBBs.
7110   MF->insert(MF->end(), DispatchBB);
7111   MF->insert(MF->end(), DispContBB);
7112   MF->insert(MF->end(), TrapBB);
7113
7114   // Insert code into the entry block that creates and registers the function
7115   // context.
7116   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
7117
7118   MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
7119       MachinePointerInfo::getFixedStack(*MF, FI),
7120       MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4);
7121
7122   MachineInstrBuilder MIB;
7123   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
7124
7125   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
7126   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
7127
7128   // Add a register mask with no preserved registers.  This results in all
7129   // registers being marked as clobbered.
7130   MIB.addRegMask(RI.getNoPreservedMask());
7131
7132   unsigned NumLPads = LPadList.size();
7133   if (Subtarget->isThumb2()) {
7134     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7135     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
7136                    .addFrameIndex(FI)
7137                    .addImm(4)
7138                    .addMemOperand(FIMMOLd));
7139
7140     if (NumLPads < 256) {
7141       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
7142                      .addReg(NewVReg1)
7143                      .addImm(LPadList.size()));
7144     } else {
7145       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7146       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
7147                      .addImm(NumLPads & 0xFFFF));
7148
7149       unsigned VReg2 = VReg1;
7150       if ((NumLPads & 0xFFFF0000) != 0) {
7151         VReg2 = MRI->createVirtualRegister(TRC);
7152         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
7153                        .addReg(VReg1)
7154                        .addImm(NumLPads >> 16));
7155       }
7156
7157       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
7158                      .addReg(NewVReg1)
7159                      .addReg(VReg2));
7160     }
7161
7162     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
7163       .addMBB(TrapBB)
7164       .addImm(ARMCC::HI)
7165       .addReg(ARM::CPSR);
7166
7167     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7168     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
7169                    .addJumpTableIndex(MJTI));
7170
7171     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7172     AddDefaultCC(
7173       AddDefaultPred(
7174         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
7175         .addReg(NewVReg3, RegState::Kill)
7176         .addReg(NewVReg1)
7177         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7178
7179     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
7180       .addReg(NewVReg4, RegState::Kill)
7181       .addReg(NewVReg1)
7182       .addJumpTableIndex(MJTI);
7183   } else if (Subtarget->isThumb()) {
7184     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7185     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
7186                    .addFrameIndex(FI)
7187                    .addImm(1)
7188                    .addMemOperand(FIMMOLd));
7189
7190     if (NumLPads < 256) {
7191       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
7192                      .addReg(NewVReg1)
7193                      .addImm(NumLPads));
7194     } else {
7195       MachineConstantPool *ConstantPool = MF->getConstantPool();
7196       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7197       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7198
7199       // MachineConstantPool wants an explicit alignment.
7200       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7201       if (Align == 0)
7202         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7203       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7204
7205       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7206       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
7207                      .addReg(VReg1, RegState::Define)
7208                      .addConstantPoolIndex(Idx));
7209       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
7210                      .addReg(NewVReg1)
7211                      .addReg(VReg1));
7212     }
7213
7214     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
7215       .addMBB(TrapBB)
7216       .addImm(ARMCC::HI)
7217       .addReg(ARM::CPSR);
7218
7219     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7220     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
7221                    .addReg(ARM::CPSR, RegState::Define)
7222                    .addReg(NewVReg1)
7223                    .addImm(2));
7224
7225     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7226     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
7227                    .addJumpTableIndex(MJTI));
7228
7229     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7230     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
7231                    .addReg(ARM::CPSR, RegState::Define)
7232                    .addReg(NewVReg2, RegState::Kill)
7233                    .addReg(NewVReg3));
7234
7235     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
7236         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
7237
7238     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7239     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
7240                    .addReg(NewVReg4, RegState::Kill)
7241                    .addImm(0)
7242                    .addMemOperand(JTMMOLd));
7243
7244     unsigned NewVReg6 = NewVReg5;
7245     if (RelocM == Reloc::PIC_) {
7246       NewVReg6 = MRI->createVirtualRegister(TRC);
7247       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
7248                      .addReg(ARM::CPSR, RegState::Define)
7249                      .addReg(NewVReg5, RegState::Kill)
7250                      .addReg(NewVReg3));
7251     }
7252
7253     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
7254       .addReg(NewVReg6, RegState::Kill)
7255       .addJumpTableIndex(MJTI);
7256   } else {
7257     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7258     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
7259                    .addFrameIndex(FI)
7260                    .addImm(4)
7261                    .addMemOperand(FIMMOLd));
7262
7263     if (NumLPads < 256) {
7264       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
7265                      .addReg(NewVReg1)
7266                      .addImm(NumLPads));
7267     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
7268       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7269       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
7270                      .addImm(NumLPads & 0xFFFF));
7271
7272       unsigned VReg2 = VReg1;
7273       if ((NumLPads & 0xFFFF0000) != 0) {
7274         VReg2 = MRI->createVirtualRegister(TRC);
7275         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
7276                        .addReg(VReg1)
7277                        .addImm(NumLPads >> 16));
7278       }
7279
7280       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7281                      .addReg(NewVReg1)
7282                      .addReg(VReg2));
7283     } else {
7284       MachineConstantPool *ConstantPool = MF->getConstantPool();
7285       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7286       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7287
7288       // MachineConstantPool wants an explicit alignment.
7289       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7290       if (Align == 0)
7291         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7292       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7293
7294       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7295       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
7296                      .addReg(VReg1, RegState::Define)
7297                      .addConstantPoolIndex(Idx)
7298                      .addImm(0));
7299       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7300                      .addReg(NewVReg1)
7301                      .addReg(VReg1, RegState::Kill));
7302     }
7303
7304     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
7305       .addMBB(TrapBB)
7306       .addImm(ARMCC::HI)
7307       .addReg(ARM::CPSR);
7308
7309     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7310     AddDefaultCC(
7311       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
7312                      .addReg(NewVReg1)
7313                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7314     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7315     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
7316                    .addJumpTableIndex(MJTI));
7317
7318     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
7319         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
7320     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7321     AddDefaultPred(
7322       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
7323       .addReg(NewVReg3, RegState::Kill)
7324       .addReg(NewVReg4)
7325       .addImm(0)
7326       .addMemOperand(JTMMOLd));
7327
7328     if (RelocM == Reloc::PIC_) {
7329       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
7330         .addReg(NewVReg5, RegState::Kill)
7331         .addReg(NewVReg4)
7332         .addJumpTableIndex(MJTI);
7333     } else {
7334       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
7335         .addReg(NewVReg5, RegState::Kill)
7336         .addJumpTableIndex(MJTI);
7337     }
7338   }
7339
7340   // Add the jump table entries as successors to the MBB.
7341   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
7342   for (std::vector<MachineBasicBlock*>::iterator
7343          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
7344     MachineBasicBlock *CurMBB = *I;
7345     if (SeenMBBs.insert(CurMBB).second)
7346       DispContBB->addSuccessor(CurMBB);
7347   }
7348
7349   // N.B. the order the invoke BBs are processed in doesn't matter here.
7350   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
7351   SmallVector<MachineBasicBlock*, 64> MBBLPads;
7352   for (MachineBasicBlock *BB : InvokeBBs) {
7353
7354     // Remove the landing pad successor from the invoke block and replace it
7355     // with the new dispatch block.
7356     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
7357                                                   BB->succ_end());
7358     while (!Successors.empty()) {
7359       MachineBasicBlock *SMBB = Successors.pop_back_val();
7360       if (SMBB->isEHPad()) {
7361         BB->removeSuccessor(SMBB);
7362         MBBLPads.push_back(SMBB);
7363       }
7364     }
7365
7366     BB->addSuccessor(DispatchBB);
7367
7368     // Find the invoke call and mark all of the callee-saved registers as
7369     // 'implicit defined' so that they're spilled. This prevents code from
7370     // moving instructions to before the EH block, where they will never be
7371     // executed.
7372     for (MachineBasicBlock::reverse_iterator
7373            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
7374       if (!II->isCall()) continue;
7375
7376       DenseMap<unsigned, bool> DefRegs;
7377       for (MachineInstr::mop_iterator
7378              OI = II->operands_begin(), OE = II->operands_end();
7379            OI != OE; ++OI) {
7380         if (!OI->isReg()) continue;
7381         DefRegs[OI->getReg()] = true;
7382       }
7383
7384       MachineInstrBuilder MIB(*MF, &*II);
7385
7386       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
7387         unsigned Reg = SavedRegs[i];
7388         if (Subtarget->isThumb2() &&
7389             !ARM::tGPRRegClass.contains(Reg) &&
7390             !ARM::hGPRRegClass.contains(Reg))
7391           continue;
7392         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
7393           continue;
7394         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7395           continue;
7396         if (!DefRegs[Reg])
7397           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7398       }
7399
7400       break;
7401     }
7402   }
7403
7404   // Mark all former landing pads as non-landing pads. The dispatch is the only
7405   // landing pad now.
7406   for (SmallVectorImpl<MachineBasicBlock*>::iterator
7407          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7408     (*I)->setIsEHPad(false);
7409
7410   // The instruction is gone now.
7411   MI->eraseFromParent();
7412 }
7413
7414 static
7415 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7416   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7417        E = MBB->succ_end(); I != E; ++I)
7418     if (*I != Succ)
7419       return *I;
7420   llvm_unreachable("Expecting a BB with two successors!");
7421 }
7422
7423 /// Return the load opcode for a given load size. If load size >= 8,
7424 /// neon opcode will be returned.
7425 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7426   if (LdSize >= 8)
7427     return LdSize == 16 ? ARM::VLD1q32wb_fixed
7428                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7429   if (IsThumb1)
7430     return LdSize == 4 ? ARM::tLDRi
7431                        : LdSize == 2 ? ARM::tLDRHi
7432                                      : LdSize == 1 ? ARM::tLDRBi : 0;
7433   if (IsThumb2)
7434     return LdSize == 4 ? ARM::t2LDR_POST
7435                        : LdSize == 2 ? ARM::t2LDRH_POST
7436                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7437   return LdSize == 4 ? ARM::LDR_POST_IMM
7438                      : LdSize == 2 ? ARM::LDRH_POST
7439                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7440 }
7441
7442 /// Return the store opcode for a given store size. If store size >= 8,
7443 /// neon opcode will be returned.
7444 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7445   if (StSize >= 8)
7446     return StSize == 16 ? ARM::VST1q32wb_fixed
7447                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7448   if (IsThumb1)
7449     return StSize == 4 ? ARM::tSTRi
7450                        : StSize == 2 ? ARM::tSTRHi
7451                                      : StSize == 1 ? ARM::tSTRBi : 0;
7452   if (IsThumb2)
7453     return StSize == 4 ? ARM::t2STR_POST
7454                        : StSize == 2 ? ARM::t2STRH_POST
7455                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
7456   return StSize == 4 ? ARM::STR_POST_IMM
7457                      : StSize == 2 ? ARM::STRH_POST
7458                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7459 }
7460
7461 /// Emit a post-increment load operation with given size. The instructions
7462 /// will be added to BB at Pos.
7463 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7464                        const TargetInstrInfo *TII, DebugLoc dl,
7465                        unsigned LdSize, unsigned Data, unsigned AddrIn,
7466                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7467   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7468   assert(LdOpc != 0 && "Should have a load opcode");
7469   if (LdSize >= 8) {
7470     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7471                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7472                        .addImm(0));
7473   } else if (IsThumb1) {
7474     // load + update AddrIn
7475     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7476                        .addReg(AddrIn).addImm(0));
7477     MachineInstrBuilder MIB =
7478         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7479     MIB = AddDefaultT1CC(MIB);
7480     MIB.addReg(AddrIn).addImm(LdSize);
7481     AddDefaultPred(MIB);
7482   } else if (IsThumb2) {
7483     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7484                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7485                        .addImm(LdSize));
7486   } else { // arm
7487     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7488                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7489                        .addReg(0).addImm(LdSize));
7490   }
7491 }
7492
7493 /// Emit a post-increment store operation with given size. The instructions
7494 /// will be added to BB at Pos.
7495 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7496                        const TargetInstrInfo *TII, DebugLoc dl,
7497                        unsigned StSize, unsigned Data, unsigned AddrIn,
7498                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7499   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7500   assert(StOpc != 0 && "Should have a store opcode");
7501   if (StSize >= 8) {
7502     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7503                        .addReg(AddrIn).addImm(0).addReg(Data));
7504   } else if (IsThumb1) {
7505     // store + update AddrIn
7506     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7507                        .addReg(AddrIn).addImm(0));
7508     MachineInstrBuilder MIB =
7509         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7510     MIB = AddDefaultT1CC(MIB);
7511     MIB.addReg(AddrIn).addImm(StSize);
7512     AddDefaultPred(MIB);
7513   } else if (IsThumb2) {
7514     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7515                        .addReg(Data).addReg(AddrIn).addImm(StSize));
7516   } else { // arm
7517     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7518                        .addReg(Data).addReg(AddrIn).addReg(0)
7519                        .addImm(StSize));
7520   }
7521 }
7522
7523 MachineBasicBlock *
7524 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7525                                    MachineBasicBlock *BB) const {
7526   // This pseudo instruction has 3 operands: dst, src, size
7527   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7528   // Otherwise, we will generate unrolled scalar copies.
7529   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7530   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7531   MachineFunction::iterator It = ++BB->getIterator();
7532
7533   unsigned dest = MI->getOperand(0).getReg();
7534   unsigned src = MI->getOperand(1).getReg();
7535   unsigned SizeVal = MI->getOperand(2).getImm();
7536   unsigned Align = MI->getOperand(3).getImm();
7537   DebugLoc dl = MI->getDebugLoc();
7538
7539   MachineFunction *MF = BB->getParent();
7540   MachineRegisterInfo &MRI = MF->getRegInfo();
7541   unsigned UnitSize = 0;
7542   const TargetRegisterClass *TRC = nullptr;
7543   const TargetRegisterClass *VecTRC = nullptr;
7544
7545   bool IsThumb1 = Subtarget->isThumb1Only();
7546   bool IsThumb2 = Subtarget->isThumb2();
7547
7548   if (Align & 1) {
7549     UnitSize = 1;
7550   } else if (Align & 2) {
7551     UnitSize = 2;
7552   } else {
7553     // Check whether we can use NEON instructions.
7554     if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
7555         Subtarget->hasNEON()) {
7556       if ((Align % 16 == 0) && SizeVal >= 16)
7557         UnitSize = 16;
7558       else if ((Align % 8 == 0) && SizeVal >= 8)
7559         UnitSize = 8;
7560     }
7561     // Can't use NEON instructions.
7562     if (UnitSize == 0)
7563       UnitSize = 4;
7564   }
7565
7566   // Select the correct opcode and register class for unit size load/store
7567   bool IsNeon = UnitSize >= 8;
7568   TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
7569   if (IsNeon)
7570     VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
7571                             : UnitSize == 8 ? &ARM::DPRRegClass
7572                                             : nullptr;
7573
7574   unsigned BytesLeft = SizeVal % UnitSize;
7575   unsigned LoopSize = SizeVal - BytesLeft;
7576
7577   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7578     // Use LDR and STR to copy.
7579     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7580     // [destOut] = STR_POST(scratch, destIn, UnitSize)
7581     unsigned srcIn = src;
7582     unsigned destIn = dest;
7583     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7584       unsigned srcOut = MRI.createVirtualRegister(TRC);
7585       unsigned destOut = MRI.createVirtualRegister(TRC);
7586       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7587       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7588                  IsThumb1, IsThumb2);
7589       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7590                  IsThumb1, IsThumb2);
7591       srcIn = srcOut;
7592       destIn = destOut;
7593     }
7594
7595     // Handle the leftover bytes with LDRB and STRB.
7596     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7597     // [destOut] = STRB_POST(scratch, destIn, 1)
7598     for (unsigned i = 0; i < BytesLeft; i++) {
7599       unsigned srcOut = MRI.createVirtualRegister(TRC);
7600       unsigned destOut = MRI.createVirtualRegister(TRC);
7601       unsigned scratch = MRI.createVirtualRegister(TRC);
7602       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7603                  IsThumb1, IsThumb2);
7604       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7605                  IsThumb1, IsThumb2);
7606       srcIn = srcOut;
7607       destIn = destOut;
7608     }
7609     MI->eraseFromParent();   // The instruction is gone now.
7610     return BB;
7611   }
7612
7613   // Expand the pseudo op to a loop.
7614   // thisMBB:
7615   //   ...
7616   //   movw varEnd, # --> with thumb2
7617   //   movt varEnd, #
7618   //   ldrcp varEnd, idx --> without thumb2
7619   //   fallthrough --> loopMBB
7620   // loopMBB:
7621   //   PHI varPhi, varEnd, varLoop
7622   //   PHI srcPhi, src, srcLoop
7623   //   PHI destPhi, dst, destLoop
7624   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7625   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7626   //   subs varLoop, varPhi, #UnitSize
7627   //   bne loopMBB
7628   //   fallthrough --> exitMBB
7629   // exitMBB:
7630   //   epilogue to handle left-over bytes
7631   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7632   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7633   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7634   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7635   MF->insert(It, loopMBB);
7636   MF->insert(It, exitMBB);
7637
7638   // Transfer the remainder of BB and its successor edges to exitMBB.
7639   exitMBB->splice(exitMBB->begin(), BB,
7640                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7641   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7642
7643   // Load an immediate to varEnd.
7644   unsigned varEnd = MRI.createVirtualRegister(TRC);
7645   if (Subtarget->useMovt(*MF)) {
7646     unsigned Vtmp = varEnd;
7647     if ((LoopSize & 0xFFFF0000) != 0)
7648       Vtmp = MRI.createVirtualRegister(TRC);
7649     AddDefaultPred(BuildMI(BB, dl,
7650                            TII->get(IsThumb2 ? ARM::t2MOVi16 : ARM::MOVi16),
7651                            Vtmp).addImm(LoopSize & 0xFFFF));
7652
7653     if ((LoopSize & 0xFFFF0000) != 0)
7654       AddDefaultPred(BuildMI(BB, dl,
7655                              TII->get(IsThumb2 ? ARM::t2MOVTi16 : ARM::MOVTi16),
7656                              varEnd)
7657                          .addReg(Vtmp)
7658                          .addImm(LoopSize >> 16));
7659   } else {
7660     MachineConstantPool *ConstantPool = MF->getConstantPool();
7661     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7662     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7663
7664     // MachineConstantPool wants an explicit alignment.
7665     unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7666     if (Align == 0)
7667       Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7668     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7669
7670     if (IsThumb1)
7671       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7672           varEnd, RegState::Define).addConstantPoolIndex(Idx));
7673     else
7674       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7675           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7676   }
7677   BB->addSuccessor(loopMBB);
7678
7679   // Generate the loop body:
7680   //   varPhi = PHI(varLoop, varEnd)
7681   //   srcPhi = PHI(srcLoop, src)
7682   //   destPhi = PHI(destLoop, dst)
7683   MachineBasicBlock *entryBB = BB;
7684   BB = loopMBB;
7685   unsigned varLoop = MRI.createVirtualRegister(TRC);
7686   unsigned varPhi = MRI.createVirtualRegister(TRC);
7687   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7688   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7689   unsigned destLoop = MRI.createVirtualRegister(TRC);
7690   unsigned destPhi = MRI.createVirtualRegister(TRC);
7691
7692   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7693     .addReg(varLoop).addMBB(loopMBB)
7694     .addReg(varEnd).addMBB(entryBB);
7695   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7696     .addReg(srcLoop).addMBB(loopMBB)
7697     .addReg(src).addMBB(entryBB);
7698   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7699     .addReg(destLoop).addMBB(loopMBB)
7700     .addReg(dest).addMBB(entryBB);
7701
7702   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7703   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7704   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7705   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7706              IsThumb1, IsThumb2);
7707   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7708              IsThumb1, IsThumb2);
7709
7710   // Decrement loop variable by UnitSize.
7711   if (IsThumb1) {
7712     MachineInstrBuilder MIB =
7713         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7714     MIB = AddDefaultT1CC(MIB);
7715     MIB.addReg(varPhi).addImm(UnitSize);
7716     AddDefaultPred(MIB);
7717   } else {
7718     MachineInstrBuilder MIB =
7719         BuildMI(*BB, BB->end(), dl,
7720                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7721     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7722     MIB->getOperand(5).setReg(ARM::CPSR);
7723     MIB->getOperand(5).setIsDef(true);
7724   }
7725   BuildMI(*BB, BB->end(), dl,
7726           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7727       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7728
7729   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7730   BB->addSuccessor(loopMBB);
7731   BB->addSuccessor(exitMBB);
7732
7733   // Add epilogue to handle BytesLeft.
7734   BB = exitMBB;
7735   MachineInstr *StartOfExit = exitMBB->begin();
7736
7737   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7738   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7739   unsigned srcIn = srcLoop;
7740   unsigned destIn = destLoop;
7741   for (unsigned i = 0; i < BytesLeft; i++) {
7742     unsigned srcOut = MRI.createVirtualRegister(TRC);
7743     unsigned destOut = MRI.createVirtualRegister(TRC);
7744     unsigned scratch = MRI.createVirtualRegister(TRC);
7745     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7746                IsThumb1, IsThumb2);
7747     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7748                IsThumb1, IsThumb2);
7749     srcIn = srcOut;
7750     destIn = destOut;
7751   }
7752
7753   MI->eraseFromParent();   // The instruction is gone now.
7754   return BB;
7755 }
7756
7757 MachineBasicBlock *
7758 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7759                                        MachineBasicBlock *MBB) const {
7760   const TargetMachine &TM = getTargetMachine();
7761   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
7762   DebugLoc DL = MI->getDebugLoc();
7763
7764   assert(Subtarget->isTargetWindows() &&
7765          "__chkstk is only supported on Windows");
7766   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7767
7768   // __chkstk takes the number of words to allocate on the stack in R4, and
7769   // returns the stack adjustment in number of bytes in R4.  This will not
7770   // clober any other registers (other than the obvious lr).
7771   //
7772   // Although, technically, IP should be considered a register which may be
7773   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
7774   // thumb-2 environment, so there is no interworking required.  As a result, we
7775   // do not expect a veneer to be emitted by the linker, clobbering IP.
7776   //
7777   // Each module receives its own copy of __chkstk, so no import thunk is
7778   // required, again, ensuring that IP is not clobbered.
7779   //
7780   // Finally, although some linkers may theoretically provide a trampoline for
7781   // out of range calls (which is quite common due to a 32M range limitation of
7782   // branches for Thumb), we can generate the long-call version via
7783   // -mcmodel=large, alleviating the need for the trampoline which may clobber
7784   // IP.
7785
7786   switch (TM.getCodeModel()) {
7787   case CodeModel::Small:
7788   case CodeModel::Medium:
7789   case CodeModel::Default:
7790   case CodeModel::Kernel:
7791     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7792       .addImm((unsigned)ARMCC::AL).addReg(0)
7793       .addExternalSymbol("__chkstk")
7794       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7795       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7796       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7797     break;
7798   case CodeModel::Large:
7799   case CodeModel::JITDefault: {
7800     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7801     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7802
7803     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7804       .addExternalSymbol("__chkstk");
7805     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7806       .addImm((unsigned)ARMCC::AL).addReg(0)
7807       .addReg(Reg, RegState::Kill)
7808       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7809       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7810       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7811     break;
7812   }
7813   }
7814
7815   AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7816                                       ARM::SP)
7817                               .addReg(ARM::SP).addReg(ARM::R4)));
7818
7819   MI->eraseFromParent();
7820   return MBB;
7821 }
7822
7823 MachineBasicBlock *
7824 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr *MI,
7825                                        MachineBasicBlock *MBB) const {
7826   DebugLoc DL = MI->getDebugLoc();
7827   MachineFunction *MF = MBB->getParent();
7828   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7829
7830   MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
7831   MF->push_back(ContBB);
7832   ContBB->splice(ContBB->begin(), MBB,
7833                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
7834   MBB->addSuccessor(ContBB);
7835
7836   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
7837   MF->push_back(TrapBB);
7838   BuildMI(TrapBB, DL, TII->get(ARM::t2UDF)).addImm(249);
7839   MBB->addSuccessor(TrapBB);
7840
7841   BuildMI(*MBB, MI, DL, TII->get(ARM::tCBZ))
7842       .addReg(MI->getOperand(0).getReg())
7843       .addMBB(TrapBB);
7844
7845   MI->eraseFromParent();
7846   return ContBB;
7847 }
7848
7849 MachineBasicBlock *
7850 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7851                                                MachineBasicBlock *BB) const {
7852   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7853   DebugLoc dl = MI->getDebugLoc();
7854   bool isThumb2 = Subtarget->isThumb2();
7855   switch (MI->getOpcode()) {
7856   default: {
7857     MI->dump();
7858     llvm_unreachable("Unexpected instr type to insert");
7859   }
7860   // The Thumb2 pre-indexed stores have the same MI operands, they just
7861   // define them differently in the .td files from the isel patterns, so
7862   // they need pseudos.
7863   case ARM::t2STR_preidx:
7864     MI->setDesc(TII->get(ARM::t2STR_PRE));
7865     return BB;
7866   case ARM::t2STRB_preidx:
7867     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7868     return BB;
7869   case ARM::t2STRH_preidx:
7870     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7871     return BB;
7872
7873   case ARM::STRi_preidx:
7874   case ARM::STRBi_preidx: {
7875     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7876       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7877     // Decode the offset.
7878     unsigned Offset = MI->getOperand(4).getImm();
7879     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7880     Offset = ARM_AM::getAM2Offset(Offset);
7881     if (isSub)
7882       Offset = -Offset;
7883
7884     MachineMemOperand *MMO = *MI->memoperands_begin();
7885     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7886       .addOperand(MI->getOperand(0))  // Rn_wb
7887       .addOperand(MI->getOperand(1))  // Rt
7888       .addOperand(MI->getOperand(2))  // Rn
7889       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7890       .addOperand(MI->getOperand(5))  // pred
7891       .addOperand(MI->getOperand(6))
7892       .addMemOperand(MMO);
7893     MI->eraseFromParent();
7894     return BB;
7895   }
7896   case ARM::STRr_preidx:
7897   case ARM::STRBr_preidx:
7898   case ARM::STRH_preidx: {
7899     unsigned NewOpc;
7900     switch (MI->getOpcode()) {
7901     default: llvm_unreachable("unexpected opcode!");
7902     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7903     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7904     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7905     }
7906     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7907     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7908       MIB.addOperand(MI->getOperand(i));
7909     MI->eraseFromParent();
7910     return BB;
7911   }
7912
7913   case ARM::tMOVCCr_pseudo: {
7914     // To "insert" a SELECT_CC instruction, we actually have to insert the
7915     // diamond control-flow pattern.  The incoming instruction knows the
7916     // destination vreg to set, the condition code register to branch on, the
7917     // true/false values to select between, and a branch opcode to use.
7918     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7919     MachineFunction::iterator It = ++BB->getIterator();
7920
7921     //  thisMBB:
7922     //  ...
7923     //   TrueVal = ...
7924     //   cmpTY ccX, r1, r2
7925     //   bCC copy1MBB
7926     //   fallthrough --> copy0MBB
7927     MachineBasicBlock *thisMBB  = BB;
7928     MachineFunction *F = BB->getParent();
7929     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7930     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7931     F->insert(It, copy0MBB);
7932     F->insert(It, sinkMBB);
7933
7934     // Transfer the remainder of BB and its successor edges to sinkMBB.
7935     sinkMBB->splice(sinkMBB->begin(), BB,
7936                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7937     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7938
7939     BB->addSuccessor(copy0MBB);
7940     BB->addSuccessor(sinkMBB);
7941
7942     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7943       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7944
7945     //  copy0MBB:
7946     //   %FalseValue = ...
7947     //   # fallthrough to sinkMBB
7948     BB = copy0MBB;
7949
7950     // Update machine-CFG edges
7951     BB->addSuccessor(sinkMBB);
7952
7953     //  sinkMBB:
7954     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7955     //  ...
7956     BB = sinkMBB;
7957     BuildMI(*BB, BB->begin(), dl,
7958             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7959       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7960       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7961
7962     MI->eraseFromParent();   // The pseudo instruction is gone now.
7963     return BB;
7964   }
7965
7966   case ARM::BCCi64:
7967   case ARM::BCCZi64: {
7968     // If there is an unconditional branch to the other successor, remove it.
7969     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7970
7971     // Compare both parts that make up the double comparison separately for
7972     // equality.
7973     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7974
7975     unsigned LHS1 = MI->getOperand(1).getReg();
7976     unsigned LHS2 = MI->getOperand(2).getReg();
7977     if (RHSisZero) {
7978       AddDefaultPred(BuildMI(BB, dl,
7979                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7980                      .addReg(LHS1).addImm(0));
7981       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7982         .addReg(LHS2).addImm(0)
7983         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7984     } else {
7985       unsigned RHS1 = MI->getOperand(3).getReg();
7986       unsigned RHS2 = MI->getOperand(4).getReg();
7987       AddDefaultPred(BuildMI(BB, dl,
7988                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7989                      .addReg(LHS1).addReg(RHS1));
7990       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7991         .addReg(LHS2).addReg(RHS2)
7992         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7993     }
7994
7995     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7996     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7997     if (MI->getOperand(0).getImm() == ARMCC::NE)
7998       std::swap(destMBB, exitMBB);
7999
8000     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
8001       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
8002     if (isThumb2)
8003       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
8004     else
8005       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
8006
8007     MI->eraseFromParent();   // The pseudo instruction is gone now.
8008     return BB;
8009   }
8010
8011   case ARM::Int_eh_sjlj_setjmp:
8012   case ARM::Int_eh_sjlj_setjmp_nofp:
8013   case ARM::tInt_eh_sjlj_setjmp:
8014   case ARM::t2Int_eh_sjlj_setjmp:
8015   case ARM::t2Int_eh_sjlj_setjmp_nofp:
8016     return BB;
8017
8018   case ARM::Int_eh_sjlj_setup_dispatch:
8019     EmitSjLjDispatchBlock(MI, BB);
8020     return BB;
8021
8022   case ARM::ABS:
8023   case ARM::t2ABS: {
8024     // To insert an ABS instruction, we have to insert the
8025     // diamond control-flow pattern.  The incoming instruction knows the
8026     // source vreg to test against 0, the destination vreg to set,
8027     // the condition code register to branch on, the
8028     // true/false values to select between, and a branch opcode to use.
8029     // It transforms
8030     //     V1 = ABS V0
8031     // into
8032     //     V2 = MOVS V0
8033     //     BCC                      (branch to SinkBB if V0 >= 0)
8034     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
8035     //     SinkBB: V1 = PHI(V2, V3)
8036     const BasicBlock *LLVM_BB = BB->getBasicBlock();
8037     MachineFunction::iterator BBI = ++BB->getIterator();
8038     MachineFunction *Fn = BB->getParent();
8039     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
8040     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
8041     Fn->insert(BBI, RSBBB);
8042     Fn->insert(BBI, SinkBB);
8043
8044     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
8045     unsigned int ABSDstReg = MI->getOperand(0).getReg();
8046     bool ABSSrcKIll = MI->getOperand(1).isKill();
8047     bool isThumb2 = Subtarget->isThumb2();
8048     MachineRegisterInfo &MRI = Fn->getRegInfo();
8049     // In Thumb mode S must not be specified if source register is the SP or
8050     // PC and if destination register is the SP, so restrict register class
8051     unsigned NewRsbDstReg =
8052       MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
8053
8054     // Transfer the remainder of BB and its successor edges to sinkMBB.
8055     SinkBB->splice(SinkBB->begin(), BB,
8056                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
8057     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
8058
8059     BB->addSuccessor(RSBBB);
8060     BB->addSuccessor(SinkBB);
8061
8062     // fall through to SinkMBB
8063     RSBBB->addSuccessor(SinkBB);
8064
8065     // insert a cmp at the end of BB
8066     AddDefaultPred(BuildMI(BB, dl,
8067                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
8068                    .addReg(ABSSrcReg).addImm(0));
8069
8070     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
8071     BuildMI(BB, dl,
8072       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
8073       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
8074
8075     // insert rsbri in RSBBB
8076     // Note: BCC and rsbri will be converted into predicated rsbmi
8077     // by if-conversion pass
8078     BuildMI(*RSBBB, RSBBB->begin(), dl,
8079       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
8080       .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
8081       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
8082
8083     // insert PHI in SinkBB,
8084     // reuse ABSDstReg to not change uses of ABS instruction
8085     BuildMI(*SinkBB, SinkBB->begin(), dl,
8086       TII->get(ARM::PHI), ABSDstReg)
8087       .addReg(NewRsbDstReg).addMBB(RSBBB)
8088       .addReg(ABSSrcReg).addMBB(BB);
8089
8090     // remove ABS instruction
8091     MI->eraseFromParent();
8092
8093     // return last added BB
8094     return SinkBB;
8095   }
8096   case ARM::COPY_STRUCT_BYVAL_I32:
8097     ++NumLoopByVals;
8098     return EmitStructByval(MI, BB);
8099   case ARM::WIN__CHKSTK:
8100     return EmitLowered__chkstk(MI, BB);
8101   case ARM::WIN__DBZCHK:
8102     return EmitLowered__dbzchk(MI, BB);
8103   }
8104 }
8105
8106 /// \brief Attaches vregs to MEMCPY that it will use as scratch registers
8107 /// when it is expanded into LDM/STM. This is done as a post-isel lowering
8108 /// instead of as a custom inserter because we need the use list from the SDNode.
8109 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget,
8110                                    MachineInstr *MI, const SDNode *Node) {
8111   bool isThumb1 = Subtarget->isThumb1Only();
8112
8113   DebugLoc DL = MI->getDebugLoc();
8114   MachineFunction *MF = MI->getParent()->getParent();
8115   MachineRegisterInfo &MRI = MF->getRegInfo();
8116   MachineInstrBuilder MIB(*MF, MI);
8117
8118   // If the new dst/src is unused mark it as dead.
8119   if (!Node->hasAnyUseOfValue(0)) {
8120     MI->getOperand(0).setIsDead(true);
8121   }
8122   if (!Node->hasAnyUseOfValue(1)) {
8123     MI->getOperand(1).setIsDead(true);
8124   }
8125
8126   // The MEMCPY both defines and kills the scratch registers.
8127   for (unsigned I = 0; I != MI->getOperand(4).getImm(); ++I) {
8128     unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass
8129                                                          : &ARM::GPRRegClass);
8130     MIB.addReg(TmpReg, RegState::Define|RegState::Dead);
8131   }
8132 }
8133
8134 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
8135                                                       SDNode *Node) const {
8136   if (MI->getOpcode() == ARM::MEMCPY) {
8137     attachMEMCPYScratchRegs(Subtarget, MI, Node);
8138     return;
8139   }
8140
8141   const MCInstrDesc *MCID = &MI->getDesc();
8142   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
8143   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
8144   // operand is still set to noreg. If needed, set the optional operand's
8145   // register to CPSR, and remove the redundant implicit def.
8146   //
8147   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
8148
8149   // Rename pseudo opcodes.
8150   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
8151   if (NewOpc) {
8152     const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
8153     MCID = &TII->get(NewOpc);
8154
8155     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
8156            "converted opcode should be the same except for cc_out");
8157
8158     MI->setDesc(*MCID);
8159
8160     // Add the optional cc_out operand
8161     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
8162   }
8163   unsigned ccOutIdx = MCID->getNumOperands() - 1;
8164
8165   // Any ARM instruction that sets the 's' bit should specify an optional
8166   // "cc_out" operand in the last operand position.
8167   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
8168     assert(!NewOpc && "Optional cc_out operand required");
8169     return;
8170   }
8171   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
8172   // since we already have an optional CPSR def.
8173   bool definesCPSR = false;
8174   bool deadCPSR = false;
8175   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
8176        i != e; ++i) {
8177     const MachineOperand &MO = MI->getOperand(i);
8178     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
8179       definesCPSR = true;
8180       if (MO.isDead())
8181         deadCPSR = true;
8182       MI->RemoveOperand(i);
8183       break;
8184     }
8185   }
8186   if (!definesCPSR) {
8187     assert(!NewOpc && "Optional cc_out operand required");
8188     return;
8189   }
8190   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
8191   if (deadCPSR) {
8192     assert(!MI->getOperand(ccOutIdx).getReg() &&
8193            "expect uninitialized optional cc_out operand");
8194     return;
8195   }
8196
8197   // If this instruction was defined with an optional CPSR def and its dag node
8198   // had a live implicit CPSR def, then activate the optional CPSR def.
8199   MachineOperand &MO = MI->getOperand(ccOutIdx);
8200   MO.setReg(ARM::CPSR);
8201   MO.setIsDef(true);
8202 }
8203
8204 //===----------------------------------------------------------------------===//
8205 //                           ARM Optimization Hooks
8206 //===----------------------------------------------------------------------===//
8207
8208 // Helper function that checks if N is a null or all ones constant.
8209 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
8210   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
8211   if (!C)
8212     return false;
8213   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
8214 }
8215
8216 // Return true if N is conditionally 0 or all ones.
8217 // Detects these expressions where cc is an i1 value:
8218 //
8219 //   (select cc 0, y)   [AllOnes=0]
8220 //   (select cc y, 0)   [AllOnes=0]
8221 //   (zext cc)          [AllOnes=0]
8222 //   (sext cc)          [AllOnes=0/1]
8223 //   (select cc -1, y)  [AllOnes=1]
8224 //   (select cc y, -1)  [AllOnes=1]
8225 //
8226 // Invert is set when N is the null/all ones constant when CC is false.
8227 // OtherOp is set to the alternative value of N.
8228 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
8229                                        SDValue &CC, bool &Invert,
8230                                        SDValue &OtherOp,
8231                                        SelectionDAG &DAG) {
8232   switch (N->getOpcode()) {
8233   default: return false;
8234   case ISD::SELECT: {
8235     CC = N->getOperand(0);
8236     SDValue N1 = N->getOperand(1);
8237     SDValue N2 = N->getOperand(2);
8238     if (isZeroOrAllOnes(N1, AllOnes)) {
8239       Invert = false;
8240       OtherOp = N2;
8241       return true;
8242     }
8243     if (isZeroOrAllOnes(N2, AllOnes)) {
8244       Invert = true;
8245       OtherOp = N1;
8246       return true;
8247     }
8248     return false;
8249   }
8250   case ISD::ZERO_EXTEND:
8251     // (zext cc) can never be the all ones value.
8252     if (AllOnes)
8253       return false;
8254     // Fall through.
8255   case ISD::SIGN_EXTEND: {
8256     SDLoc dl(N);
8257     EVT VT = N->getValueType(0);
8258     CC = N->getOperand(0);
8259     if (CC.getValueType() != MVT::i1)
8260       return false;
8261     Invert = !AllOnes;
8262     if (AllOnes)
8263       // When looking for an AllOnes constant, N is an sext, and the 'other'
8264       // value is 0.
8265       OtherOp = DAG.getConstant(0, dl, VT);
8266     else if (N->getOpcode() == ISD::ZERO_EXTEND)
8267       // When looking for a 0 constant, N can be zext or sext.
8268       OtherOp = DAG.getConstant(1, dl, VT);
8269     else
8270       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
8271                                 VT);
8272     return true;
8273   }
8274   }
8275 }
8276
8277 // Combine a constant select operand into its use:
8278 //
8279 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
8280 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
8281 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
8282 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
8283 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
8284 //
8285 // The transform is rejected if the select doesn't have a constant operand that
8286 // is null, or all ones when AllOnes is set.
8287 //
8288 // Also recognize sext/zext from i1:
8289 //
8290 //   (add (zext cc), x) -> (select cc (add x, 1), x)
8291 //   (add (sext cc), x) -> (select cc (add x, -1), x)
8292 //
8293 // These transformations eventually create predicated instructions.
8294 //
8295 // @param N       The node to transform.
8296 // @param Slct    The N operand that is a select.
8297 // @param OtherOp The other N operand (x above).
8298 // @param DCI     Context.
8299 // @param AllOnes Require the select constant to be all ones instead of null.
8300 // @returns The new node, or SDValue() on failure.
8301 static
8302 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
8303                             TargetLowering::DAGCombinerInfo &DCI,
8304                             bool AllOnes = false) {
8305   SelectionDAG &DAG = DCI.DAG;
8306   EVT VT = N->getValueType(0);
8307   SDValue NonConstantVal;
8308   SDValue CCOp;
8309   bool SwapSelectOps;
8310   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
8311                                   NonConstantVal, DAG))
8312     return SDValue();
8313
8314   // Slct is now know to be the desired identity constant when CC is true.
8315   SDValue TrueVal = OtherOp;
8316   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
8317                                  OtherOp, NonConstantVal);
8318   // Unless SwapSelectOps says CC should be false.
8319   if (SwapSelectOps)
8320     std::swap(TrueVal, FalseVal);
8321
8322   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
8323                      CCOp, TrueVal, FalseVal);
8324 }
8325
8326 // Attempt combineSelectAndUse on each operand of a commutative operator N.
8327 static
8328 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
8329                                        TargetLowering::DAGCombinerInfo &DCI) {
8330   SDValue N0 = N->getOperand(0);
8331   SDValue N1 = N->getOperand(1);
8332   if (N0.getNode()->hasOneUse()) {
8333     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
8334     if (Result.getNode())
8335       return Result;
8336   }
8337   if (N1.getNode()->hasOneUse()) {
8338     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
8339     if (Result.getNode())
8340       return Result;
8341   }
8342   return SDValue();
8343 }
8344
8345 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
8346 // (only after legalization).
8347 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
8348                                  TargetLowering::DAGCombinerInfo &DCI,
8349                                  const ARMSubtarget *Subtarget) {
8350
8351   // Only perform optimization if after legalize, and if NEON is available. We
8352   // also expected both operands to be BUILD_VECTORs.
8353   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
8354       || N0.getOpcode() != ISD::BUILD_VECTOR
8355       || N1.getOpcode() != ISD::BUILD_VECTOR)
8356     return SDValue();
8357
8358   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
8359   EVT VT = N->getValueType(0);
8360   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
8361     return SDValue();
8362
8363   // Check that the vector operands are of the right form.
8364   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
8365   // operands, where N is the size of the formed vector.
8366   // Each EXTRACT_VECTOR should have the same input vector and odd or even
8367   // index such that we have a pair wise add pattern.
8368
8369   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
8370   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8371     return SDValue();
8372   SDValue Vec = N0->getOperand(0)->getOperand(0);
8373   SDNode *V = Vec.getNode();
8374   unsigned nextIndex = 0;
8375
8376   // For each operands to the ADD which are BUILD_VECTORs,
8377   // check to see if each of their operands are an EXTRACT_VECTOR with
8378   // the same vector and appropriate index.
8379   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
8380     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
8381         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8382
8383       SDValue ExtVec0 = N0->getOperand(i);
8384       SDValue ExtVec1 = N1->getOperand(i);
8385
8386       // First operand is the vector, verify its the same.
8387       if (V != ExtVec0->getOperand(0).getNode() ||
8388           V != ExtVec1->getOperand(0).getNode())
8389         return SDValue();
8390
8391       // Second is the constant, verify its correct.
8392       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
8393       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
8394
8395       // For the constant, we want to see all the even or all the odd.
8396       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
8397           || C1->getZExtValue() != nextIndex+1)
8398         return SDValue();
8399
8400       // Increment index.
8401       nextIndex+=2;
8402     } else
8403       return SDValue();
8404   }
8405
8406   // Create VPADDL node.
8407   SelectionDAG &DAG = DCI.DAG;
8408   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8409
8410   SDLoc dl(N);
8411
8412   // Build operand list.
8413   SmallVector<SDValue, 8> Ops;
8414   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
8415                                 TLI.getPointerTy(DAG.getDataLayout())));
8416
8417   // Input is the vector.
8418   Ops.push_back(Vec);
8419
8420   // Get widened type and narrowed type.
8421   MVT widenType;
8422   unsigned numElem = VT.getVectorNumElements();
8423   
8424   EVT inputLaneType = Vec.getValueType().getVectorElementType();
8425   switch (inputLaneType.getSimpleVT().SimpleTy) {
8426     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
8427     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
8428     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
8429     default:
8430       llvm_unreachable("Invalid vector element type for padd optimization.");
8431   }
8432
8433   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
8434   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
8435   return DAG.getNode(ExtOp, dl, VT, tmp);
8436 }
8437
8438 static SDValue findMUL_LOHI(SDValue V) {
8439   if (V->getOpcode() == ISD::UMUL_LOHI ||
8440       V->getOpcode() == ISD::SMUL_LOHI)
8441     return V;
8442   return SDValue();
8443 }
8444
8445 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
8446                                      TargetLowering::DAGCombinerInfo &DCI,
8447                                      const ARMSubtarget *Subtarget) {
8448
8449   if (Subtarget->isThumb1Only()) return SDValue();
8450
8451   // Only perform the checks after legalize when the pattern is available.
8452   if (DCI.isBeforeLegalize()) return SDValue();
8453
8454   // Look for multiply add opportunities.
8455   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8456   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8457   // a glue link from the first add to the second add.
8458   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8459   // a S/UMLAL instruction.
8460   //                  UMUL_LOHI
8461   //                 / :lo    \ :hi
8462   //                /          \          [no multiline comment]
8463   //    loAdd ->  ADDE         |
8464   //                 \ :glue  /
8465   //                  \      /
8466   //                    ADDC   <- hiAdd
8467   //
8468   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8469   SDValue AddcOp0 = AddcNode->getOperand(0);
8470   SDValue AddcOp1 = AddcNode->getOperand(1);
8471
8472   // Check if the two operands are from the same mul_lohi node.
8473   if (AddcOp0.getNode() == AddcOp1.getNode())
8474     return SDValue();
8475
8476   assert(AddcNode->getNumValues() == 2 &&
8477          AddcNode->getValueType(0) == MVT::i32 &&
8478          "Expect ADDC with two result values. First: i32");
8479
8480   // Check that we have a glued ADDC node.
8481   if (AddcNode->getValueType(1) != MVT::Glue)
8482     return SDValue();
8483
8484   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8485   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8486       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8487       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8488       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8489     return SDValue();
8490
8491   // Look for the glued ADDE.
8492   SDNode* AddeNode = AddcNode->getGluedUser();
8493   if (!AddeNode)
8494     return SDValue();
8495
8496   // Make sure it is really an ADDE.
8497   if (AddeNode->getOpcode() != ISD::ADDE)
8498     return SDValue();
8499
8500   assert(AddeNode->getNumOperands() == 3 &&
8501          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8502          "ADDE node has the wrong inputs");
8503
8504   // Check for the triangle shape.
8505   SDValue AddeOp0 = AddeNode->getOperand(0);
8506   SDValue AddeOp1 = AddeNode->getOperand(1);
8507
8508   // Make sure that the ADDE operands are not coming from the same node.
8509   if (AddeOp0.getNode() == AddeOp1.getNode())
8510     return SDValue();
8511
8512   // Find the MUL_LOHI node walking up ADDE's operands.
8513   bool IsLeftOperandMUL = false;
8514   SDValue MULOp = findMUL_LOHI(AddeOp0);
8515   if (MULOp == SDValue())
8516    MULOp = findMUL_LOHI(AddeOp1);
8517   else
8518     IsLeftOperandMUL = true;
8519   if (MULOp == SDValue())
8520     return SDValue();
8521
8522   // Figure out the right opcode.
8523   unsigned Opc = MULOp->getOpcode();
8524   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8525
8526   // Figure out the high and low input values to the MLAL node.
8527   SDValue* HiAdd = nullptr;
8528   SDValue* LoMul = nullptr;
8529   SDValue* LowAdd = nullptr;
8530
8531   // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
8532   if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
8533     return SDValue();
8534
8535   if (IsLeftOperandMUL)
8536     HiAdd = &AddeOp1;
8537   else
8538     HiAdd = &AddeOp0;
8539
8540
8541   // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
8542   // whose low result is fed to the ADDC we are checking.
8543
8544   if (AddcOp0 == MULOp.getValue(0)) {
8545     LoMul = &AddcOp0;
8546     LowAdd = &AddcOp1;
8547   }
8548   if (AddcOp1 == MULOp.getValue(0)) {
8549     LoMul = &AddcOp1;
8550     LowAdd = &AddcOp0;
8551   }
8552
8553   if (!LoMul)
8554     return SDValue();
8555
8556   // Create the merged node.
8557   SelectionDAG &DAG = DCI.DAG;
8558
8559   // Build operand list.
8560   SmallVector<SDValue, 8> Ops;
8561   Ops.push_back(LoMul->getOperand(0));
8562   Ops.push_back(LoMul->getOperand(1));
8563   Ops.push_back(*LowAdd);
8564   Ops.push_back(*HiAdd);
8565
8566   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
8567                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
8568
8569   // Replace the ADDs' nodes uses by the MLA node's values.
8570   SDValue HiMLALResult(MLALNode.getNode(), 1);
8571   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8572
8573   SDValue LoMLALResult(MLALNode.getNode(), 0);
8574   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8575
8576   // Return original node to notify the driver to stop replacing.
8577   SDValue resNode(AddcNode, 0);
8578   return resNode;
8579 }
8580
8581 /// PerformADDCCombine - Target-specific dag combine transform from
8582 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8583 static SDValue PerformADDCCombine(SDNode *N,
8584                                  TargetLowering::DAGCombinerInfo &DCI,
8585                                  const ARMSubtarget *Subtarget) {
8586
8587   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8588
8589 }
8590
8591 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8592 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
8593 /// called with the default operands, and if that fails, with commuted
8594 /// operands.
8595 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8596                                           TargetLowering::DAGCombinerInfo &DCI,
8597                                           const ARMSubtarget *Subtarget){
8598
8599   // Attempt to create vpaddl for this add.
8600   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8601   if (Result.getNode())
8602     return Result;
8603
8604   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8605   if (N0.getNode()->hasOneUse()) {
8606     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8607     if (Result.getNode()) return Result;
8608   }
8609   return SDValue();
8610 }
8611
8612 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8613 ///
8614 static SDValue PerformADDCombine(SDNode *N,
8615                                  TargetLowering::DAGCombinerInfo &DCI,
8616                                  const ARMSubtarget *Subtarget) {
8617   SDValue N0 = N->getOperand(0);
8618   SDValue N1 = N->getOperand(1);
8619
8620   // First try with the default operand order.
8621   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8622   if (Result.getNode())
8623     return Result;
8624
8625   // If that didn't work, try again with the operands commuted.
8626   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8627 }
8628
8629 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8630 ///
8631 static SDValue PerformSUBCombine(SDNode *N,
8632                                  TargetLowering::DAGCombinerInfo &DCI) {
8633   SDValue N0 = N->getOperand(0);
8634   SDValue N1 = N->getOperand(1);
8635
8636   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8637   if (N1.getNode()->hasOneUse()) {
8638     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8639     if (Result.getNode()) return Result;
8640   }
8641
8642   return SDValue();
8643 }
8644
8645 /// PerformVMULCombine
8646 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8647 /// special multiplier accumulator forwarding.
8648 ///   vmul d3, d0, d2
8649 ///   vmla d3, d1, d2
8650 /// is faster than
8651 ///   vadd d3, d0, d1
8652 ///   vmul d3, d3, d2
8653 //  However, for (A + B) * (A + B),
8654 //    vadd d2, d0, d1
8655 //    vmul d3, d0, d2
8656 //    vmla d3, d1, d2
8657 //  is slower than
8658 //    vadd d2, d0, d1
8659 //    vmul d3, d2, d2
8660 static SDValue PerformVMULCombine(SDNode *N,
8661                                   TargetLowering::DAGCombinerInfo &DCI,
8662                                   const ARMSubtarget *Subtarget) {
8663   if (!Subtarget->hasVMLxForwarding())
8664     return SDValue();
8665
8666   SelectionDAG &DAG = DCI.DAG;
8667   SDValue N0 = N->getOperand(0);
8668   SDValue N1 = N->getOperand(1);
8669   unsigned Opcode = N0.getOpcode();
8670   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8671       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8672     Opcode = N1.getOpcode();
8673     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8674         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8675       return SDValue();
8676     std::swap(N0, N1);
8677   }
8678
8679   if (N0 == N1)
8680     return SDValue();
8681
8682   EVT VT = N->getValueType(0);
8683   SDLoc DL(N);
8684   SDValue N00 = N0->getOperand(0);
8685   SDValue N01 = N0->getOperand(1);
8686   return DAG.getNode(Opcode, DL, VT,
8687                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8688                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8689 }
8690
8691 static SDValue PerformMULCombine(SDNode *N,
8692                                  TargetLowering::DAGCombinerInfo &DCI,
8693                                  const ARMSubtarget *Subtarget) {
8694   SelectionDAG &DAG = DCI.DAG;
8695
8696   if (Subtarget->isThumb1Only())
8697     return SDValue();
8698
8699   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8700     return SDValue();
8701
8702   EVT VT = N->getValueType(0);
8703   if (VT.is64BitVector() || VT.is128BitVector())
8704     return PerformVMULCombine(N, DCI, Subtarget);
8705   if (VT != MVT::i32)
8706     return SDValue();
8707
8708   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8709   if (!C)
8710     return SDValue();
8711
8712   int64_t MulAmt = C->getSExtValue();
8713   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8714
8715   ShiftAmt = ShiftAmt & (32 - 1);
8716   SDValue V = N->getOperand(0);
8717   SDLoc DL(N);
8718
8719   SDValue Res;
8720   MulAmt >>= ShiftAmt;
8721
8722   if (MulAmt >= 0) {
8723     if (isPowerOf2_32(MulAmt - 1)) {
8724       // (mul x, 2^N + 1) => (add (shl x, N), x)
8725       Res = DAG.getNode(ISD::ADD, DL, VT,
8726                         V,
8727                         DAG.getNode(ISD::SHL, DL, VT,
8728                                     V,
8729                                     DAG.getConstant(Log2_32(MulAmt - 1), DL,
8730                                                     MVT::i32)));
8731     } else if (isPowerOf2_32(MulAmt + 1)) {
8732       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8733       Res = DAG.getNode(ISD::SUB, DL, VT,
8734                         DAG.getNode(ISD::SHL, DL, VT,
8735                                     V,
8736                                     DAG.getConstant(Log2_32(MulAmt + 1), DL,
8737                                                     MVT::i32)),
8738                         V);
8739     } else
8740       return SDValue();
8741   } else {
8742     uint64_t MulAmtAbs = -MulAmt;
8743     if (isPowerOf2_32(MulAmtAbs + 1)) {
8744       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8745       Res = DAG.getNode(ISD::SUB, DL, VT,
8746                         V,
8747                         DAG.getNode(ISD::SHL, DL, VT,
8748                                     V,
8749                                     DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
8750                                                     MVT::i32)));
8751     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8752       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8753       Res = DAG.getNode(ISD::ADD, DL, VT,
8754                         V,
8755                         DAG.getNode(ISD::SHL, DL, VT,
8756                                     V,
8757                                     DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
8758                                                     MVT::i32)));
8759       Res = DAG.getNode(ISD::SUB, DL, VT,
8760                         DAG.getConstant(0, DL, MVT::i32), Res);
8761
8762     } else
8763       return SDValue();
8764   }
8765
8766   if (ShiftAmt != 0)
8767     Res = DAG.getNode(ISD::SHL, DL, VT,
8768                       Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
8769
8770   // Do not add new nodes to DAG combiner worklist.
8771   DCI.CombineTo(N, Res, false);
8772   return SDValue();
8773 }
8774
8775 static SDValue PerformANDCombine(SDNode *N,
8776                                  TargetLowering::DAGCombinerInfo &DCI,
8777                                  const ARMSubtarget *Subtarget) {
8778
8779   // Attempt to use immediate-form VBIC
8780   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8781   SDLoc dl(N);
8782   EVT VT = N->getValueType(0);
8783   SelectionDAG &DAG = DCI.DAG;
8784
8785   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8786     return SDValue();
8787
8788   APInt SplatBits, SplatUndef;
8789   unsigned SplatBitSize;
8790   bool HasAnyUndefs;
8791   if (BVN &&
8792       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8793     if (SplatBitSize <= 64) {
8794       EVT VbicVT;
8795       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8796                                       SplatUndef.getZExtValue(), SplatBitSize,
8797                                       DAG, dl, VbicVT, VT.is128BitVector(),
8798                                       OtherModImm);
8799       if (Val.getNode()) {
8800         SDValue Input =
8801           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8802         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8803         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8804       }
8805     }
8806   }
8807
8808   if (!Subtarget->isThumb1Only()) {
8809     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8810     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8811     if (Result.getNode())
8812       return Result;
8813   }
8814
8815   return SDValue();
8816 }
8817
8818 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8819 static SDValue PerformORCombine(SDNode *N,
8820                                 TargetLowering::DAGCombinerInfo &DCI,
8821                                 const ARMSubtarget *Subtarget) {
8822   // Attempt to use immediate-form VORR
8823   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8824   SDLoc dl(N);
8825   EVT VT = N->getValueType(0);
8826   SelectionDAG &DAG = DCI.DAG;
8827
8828   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8829     return SDValue();
8830
8831   APInt SplatBits, SplatUndef;
8832   unsigned SplatBitSize;
8833   bool HasAnyUndefs;
8834   if (BVN && Subtarget->hasNEON() &&
8835       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8836     if (SplatBitSize <= 64) {
8837       EVT VorrVT;
8838       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8839                                       SplatUndef.getZExtValue(), SplatBitSize,
8840                                       DAG, dl, VorrVT, VT.is128BitVector(),
8841                                       OtherModImm);
8842       if (Val.getNode()) {
8843         SDValue Input =
8844           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8845         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8846         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8847       }
8848     }
8849   }
8850
8851   if (!Subtarget->isThumb1Only()) {
8852     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8853     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8854     if (Result.getNode())
8855       return Result;
8856   }
8857
8858   // The code below optimizes (or (and X, Y), Z).
8859   // The AND operand needs to have a single user to make these optimizations
8860   // profitable.
8861   SDValue N0 = N->getOperand(0);
8862   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8863     return SDValue();
8864   SDValue N1 = N->getOperand(1);
8865
8866   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8867   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8868       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8869     APInt SplatUndef;
8870     unsigned SplatBitSize;
8871     bool HasAnyUndefs;
8872
8873     APInt SplatBits0, SplatBits1;
8874     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8875     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8876     // Ensure that the second operand of both ands are constants
8877     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8878                                       HasAnyUndefs) && !HasAnyUndefs) {
8879         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8880                                           HasAnyUndefs) && !HasAnyUndefs) {
8881             // Ensure that the bit width of the constants are the same and that
8882             // the splat arguments are logical inverses as per the pattern we
8883             // are trying to simplify.
8884             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8885                 SplatBits0 == ~SplatBits1) {
8886                 // Canonicalize the vector type to make instruction selection
8887                 // simpler.
8888                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8889                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8890                                              N0->getOperand(1),
8891                                              N0->getOperand(0),
8892                                              N1->getOperand(0));
8893                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8894             }
8895         }
8896     }
8897   }
8898
8899   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8900   // reasonable.
8901
8902   // BFI is only available on V6T2+
8903   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8904     return SDValue();
8905
8906   SDLoc DL(N);
8907   // 1) or (and A, mask), val => ARMbfi A, val, mask
8908   //      iff (val & mask) == val
8909   //
8910   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8911   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8912   //          && mask == ~mask2
8913   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8914   //          && ~mask == mask2
8915   //  (i.e., copy a bitfield value into another bitfield of the same width)
8916
8917   if (VT != MVT::i32)
8918     return SDValue();
8919
8920   SDValue N00 = N0.getOperand(0);
8921
8922   // The value and the mask need to be constants so we can verify this is
8923   // actually a bitfield set. If the mask is 0xffff, we can do better
8924   // via a movt instruction, so don't use BFI in that case.
8925   SDValue MaskOp = N0.getOperand(1);
8926   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8927   if (!MaskC)
8928     return SDValue();
8929   unsigned Mask = MaskC->getZExtValue();
8930   if (Mask == 0xffff)
8931     return SDValue();
8932   SDValue Res;
8933   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8934   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8935   if (N1C) {
8936     unsigned Val = N1C->getZExtValue();
8937     if ((Val & ~Mask) != Val)
8938       return SDValue();
8939
8940     if (ARM::isBitFieldInvertedMask(Mask)) {
8941       Val >>= countTrailingZeros(~Mask);
8942
8943       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8944                         DAG.getConstant(Val, DL, MVT::i32),
8945                         DAG.getConstant(Mask, DL, MVT::i32));
8946
8947       // Do not add new nodes to DAG combiner worklist.
8948       DCI.CombineTo(N, Res, false);
8949       return SDValue();
8950     }
8951   } else if (N1.getOpcode() == ISD::AND) {
8952     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8953     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8954     if (!N11C)
8955       return SDValue();
8956     unsigned Mask2 = N11C->getZExtValue();
8957
8958     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8959     // as is to match.
8960     if (ARM::isBitFieldInvertedMask(Mask) &&
8961         (Mask == ~Mask2)) {
8962       // The pack halfword instruction works better for masks that fit it,
8963       // so use that when it's available.
8964       if (Subtarget->hasT2ExtractPack() &&
8965           (Mask == 0xffff || Mask == 0xffff0000))
8966         return SDValue();
8967       // 2a
8968       unsigned amt = countTrailingZeros(Mask2);
8969       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8970                         DAG.getConstant(amt, DL, MVT::i32));
8971       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8972                         DAG.getConstant(Mask, DL, MVT::i32));
8973       // Do not add new nodes to DAG combiner worklist.
8974       DCI.CombineTo(N, Res, false);
8975       return SDValue();
8976     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8977                (~Mask == Mask2)) {
8978       // The pack halfword instruction works better for masks that fit it,
8979       // so use that when it's available.
8980       if (Subtarget->hasT2ExtractPack() &&
8981           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8982         return SDValue();
8983       // 2b
8984       unsigned lsb = countTrailingZeros(Mask);
8985       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8986                         DAG.getConstant(lsb, DL, MVT::i32));
8987       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8988                         DAG.getConstant(Mask2, DL, MVT::i32));
8989       // Do not add new nodes to DAG combiner worklist.
8990       DCI.CombineTo(N, Res, false);
8991       return SDValue();
8992     }
8993   }
8994
8995   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8996       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8997       ARM::isBitFieldInvertedMask(~Mask)) {
8998     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8999     // where lsb(mask) == #shamt and masked bits of B are known zero.
9000     SDValue ShAmt = N00.getOperand(1);
9001     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
9002     unsigned LSB = countTrailingZeros(Mask);
9003     if (ShAmtC != LSB)
9004       return SDValue();
9005
9006     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
9007                       DAG.getConstant(~Mask, DL, MVT::i32));
9008
9009     // Do not add new nodes to DAG combiner worklist.
9010     DCI.CombineTo(N, Res, false);
9011   }
9012
9013   return SDValue();
9014 }
9015
9016 static SDValue PerformXORCombine(SDNode *N,
9017                                  TargetLowering::DAGCombinerInfo &DCI,
9018                                  const ARMSubtarget *Subtarget) {
9019   EVT VT = N->getValueType(0);
9020   SelectionDAG &DAG = DCI.DAG;
9021
9022   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9023     return SDValue();
9024
9025   if (!Subtarget->isThumb1Only()) {
9026     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
9027     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
9028     if (Result.getNode())
9029       return Result;
9030   }
9031
9032   return SDValue();
9033 }
9034
9035 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it,
9036 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and
9037 // their position in "to" (Rd).
9038 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) {
9039   assert(N->getOpcode() == ARMISD::BFI);
9040   
9041   SDValue From = N->getOperand(1);
9042   ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue();
9043   FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation());
9044
9045   // If the Base came from a SHR #C, we can deduce that it is really testing bit
9046   // #C in the base of the SHR.
9047   if (From->getOpcode() == ISD::SRL &&
9048       isa<ConstantSDNode>(From->getOperand(1))) {
9049     APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue();
9050     assert(Shift.getLimitedValue() < 32 && "Shift too large!");
9051     FromMask <<= Shift.getLimitedValue(31);
9052     From = From->getOperand(0);
9053   }
9054
9055   return From;
9056 }
9057
9058 // If A and B contain one contiguous set of bits, does A | B == A . B?
9059 //
9060 // Neither A nor B must be zero.
9061 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) {
9062   unsigned LastActiveBitInA =  A.countTrailingZeros();
9063   unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1;
9064   return LastActiveBitInA - 1 == FirstActiveBitInB;
9065 }
9066
9067 static SDValue FindBFIToCombineWith(SDNode *N) {
9068   // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with,
9069   // if one exists.
9070   APInt ToMask, FromMask;
9071   SDValue From = ParseBFI(N, ToMask, FromMask);
9072   SDValue To = N->getOperand(0);
9073
9074   // Now check for a compatible BFI to merge with. We can pass through BFIs that
9075   // aren't compatible, but not if they set the same bit in their destination as
9076   // we do (or that of any BFI we're going to combine with).
9077   SDValue V = To;
9078   APInt CombinedToMask = ToMask;
9079   while (V.getOpcode() == ARMISD::BFI) {
9080     APInt NewToMask, NewFromMask;
9081     SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask);
9082     if (NewFrom != From) {
9083       // This BFI has a different base. Keep going.
9084       CombinedToMask |= NewToMask;
9085       V = V.getOperand(0);
9086       continue;
9087     }
9088
9089     // Do the written bits conflict with any we've seen so far?
9090     if ((NewToMask & CombinedToMask).getBoolValue())
9091       // Conflicting bits - bail out because going further is unsafe.
9092       return SDValue();
9093
9094     // Are the new bits contiguous when combined with the old bits?
9095     if (BitsProperlyConcatenate(ToMask, NewToMask) &&
9096         BitsProperlyConcatenate(FromMask, NewFromMask))
9097       return V;
9098     if (BitsProperlyConcatenate(NewToMask, ToMask) &&
9099         BitsProperlyConcatenate(NewFromMask, FromMask))
9100       return V;
9101     
9102     // We've seen a write to some bits, so track it.
9103     CombinedToMask |= NewToMask;
9104     // Keep going...
9105     V = V.getOperand(0);
9106   }
9107
9108   return SDValue();
9109 }
9110
9111 static SDValue PerformBFICombine(SDNode *N,
9112                                  TargetLowering::DAGCombinerInfo &DCI) {
9113   SDValue N1 = N->getOperand(1);
9114   if (N1.getOpcode() == ISD::AND) {
9115     // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
9116     // the bits being cleared by the AND are not demanded by the BFI.
9117     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
9118     if (!N11C)
9119       return SDValue();
9120     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
9121     unsigned LSB = countTrailingZeros(~InvMask);
9122     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
9123     assert(Width <
9124                static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
9125            "undefined behavior");
9126     unsigned Mask = (1u << Width) - 1;
9127     unsigned Mask2 = N11C->getZExtValue();
9128     if ((Mask & (~Mask2)) == 0)
9129       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
9130                              N->getOperand(0), N1.getOperand(0),
9131                              N->getOperand(2));
9132   } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) {
9133     // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes.
9134     // Keep track of any consecutive bits set that all come from the same base
9135     // value. We can combine these together into a single BFI.
9136     SDValue CombineBFI = FindBFIToCombineWith(N);
9137     if (CombineBFI == SDValue())
9138       return SDValue();
9139
9140     // We've found a BFI.
9141     APInt ToMask1, FromMask1;
9142     SDValue From1 = ParseBFI(N, ToMask1, FromMask1);
9143
9144     APInt ToMask2, FromMask2;
9145     SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2);
9146     assert(From1 == From2);
9147     (void)From2;
9148   
9149     // First, unlink CombineBFI.
9150     DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0));
9151     // Then create a new BFI, combining the two together.
9152     APInt NewFromMask = FromMask1 | FromMask2;
9153     APInt NewToMask = ToMask1 | ToMask2;
9154
9155     EVT VT = N->getValueType(0);
9156     SDLoc dl(N);
9157
9158     if (NewFromMask[0] == 0)
9159       From1 = DCI.DAG.getNode(
9160         ISD::SRL, dl, VT, From1,
9161         DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT));
9162     return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1,
9163                            DCI.DAG.getConstant(~NewToMask, dl, VT));
9164   }
9165   return SDValue();
9166 }
9167
9168 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
9169 /// ARMISD::VMOVRRD.
9170 static SDValue PerformVMOVRRDCombine(SDNode *N,
9171                                      TargetLowering::DAGCombinerInfo &DCI,
9172                                      const ARMSubtarget *Subtarget) {
9173   // vmovrrd(vmovdrr x, y) -> x,y
9174   SDValue InDouble = N->getOperand(0);
9175   if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
9176     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
9177
9178   // vmovrrd(load f64) -> (load i32), (load i32)
9179   SDNode *InNode = InDouble.getNode();
9180   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
9181       InNode->getValueType(0) == MVT::f64 &&
9182       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
9183       !cast<LoadSDNode>(InNode)->isVolatile()) {
9184     // TODO: Should this be done for non-FrameIndex operands?
9185     LoadSDNode *LD = cast<LoadSDNode>(InNode);
9186
9187     SelectionDAG &DAG = DCI.DAG;
9188     SDLoc DL(LD);
9189     SDValue BasePtr = LD->getBasePtr();
9190     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
9191                                  LD->getPointerInfo(), LD->isVolatile(),
9192                                  LD->isNonTemporal(), LD->isInvariant(),
9193                                  LD->getAlignment());
9194
9195     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9196                                     DAG.getConstant(4, DL, MVT::i32));
9197     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
9198                                  LD->getPointerInfo(), LD->isVolatile(),
9199                                  LD->isNonTemporal(), LD->isInvariant(),
9200                                  std::min(4U, LD->getAlignment() / 2));
9201
9202     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
9203     if (DCI.DAG.getDataLayout().isBigEndian())
9204       std::swap (NewLD1, NewLD2);
9205     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
9206     return Result;
9207   }
9208
9209   return SDValue();
9210 }
9211
9212 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
9213 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
9214 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
9215   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
9216   SDValue Op0 = N->getOperand(0);
9217   SDValue Op1 = N->getOperand(1);
9218   if (Op0.getOpcode() == ISD::BITCAST)
9219     Op0 = Op0.getOperand(0);
9220   if (Op1.getOpcode() == ISD::BITCAST)
9221     Op1 = Op1.getOperand(0);
9222   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
9223       Op0.getNode() == Op1.getNode() &&
9224       Op0.getResNo() == 0 && Op1.getResNo() == 1)
9225     return DAG.getNode(ISD::BITCAST, SDLoc(N),
9226                        N->getValueType(0), Op0.getOperand(0));
9227   return SDValue();
9228 }
9229
9230 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
9231 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
9232 /// i64 vector to have f64 elements, since the value can then be loaded
9233 /// directly into a VFP register.
9234 static bool hasNormalLoadOperand(SDNode *N) {
9235   unsigned NumElts = N->getValueType(0).getVectorNumElements();
9236   for (unsigned i = 0; i < NumElts; ++i) {
9237     SDNode *Elt = N->getOperand(i).getNode();
9238     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
9239       return true;
9240   }
9241   return false;
9242 }
9243
9244 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
9245 /// ISD::BUILD_VECTOR.
9246 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
9247                                           TargetLowering::DAGCombinerInfo &DCI,
9248                                           const ARMSubtarget *Subtarget) {
9249   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
9250   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
9251   // into a pair of GPRs, which is fine when the value is used as a scalar,
9252   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
9253   SelectionDAG &DAG = DCI.DAG;
9254   if (N->getNumOperands() == 2) {
9255     SDValue RV = PerformVMOVDRRCombine(N, DAG);
9256     if (RV.getNode())
9257       return RV;
9258   }
9259
9260   // Load i64 elements as f64 values so that type legalization does not split
9261   // them up into i32 values.
9262   EVT VT = N->getValueType(0);
9263   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
9264     return SDValue();
9265   SDLoc dl(N);
9266   SmallVector<SDValue, 8> Ops;
9267   unsigned NumElts = VT.getVectorNumElements();
9268   for (unsigned i = 0; i < NumElts; ++i) {
9269     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
9270     Ops.push_back(V);
9271     // Make the DAGCombiner fold the bitcast.
9272     DCI.AddToWorklist(V.getNode());
9273   }
9274   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
9275   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
9276   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9277 }
9278
9279 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
9280 static SDValue
9281 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9282   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
9283   // At that time, we may have inserted bitcasts from integer to float.
9284   // If these bitcasts have survived DAGCombine, change the lowering of this
9285   // BUILD_VECTOR in something more vector friendly, i.e., that does not
9286   // force to use floating point types.
9287
9288   // Make sure we can change the type of the vector.
9289   // This is possible iff:
9290   // 1. The vector is only used in a bitcast to a integer type. I.e.,
9291   //    1.1. Vector is used only once.
9292   //    1.2. Use is a bit convert to an integer type.
9293   // 2. The size of its operands are 32-bits (64-bits are not legal).
9294   EVT VT = N->getValueType(0);
9295   EVT EltVT = VT.getVectorElementType();
9296
9297   // Check 1.1. and 2.
9298   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
9299     return SDValue();
9300
9301   // By construction, the input type must be float.
9302   assert(EltVT == MVT::f32 && "Unexpected type!");
9303
9304   // Check 1.2.
9305   SDNode *Use = *N->use_begin();
9306   if (Use->getOpcode() != ISD::BITCAST ||
9307       Use->getValueType(0).isFloatingPoint())
9308     return SDValue();
9309
9310   // Check profitability.
9311   // Model is, if more than half of the relevant operands are bitcast from
9312   // i32, turn the build_vector into a sequence of insert_vector_elt.
9313   // Relevant operands are everything that is not statically
9314   // (i.e., at compile time) bitcasted.
9315   unsigned NumOfBitCastedElts = 0;
9316   unsigned NumElts = VT.getVectorNumElements();
9317   unsigned NumOfRelevantElts = NumElts;
9318   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
9319     SDValue Elt = N->getOperand(Idx);
9320     if (Elt->getOpcode() == ISD::BITCAST) {
9321       // Assume only bit cast to i32 will go away.
9322       if (Elt->getOperand(0).getValueType() == MVT::i32)
9323         ++NumOfBitCastedElts;
9324     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
9325       // Constants are statically casted, thus do not count them as
9326       // relevant operands.
9327       --NumOfRelevantElts;
9328   }
9329
9330   // Check if more than half of the elements require a non-free bitcast.
9331   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
9332     return SDValue();
9333
9334   SelectionDAG &DAG = DCI.DAG;
9335   // Create the new vector type.
9336   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
9337   // Check if the type is legal.
9338   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9339   if (!TLI.isTypeLegal(VecVT))
9340     return SDValue();
9341
9342   // Combine:
9343   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
9344   // => BITCAST INSERT_VECTOR_ELT
9345   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
9346   //                      (BITCAST EN), N.
9347   SDValue Vec = DAG.getUNDEF(VecVT);
9348   SDLoc dl(N);
9349   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
9350     SDValue V = N->getOperand(Idx);
9351     if (V.getOpcode() == ISD::UNDEF)
9352       continue;
9353     if (V.getOpcode() == ISD::BITCAST &&
9354         V->getOperand(0).getValueType() == MVT::i32)
9355       // Fold obvious case.
9356       V = V.getOperand(0);
9357     else {
9358       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
9359       // Make the DAGCombiner fold the bitcasts.
9360       DCI.AddToWorklist(V.getNode());
9361     }
9362     SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
9363     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
9364   }
9365   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
9366   // Make the DAGCombiner fold the bitcasts.
9367   DCI.AddToWorklist(Vec.getNode());
9368   return Vec;
9369 }
9370
9371 /// PerformInsertEltCombine - Target-specific dag combine xforms for
9372 /// ISD::INSERT_VECTOR_ELT.
9373 static SDValue PerformInsertEltCombine(SDNode *N,
9374                                        TargetLowering::DAGCombinerInfo &DCI) {
9375   // Bitcast an i64 load inserted into a vector to f64.
9376   // Otherwise, the i64 value will be legalized to a pair of i32 values.
9377   EVT VT = N->getValueType(0);
9378   SDNode *Elt = N->getOperand(1).getNode();
9379   if (VT.getVectorElementType() != MVT::i64 ||
9380       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
9381     return SDValue();
9382
9383   SelectionDAG &DAG = DCI.DAG;
9384   SDLoc dl(N);
9385   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9386                                  VT.getVectorNumElements());
9387   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
9388   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
9389   // Make the DAGCombiner fold the bitcasts.
9390   DCI.AddToWorklist(Vec.getNode());
9391   DCI.AddToWorklist(V.getNode());
9392   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
9393                                Vec, V, N->getOperand(2));
9394   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
9395 }
9396
9397 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
9398 /// ISD::VECTOR_SHUFFLE.
9399 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
9400   // The LLVM shufflevector instruction does not require the shuffle mask
9401   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
9402   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
9403   // operands do not match the mask length, they are extended by concatenating
9404   // them with undef vectors.  That is probably the right thing for other
9405   // targets, but for NEON it is better to concatenate two double-register
9406   // size vector operands into a single quad-register size vector.  Do that
9407   // transformation here:
9408   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
9409   //   shuffle(concat(v1, v2), undef)
9410   SDValue Op0 = N->getOperand(0);
9411   SDValue Op1 = N->getOperand(1);
9412   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
9413       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
9414       Op0.getNumOperands() != 2 ||
9415       Op1.getNumOperands() != 2)
9416     return SDValue();
9417   SDValue Concat0Op1 = Op0.getOperand(1);
9418   SDValue Concat1Op1 = Op1.getOperand(1);
9419   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
9420       Concat1Op1.getOpcode() != ISD::UNDEF)
9421     return SDValue();
9422   // Skip the transformation if any of the types are illegal.
9423   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9424   EVT VT = N->getValueType(0);
9425   if (!TLI.isTypeLegal(VT) ||
9426       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
9427       !TLI.isTypeLegal(Concat1Op1.getValueType()))
9428     return SDValue();
9429
9430   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
9431                                   Op0.getOperand(0), Op1.getOperand(0));
9432   // Translate the shuffle mask.
9433   SmallVector<int, 16> NewMask;
9434   unsigned NumElts = VT.getVectorNumElements();
9435   unsigned HalfElts = NumElts/2;
9436   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9437   for (unsigned n = 0; n < NumElts; ++n) {
9438     int MaskElt = SVN->getMaskElt(n);
9439     int NewElt = -1;
9440     if (MaskElt < (int)HalfElts)
9441       NewElt = MaskElt;
9442     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
9443       NewElt = HalfElts + MaskElt - NumElts;
9444     NewMask.push_back(NewElt);
9445   }
9446   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
9447                               DAG.getUNDEF(VT), NewMask.data());
9448 }
9449
9450 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
9451 /// NEON load/store intrinsics, and generic vector load/stores, to merge
9452 /// base address updates.
9453 /// For generic load/stores, the memory type is assumed to be a vector.
9454 /// The caller is assumed to have checked legality.
9455 static SDValue CombineBaseUpdate(SDNode *N,
9456                                  TargetLowering::DAGCombinerInfo &DCI) {
9457   SelectionDAG &DAG = DCI.DAG;
9458   const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9459                             N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9460   const bool isStore = N->getOpcode() == ISD::STORE;
9461   const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
9462   SDValue Addr = N->getOperand(AddrOpIdx);
9463   MemSDNode *MemN = cast<MemSDNode>(N);
9464   SDLoc dl(N);
9465
9466   // Search for a use of the address operand that is an increment.
9467   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9468          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9469     SDNode *User = *UI;
9470     if (User->getOpcode() != ISD::ADD ||
9471         UI.getUse().getResNo() != Addr.getResNo())
9472       continue;
9473
9474     // Check that the add is independent of the load/store.  Otherwise, folding
9475     // it would create a cycle.
9476     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9477       continue;
9478
9479     // Find the new opcode for the updating load/store.
9480     bool isLoadOp = true;
9481     bool isLaneOp = false;
9482     unsigned NewOpc = 0;
9483     unsigned NumVecs = 0;
9484     if (isIntrinsic) {
9485       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9486       switch (IntNo) {
9487       default: llvm_unreachable("unexpected intrinsic for Neon base update");
9488       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
9489         NumVecs = 1; break;
9490       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
9491         NumVecs = 2; break;
9492       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
9493         NumVecs = 3; break;
9494       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
9495         NumVecs = 4; break;
9496       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9497         NumVecs = 2; isLaneOp = true; break;
9498       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9499         NumVecs = 3; isLaneOp = true; break;
9500       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9501         NumVecs = 4; isLaneOp = true; break;
9502       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
9503         NumVecs = 1; isLoadOp = false; break;
9504       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
9505         NumVecs = 2; isLoadOp = false; break;
9506       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
9507         NumVecs = 3; isLoadOp = false; break;
9508       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
9509         NumVecs = 4; isLoadOp = false; break;
9510       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9511         NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
9512       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9513         NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
9514       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9515         NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
9516       }
9517     } else {
9518       isLaneOp = true;
9519       switch (N->getOpcode()) {
9520       default: llvm_unreachable("unexpected opcode for Neon base update");
9521       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9522       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9523       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9524       case ISD::LOAD:       NewOpc = ARMISD::VLD1_UPD;
9525         NumVecs = 1; isLaneOp = false; break;
9526       case ISD::STORE:      NewOpc = ARMISD::VST1_UPD;
9527         NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
9528       }
9529     }
9530
9531     // Find the size of memory referenced by the load/store.
9532     EVT VecTy;
9533     if (isLoadOp) {
9534       VecTy = N->getValueType(0);
9535     } else if (isIntrinsic) {
9536       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9537     } else {
9538       assert(isStore && "Node has to be a load, a store, or an intrinsic!");
9539       VecTy = N->getOperand(1).getValueType();
9540     }
9541
9542     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9543     if (isLaneOp)
9544       NumBytes /= VecTy.getVectorNumElements();
9545
9546     // If the increment is a constant, it must match the memory ref size.
9547     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9548     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9549       uint64_t IncVal = CInc->getZExtValue();
9550       if (IncVal != NumBytes)
9551         continue;
9552     } else if (NumBytes >= 3 * 16) {
9553       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9554       // separate instructions that make it harder to use a non-constant update.
9555       continue;
9556     }
9557
9558     // OK, we found an ADD we can fold into the base update.
9559     // Now, create a _UPD node, taking care of not breaking alignment.
9560
9561     EVT AlignedVecTy = VecTy;
9562     unsigned Alignment = MemN->getAlignment();
9563
9564     // If this is a less-than-standard-aligned load/store, change the type to
9565     // match the standard alignment.
9566     // The alignment is overlooked when selecting _UPD variants; and it's
9567     // easier to introduce bitcasts here than fix that.
9568     // There are 3 ways to get to this base-update combine:
9569     // - intrinsics: they are assumed to be properly aligned (to the standard
9570     //   alignment of the memory type), so we don't need to do anything.
9571     // - ARMISD::VLDx nodes: they are only generated from the aforementioned
9572     //   intrinsics, so, likewise, there's nothing to do.
9573     // - generic load/store instructions: the alignment is specified as an
9574     //   explicit operand, rather than implicitly as the standard alignment
9575     //   of the memory type (like the intrisics).  We need to change the
9576     //   memory type to match the explicit alignment.  That way, we don't
9577     //   generate non-standard-aligned ARMISD::VLDx nodes.
9578     if (isa<LSBaseSDNode>(N)) {
9579       if (Alignment == 0)
9580         Alignment = 1;
9581       if (Alignment < VecTy.getScalarSizeInBits() / 8) {
9582         MVT EltTy = MVT::getIntegerVT(Alignment * 8);
9583         assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
9584         assert(!isLaneOp && "Unexpected generic load/store lane.");
9585         unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
9586         AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
9587       }
9588       // Don't set an explicit alignment on regular load/stores that we want
9589       // to transform to VLD/VST 1_UPD nodes.
9590       // This matches the behavior of regular load/stores, which only get an
9591       // explicit alignment if the MMO alignment is larger than the standard
9592       // alignment of the memory type.
9593       // Intrinsics, however, always get an explicit alignment, set to the
9594       // alignment of the MMO.
9595       Alignment = 1;
9596     }
9597
9598     // Create the new updating load/store node.
9599     // First, create an SDVTList for the new updating node's results.
9600     EVT Tys[6];
9601     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
9602     unsigned n;
9603     for (n = 0; n < NumResultVecs; ++n)
9604       Tys[n] = AlignedVecTy;
9605     Tys[n++] = MVT::i32;
9606     Tys[n] = MVT::Other;
9607     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
9608
9609     // Then, gather the new node's operands.
9610     SmallVector<SDValue, 8> Ops;
9611     Ops.push_back(N->getOperand(0)); // incoming chain
9612     Ops.push_back(N->getOperand(AddrOpIdx));
9613     Ops.push_back(Inc);
9614
9615     if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
9616       // Try to match the intrinsic's signature
9617       Ops.push_back(StN->getValue());
9618     } else {
9619       // Loads (and of course intrinsics) match the intrinsics' signature,
9620       // so just add all but the alignment operand.
9621       for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
9622         Ops.push_back(N->getOperand(i));
9623     }
9624
9625     // For all node types, the alignment operand is always the last one.
9626     Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
9627
9628     // If this is a non-standard-aligned STORE, the penultimate operand is the
9629     // stored value.  Bitcast it to the aligned type.
9630     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
9631       SDValue &StVal = Ops[Ops.size()-2];
9632       StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
9633     }
9634
9635     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys,
9636                                            Ops, AlignedVecTy,
9637                                            MemN->getMemOperand());
9638
9639     // Update the uses.
9640     SmallVector<SDValue, 5> NewResults;
9641     for (unsigned i = 0; i < NumResultVecs; ++i)
9642       NewResults.push_back(SDValue(UpdN.getNode(), i));
9643
9644     // If this is an non-standard-aligned LOAD, the first result is the loaded
9645     // value.  Bitcast it to the expected result type.
9646     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
9647       SDValue &LdVal = NewResults[0];
9648       LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
9649     }
9650
9651     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9652     DCI.CombineTo(N, NewResults);
9653     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9654
9655     break;
9656   }
9657   return SDValue();
9658 }
9659
9660 static SDValue PerformVLDCombine(SDNode *N,
9661                                  TargetLowering::DAGCombinerInfo &DCI) {
9662   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9663     return SDValue();
9664
9665   return CombineBaseUpdate(N, DCI);
9666 }
9667
9668 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9669 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9670 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
9671 /// return true.
9672 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9673   SelectionDAG &DAG = DCI.DAG;
9674   EVT VT = N->getValueType(0);
9675   // vldN-dup instructions only support 64-bit vectors for N > 1.
9676   if (!VT.is64BitVector())
9677     return false;
9678
9679   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9680   SDNode *VLD = N->getOperand(0).getNode();
9681   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9682     return false;
9683   unsigned NumVecs = 0;
9684   unsigned NewOpc = 0;
9685   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9686   if (IntNo == Intrinsic::arm_neon_vld2lane) {
9687     NumVecs = 2;
9688     NewOpc = ARMISD::VLD2DUP;
9689   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9690     NumVecs = 3;
9691     NewOpc = ARMISD::VLD3DUP;
9692   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9693     NumVecs = 4;
9694     NewOpc = ARMISD::VLD4DUP;
9695   } else {
9696     return false;
9697   }
9698
9699   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9700   // numbers match the load.
9701   unsigned VLDLaneNo =
9702     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9703   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9704        UI != UE; ++UI) {
9705     // Ignore uses of the chain result.
9706     if (UI.getUse().getResNo() == NumVecs)
9707       continue;
9708     SDNode *User = *UI;
9709     if (User->getOpcode() != ARMISD::VDUPLANE ||
9710         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9711       return false;
9712   }
9713
9714   // Create the vldN-dup node.
9715   EVT Tys[5];
9716   unsigned n;
9717   for (n = 0; n < NumVecs; ++n)
9718     Tys[n] = VT;
9719   Tys[n] = MVT::Other;
9720   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9721   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9722   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9723   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9724                                            Ops, VLDMemInt->getMemoryVT(),
9725                                            VLDMemInt->getMemOperand());
9726
9727   // Update the uses.
9728   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9729        UI != UE; ++UI) {
9730     unsigned ResNo = UI.getUse().getResNo();
9731     // Ignore uses of the chain result.
9732     if (ResNo == NumVecs)
9733       continue;
9734     SDNode *User = *UI;
9735     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9736   }
9737
9738   // Now the vldN-lane intrinsic is dead except for its chain result.
9739   // Update uses of the chain.
9740   std::vector<SDValue> VLDDupResults;
9741   for (unsigned n = 0; n < NumVecs; ++n)
9742     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9743   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9744   DCI.CombineTo(VLD, VLDDupResults);
9745
9746   return true;
9747 }
9748
9749 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9750 /// ARMISD::VDUPLANE.
9751 static SDValue PerformVDUPLANECombine(SDNode *N,
9752                                       TargetLowering::DAGCombinerInfo &DCI) {
9753   SDValue Op = N->getOperand(0);
9754
9755   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9756   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9757   if (CombineVLDDUP(N, DCI))
9758     return SDValue(N, 0);
9759
9760   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9761   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9762   while (Op.getOpcode() == ISD::BITCAST)
9763     Op = Op.getOperand(0);
9764   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9765     return SDValue();
9766
9767   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9768   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9769   // The canonical VMOV for a zero vector uses a 32-bit element size.
9770   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9771   unsigned EltBits;
9772   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9773     EltSize = 8;
9774   EVT VT = N->getValueType(0);
9775   if (EltSize > VT.getVectorElementType().getSizeInBits())
9776     return SDValue();
9777
9778   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9779 }
9780
9781 static SDValue PerformLOADCombine(SDNode *N,
9782                                   TargetLowering::DAGCombinerInfo &DCI) {
9783   EVT VT = N->getValueType(0);
9784
9785   // If this is a legal vector load, try to combine it into a VLD1_UPD.
9786   if (ISD::isNormalLoad(N) && VT.isVector() &&
9787       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9788     return CombineBaseUpdate(N, DCI);
9789
9790   return SDValue();
9791 }
9792
9793 /// PerformSTORECombine - Target-specific dag combine xforms for
9794 /// ISD::STORE.
9795 static SDValue PerformSTORECombine(SDNode *N,
9796                                    TargetLowering::DAGCombinerInfo &DCI) {
9797   StoreSDNode *St = cast<StoreSDNode>(N);
9798   if (St->isVolatile())
9799     return SDValue();
9800
9801   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
9802   // pack all of the elements in one place.  Next, store to memory in fewer
9803   // chunks.
9804   SDValue StVal = St->getValue();
9805   EVT VT = StVal.getValueType();
9806   if (St->isTruncatingStore() && VT.isVector()) {
9807     SelectionDAG &DAG = DCI.DAG;
9808     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9809     EVT StVT = St->getMemoryVT();
9810     unsigned NumElems = VT.getVectorNumElements();
9811     assert(StVT != VT && "Cannot truncate to the same type");
9812     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
9813     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
9814
9815     // From, To sizes and ElemCount must be pow of two
9816     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
9817
9818     // We are going to use the original vector elt for storing.
9819     // Accumulated smaller vector elements must be a multiple of the store size.
9820     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
9821
9822     unsigned SizeRatio  = FromEltSz / ToEltSz;
9823     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
9824
9825     // Create a type on which we perform the shuffle.
9826     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9827                                      NumElems*SizeRatio);
9828     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9829
9830     SDLoc DL(St);
9831     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9832     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9833     for (unsigned i = 0; i < NumElems; ++i)
9834       ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
9835                           ? (i + 1) * SizeRatio - 1
9836                           : i * SizeRatio;
9837
9838     // Can't shuffle using an illegal type.
9839     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9840
9841     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9842                                 DAG.getUNDEF(WideVec.getValueType()),
9843                                 ShuffleVec.data());
9844     // At this point all of the data is stored at the bottom of the
9845     // register. We now need to save it to mem.
9846
9847     // Find the largest store unit
9848     MVT StoreType = MVT::i8;
9849     for (MVT Tp : MVT::integer_valuetypes()) {
9850       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9851         StoreType = Tp;
9852     }
9853     // Didn't find a legal store type.
9854     if (!TLI.isTypeLegal(StoreType))
9855       return SDValue();
9856
9857     // Bitcast the original vector into a vector of store-size units
9858     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9859             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9860     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9861     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9862     SmallVector<SDValue, 8> Chains;
9863     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
9864                                         TLI.getPointerTy(DAG.getDataLayout()));
9865     SDValue BasePtr = St->getBasePtr();
9866
9867     // Perform one or more big stores into memory.
9868     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9869     for (unsigned I = 0; I < E; I++) {
9870       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9871                                    StoreType, ShuffWide,
9872                                    DAG.getIntPtrConstant(I, DL));
9873       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9874                                 St->getPointerInfo(), St->isVolatile(),
9875                                 St->isNonTemporal(), St->getAlignment());
9876       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9877                             Increment);
9878       Chains.push_back(Ch);
9879     }
9880     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
9881   }
9882
9883   if (!ISD::isNormalStore(St))
9884     return SDValue();
9885
9886   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9887   // ARM stores of arguments in the same cache line.
9888   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9889       StVal.getNode()->hasOneUse()) {
9890     SelectionDAG  &DAG = DCI.DAG;
9891     bool isBigEndian = DAG.getDataLayout().isBigEndian();
9892     SDLoc DL(St);
9893     SDValue BasePtr = St->getBasePtr();
9894     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9895                                   StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
9896                                   BasePtr, St->getPointerInfo(), St->isVolatile(),
9897                                   St->isNonTemporal(), St->getAlignment());
9898
9899     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9900                                     DAG.getConstant(4, DL, MVT::i32));
9901     return DAG.getStore(NewST1.getValue(0), DL,
9902                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
9903                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9904                         St->isNonTemporal(),
9905                         std::min(4U, St->getAlignment() / 2));
9906   }
9907
9908   if (StVal.getValueType() == MVT::i64 &&
9909       StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9910
9911     // Bitcast an i64 store extracted from a vector to f64.
9912     // Otherwise, the i64 value will be legalized to a pair of i32 values.
9913     SelectionDAG &DAG = DCI.DAG;
9914     SDLoc dl(StVal);
9915     SDValue IntVec = StVal.getOperand(0);
9916     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9917                                    IntVec.getValueType().getVectorNumElements());
9918     SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9919     SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9920                                  Vec, StVal.getOperand(1));
9921     dl = SDLoc(N);
9922     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9923     // Make the DAGCombiner fold the bitcasts.
9924     DCI.AddToWorklist(Vec.getNode());
9925     DCI.AddToWorklist(ExtElt.getNode());
9926     DCI.AddToWorklist(V.getNode());
9927     return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9928                         St->getPointerInfo(), St->isVolatile(),
9929                         St->isNonTemporal(), St->getAlignment(),
9930                         St->getAAInfo());
9931   }
9932
9933   // If this is a legal vector store, try to combine it into a VST1_UPD.
9934   if (ISD::isNormalStore(N) && VT.isVector() &&
9935       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9936     return CombineBaseUpdate(N, DCI);
9937
9938   return SDValue();
9939 }
9940
9941 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9942 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9943 /// when the VMUL has a constant operand that is a power of 2.
9944 ///
9945 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9946 ///  vmul.f32        d16, d17, d16
9947 ///  vcvt.s32.f32    d16, d16
9948 /// becomes:
9949 ///  vcvt.s32.f32    d16, d16, #3
9950 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG,
9951                                   const ARMSubtarget *Subtarget) {
9952   if (!Subtarget->hasNEON())
9953     return SDValue();
9954
9955   SDValue Op = N->getOperand(0);
9956   if (!Op.getValueType().isVector() || Op.getOpcode() != ISD::FMUL)
9957     return SDValue();
9958
9959   SDValue ConstVec = Op->getOperand(1);
9960   if (!isa<BuildVectorSDNode>(ConstVec))
9961     return SDValue();
9962
9963   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9964   uint32_t FloatBits = FloatTy.getSizeInBits();
9965   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9966   uint32_t IntBits = IntTy.getSizeInBits();
9967   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9968   if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
9969     // These instructions only exist converting from f32 to i32. We can handle
9970     // smaller integers by generating an extra truncate, but larger ones would
9971     // be lossy. We also can't handle more then 4 lanes, since these intructions
9972     // only support v2i32/v4i32 types.
9973     return SDValue();
9974   }
9975
9976   BitVector UndefElements;
9977   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
9978   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
9979   if (C == -1 || C == 0 || C > 32)
9980     return SDValue();
9981
9982   SDLoc dl(N);
9983   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9984   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9985     Intrinsic::arm_neon_vcvtfp2fxu;
9986   SDValue FixConv = DAG.getNode(
9987       ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9988       DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0),
9989       DAG.getConstant(C, dl, MVT::i32));
9990
9991   if (IntBits < FloatBits)
9992     FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
9993
9994   return FixConv;
9995 }
9996
9997 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9998 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9999 /// when the VDIV has a constant operand that is a power of 2.
10000 ///
10001 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
10002 ///  vcvt.f32.s32    d16, d16
10003 ///  vdiv.f32        d16, d17, d16
10004 /// becomes:
10005 ///  vcvt.f32.s32    d16, d16, #3
10006 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG,
10007                                   const ARMSubtarget *Subtarget) {
10008   if (!Subtarget->hasNEON())
10009     return SDValue();
10010
10011   SDValue Op = N->getOperand(0);
10012   unsigned OpOpcode = Op.getNode()->getOpcode();
10013   if (!N->getValueType(0).isVector() ||
10014       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
10015     return SDValue();
10016
10017   SDValue ConstVec = N->getOperand(1);
10018   if (!isa<BuildVectorSDNode>(ConstVec))
10019     return SDValue();
10020
10021   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
10022   uint32_t FloatBits = FloatTy.getSizeInBits();
10023   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
10024   uint32_t IntBits = IntTy.getSizeInBits();
10025   unsigned NumLanes = Op.getValueType().getVectorNumElements();
10026   if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
10027     // These instructions only exist converting from i32 to f32. We can handle
10028     // smaller integers by generating an extra extend, but larger ones would
10029     // be lossy. We also can't handle more then 4 lanes, since these intructions
10030     // only support v2i32/v4i32 types.
10031     return SDValue();
10032   }
10033
10034   BitVector UndefElements;
10035   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
10036   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
10037   if (C == -1 || C == 0 || C > 32)
10038     return SDValue();
10039
10040   SDLoc dl(N);
10041   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
10042   SDValue ConvInput = Op.getOperand(0);
10043   if (IntBits < FloatBits)
10044     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
10045                             dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
10046                             ConvInput);
10047
10048   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
10049     Intrinsic::arm_neon_vcvtfxu2fp;
10050   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
10051                      Op.getValueType(),
10052                      DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
10053                      ConvInput, DAG.getConstant(C, dl, MVT::i32));
10054 }
10055
10056 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
10057 /// operand of a vector shift operation, where all the elements of the
10058 /// build_vector must have the same constant integer value.
10059 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
10060   // Ignore bit_converts.
10061   while (Op.getOpcode() == ISD::BITCAST)
10062     Op = Op.getOperand(0);
10063   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
10064   APInt SplatBits, SplatUndef;
10065   unsigned SplatBitSize;
10066   bool HasAnyUndefs;
10067   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
10068                                       HasAnyUndefs, ElementBits) ||
10069       SplatBitSize > ElementBits)
10070     return false;
10071   Cnt = SplatBits.getSExtValue();
10072   return true;
10073 }
10074
10075 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
10076 /// operand of a vector shift left operation.  That value must be in the range:
10077 ///   0 <= Value < ElementBits for a left shift; or
10078 ///   0 <= Value <= ElementBits for a long left shift.
10079 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
10080   assert(VT.isVector() && "vector shift count is not a vector type");
10081   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
10082   if (! getVShiftImm(Op, ElementBits, Cnt))
10083     return false;
10084   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
10085 }
10086
10087 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
10088 /// operand of a vector shift right operation.  For a shift opcode, the value
10089 /// is positive, but for an intrinsic the value count must be negative. The
10090 /// absolute value must be in the range:
10091 ///   1 <= |Value| <= ElementBits for a right shift; or
10092 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
10093 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
10094                          int64_t &Cnt) {
10095   assert(VT.isVector() && "vector shift count is not a vector type");
10096   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
10097   if (! getVShiftImm(Op, ElementBits, Cnt))
10098     return false;
10099   if (!isIntrinsic)
10100     return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
10101   if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) {
10102     Cnt = -Cnt;
10103     return true;
10104   }
10105   return false;
10106 }
10107
10108 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
10109 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
10110   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
10111   switch (IntNo) {
10112   default:
10113     // Don't do anything for most intrinsics.
10114     break;
10115
10116   case Intrinsic::arm_neon_vabds:
10117     if (!N->getValueType(0).isInteger())
10118       return SDValue();
10119     return DAG.getNode(ISD::SABSDIFF, SDLoc(N), N->getValueType(0),
10120                        N->getOperand(1), N->getOperand(2));
10121   case Intrinsic::arm_neon_vabdu:
10122     return DAG.getNode(ISD::UABSDIFF, SDLoc(N), N->getValueType(0),
10123                        N->getOperand(1), N->getOperand(2));
10124
10125   // Vector shifts: check for immediate versions and lower them.
10126   // Note: This is done during DAG combining instead of DAG legalizing because
10127   // the build_vectors for 64-bit vector element shift counts are generally
10128   // not legal, and it is hard to see their values after they get legalized to
10129   // loads from a constant pool.
10130   case Intrinsic::arm_neon_vshifts:
10131   case Intrinsic::arm_neon_vshiftu:
10132   case Intrinsic::arm_neon_vrshifts:
10133   case Intrinsic::arm_neon_vrshiftu:
10134   case Intrinsic::arm_neon_vrshiftn:
10135   case Intrinsic::arm_neon_vqshifts:
10136   case Intrinsic::arm_neon_vqshiftu:
10137   case Intrinsic::arm_neon_vqshiftsu:
10138   case Intrinsic::arm_neon_vqshiftns:
10139   case Intrinsic::arm_neon_vqshiftnu:
10140   case Intrinsic::arm_neon_vqshiftnsu:
10141   case Intrinsic::arm_neon_vqrshiftns:
10142   case Intrinsic::arm_neon_vqrshiftnu:
10143   case Intrinsic::arm_neon_vqrshiftnsu: {
10144     EVT VT = N->getOperand(1).getValueType();
10145     int64_t Cnt;
10146     unsigned VShiftOpc = 0;
10147
10148     switch (IntNo) {
10149     case Intrinsic::arm_neon_vshifts:
10150     case Intrinsic::arm_neon_vshiftu:
10151       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
10152         VShiftOpc = ARMISD::VSHL;
10153         break;
10154       }
10155       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
10156         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
10157                      ARMISD::VSHRs : ARMISD::VSHRu);
10158         break;
10159       }
10160       return SDValue();
10161
10162     case Intrinsic::arm_neon_vrshifts:
10163     case Intrinsic::arm_neon_vrshiftu:
10164       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
10165         break;
10166       return SDValue();
10167
10168     case Intrinsic::arm_neon_vqshifts:
10169     case Intrinsic::arm_neon_vqshiftu:
10170       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
10171         break;
10172       return SDValue();
10173
10174     case Intrinsic::arm_neon_vqshiftsu:
10175       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
10176         break;
10177       llvm_unreachable("invalid shift count for vqshlu intrinsic");
10178
10179     case Intrinsic::arm_neon_vrshiftn:
10180     case Intrinsic::arm_neon_vqshiftns:
10181     case Intrinsic::arm_neon_vqshiftnu:
10182     case Intrinsic::arm_neon_vqshiftnsu:
10183     case Intrinsic::arm_neon_vqrshiftns:
10184     case Intrinsic::arm_neon_vqrshiftnu:
10185     case Intrinsic::arm_neon_vqrshiftnsu:
10186       // Narrowing shifts require an immediate right shift.
10187       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
10188         break;
10189       llvm_unreachable("invalid shift count for narrowing vector shift "
10190                        "intrinsic");
10191
10192     default:
10193       llvm_unreachable("unhandled vector shift");
10194     }
10195
10196     switch (IntNo) {
10197     case Intrinsic::arm_neon_vshifts:
10198     case Intrinsic::arm_neon_vshiftu:
10199       // Opcode already set above.
10200       break;
10201     case Intrinsic::arm_neon_vrshifts:
10202       VShiftOpc = ARMISD::VRSHRs; break;
10203     case Intrinsic::arm_neon_vrshiftu:
10204       VShiftOpc = ARMISD::VRSHRu; break;
10205     case Intrinsic::arm_neon_vrshiftn:
10206       VShiftOpc = ARMISD::VRSHRN; break;
10207     case Intrinsic::arm_neon_vqshifts:
10208       VShiftOpc = ARMISD::VQSHLs; break;
10209     case Intrinsic::arm_neon_vqshiftu:
10210       VShiftOpc = ARMISD::VQSHLu; break;
10211     case Intrinsic::arm_neon_vqshiftsu:
10212       VShiftOpc = ARMISD::VQSHLsu; break;
10213     case Intrinsic::arm_neon_vqshiftns:
10214       VShiftOpc = ARMISD::VQSHRNs; break;
10215     case Intrinsic::arm_neon_vqshiftnu:
10216       VShiftOpc = ARMISD::VQSHRNu; break;
10217     case Intrinsic::arm_neon_vqshiftnsu:
10218       VShiftOpc = ARMISD::VQSHRNsu; break;
10219     case Intrinsic::arm_neon_vqrshiftns:
10220       VShiftOpc = ARMISD::VQRSHRNs; break;
10221     case Intrinsic::arm_neon_vqrshiftnu:
10222       VShiftOpc = ARMISD::VQRSHRNu; break;
10223     case Intrinsic::arm_neon_vqrshiftnsu:
10224       VShiftOpc = ARMISD::VQRSHRNsu; break;
10225     }
10226
10227     SDLoc dl(N);
10228     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
10229                        N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
10230   }
10231
10232   case Intrinsic::arm_neon_vshiftins: {
10233     EVT VT = N->getOperand(1).getValueType();
10234     int64_t Cnt;
10235     unsigned VShiftOpc = 0;
10236
10237     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
10238       VShiftOpc = ARMISD::VSLI;
10239     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
10240       VShiftOpc = ARMISD::VSRI;
10241     else {
10242       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
10243     }
10244
10245     SDLoc dl(N);
10246     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
10247                        N->getOperand(1), N->getOperand(2),
10248                        DAG.getConstant(Cnt, dl, MVT::i32));
10249   }
10250
10251   case Intrinsic::arm_neon_vqrshifts:
10252   case Intrinsic::arm_neon_vqrshiftu:
10253     // No immediate versions of these to check for.
10254     break;
10255   }
10256
10257   return SDValue();
10258 }
10259
10260 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
10261 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
10262 /// combining instead of DAG legalizing because the build_vectors for 64-bit
10263 /// vector element shift counts are generally not legal, and it is hard to see
10264 /// their values after they get legalized to loads from a constant pool.
10265 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
10266                                    const ARMSubtarget *ST) {
10267   EVT VT = N->getValueType(0);
10268   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
10269     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
10270     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
10271     SDValue N1 = N->getOperand(1);
10272     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
10273       SDValue N0 = N->getOperand(0);
10274       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
10275           DAG.MaskedValueIsZero(N0.getOperand(0),
10276                                 APInt::getHighBitsSet(32, 16)))
10277         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
10278     }
10279   }
10280
10281   // Nothing to be done for scalar shifts.
10282   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10283   if (!VT.isVector() || !TLI.isTypeLegal(VT))
10284     return SDValue();
10285
10286   assert(ST->hasNEON() && "unexpected vector shift");
10287   int64_t Cnt;
10288
10289   switch (N->getOpcode()) {
10290   default: llvm_unreachable("unexpected shift opcode");
10291
10292   case ISD::SHL:
10293     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
10294       SDLoc dl(N);
10295       return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
10296                          DAG.getConstant(Cnt, dl, MVT::i32));
10297     }
10298     break;
10299
10300   case ISD::SRA:
10301   case ISD::SRL:
10302     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
10303       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
10304                             ARMISD::VSHRs : ARMISD::VSHRu);
10305       SDLoc dl(N);
10306       return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
10307                          DAG.getConstant(Cnt, dl, MVT::i32));
10308     }
10309   }
10310   return SDValue();
10311 }
10312
10313 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
10314 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
10315 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
10316                                     const ARMSubtarget *ST) {
10317   SDValue N0 = N->getOperand(0);
10318
10319   // Check for sign- and zero-extensions of vector extract operations of 8-
10320   // and 16-bit vector elements.  NEON supports these directly.  They are
10321   // handled during DAG combining because type legalization will promote them
10322   // to 32-bit types and it is messy to recognize the operations after that.
10323   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
10324     SDValue Vec = N0.getOperand(0);
10325     SDValue Lane = N0.getOperand(1);
10326     EVT VT = N->getValueType(0);
10327     EVT EltVT = N0.getValueType();
10328     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10329
10330     if (VT == MVT::i32 &&
10331         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
10332         TLI.isTypeLegal(Vec.getValueType()) &&
10333         isa<ConstantSDNode>(Lane)) {
10334
10335       unsigned Opc = 0;
10336       switch (N->getOpcode()) {
10337       default: llvm_unreachable("unexpected opcode");
10338       case ISD::SIGN_EXTEND:
10339         Opc = ARMISD::VGETLANEs;
10340         break;
10341       case ISD::ZERO_EXTEND:
10342       case ISD::ANY_EXTEND:
10343         Opc = ARMISD::VGETLANEu;
10344         break;
10345       }
10346       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
10347     }
10348   }
10349
10350   return SDValue();
10351 }
10352
10353 static void computeKnownBits(SelectionDAG &DAG, SDValue Op, APInt &KnownZero,
10354                              APInt &KnownOne) {
10355   if (Op.getOpcode() == ARMISD::BFI) {
10356     // Conservatively, we can recurse down the first operand
10357     // and just mask out all affected bits.
10358     computeKnownBits(DAG, Op.getOperand(0), KnownZero, KnownOne);
10359
10360     // The operand to BFI is already a mask suitable for removing the bits it
10361     // sets.
10362     ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2));
10363     APInt Mask = CI->getAPIntValue();
10364     KnownZero &= Mask;
10365     KnownOne &= Mask;
10366     return;
10367   }
10368   if (Op.getOpcode() == ARMISD::CMOV) {
10369     APInt KZ2(KnownZero.getBitWidth(), 0);
10370     APInt KO2(KnownOne.getBitWidth(), 0);
10371     computeKnownBits(DAG, Op.getOperand(1), KnownZero, KnownOne);
10372     computeKnownBits(DAG, Op.getOperand(2), KZ2, KO2);
10373
10374     KnownZero &= KZ2;
10375     KnownOne &= KO2;
10376     return;
10377   }
10378   return DAG.computeKnownBits(Op, KnownZero, KnownOne);
10379 }
10380
10381 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const {
10382   // If we have a CMOV, OR and AND combination such as:
10383   //   if (x & CN)
10384   //     y |= CM;
10385   //
10386   // And:
10387   //   * CN is a single bit;
10388   //   * All bits covered by CM are known zero in y
10389   //
10390   // Then we can convert this into a sequence of BFI instructions. This will
10391   // always be a win if CM is a single bit, will always be no worse than the
10392   // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is
10393   // three bits (due to the extra IT instruction).
10394
10395   SDValue Op0 = CMOV->getOperand(0);
10396   SDValue Op1 = CMOV->getOperand(1);
10397   auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2));
10398   auto CC = CCNode->getAPIntValue().getLimitedValue();
10399   SDValue CmpZ = CMOV->getOperand(4);
10400
10401   assert(CmpZ->getOpcode() == ARMISD::CMPZ);
10402   SDValue And = CmpZ->getOperand(0);
10403   if (And->getOpcode() != ISD::AND)
10404     return SDValue();
10405   ConstantSDNode *AndC = dyn_cast<ConstantSDNode>(And->getOperand(1));
10406   if (!AndC || !AndC->getAPIntValue().isPowerOf2())
10407     return SDValue();
10408   SDValue X = And->getOperand(0);
10409
10410   if (CC == ARMCC::EQ) {
10411     // We're performing an "equal to zero" compare. Swap the operands so we
10412     // canonicalize on a "not equal to zero" compare.
10413     std::swap(Op0, Op1);
10414   } else {
10415     assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?");
10416   }
10417   
10418   if (Op1->getOpcode() != ISD::OR)
10419     return SDValue();
10420
10421   ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1));
10422   if (!OrC)
10423     return SDValue();
10424   SDValue Y = Op1->getOperand(0);
10425
10426   if (Op0 != Y)
10427     return SDValue();
10428
10429   // Now, is it profitable to continue?
10430   APInt OrCI = OrC->getAPIntValue();
10431   unsigned Heuristic = Subtarget->isThumb() ? 3 : 2;
10432   if (OrCI.countPopulation() > Heuristic)
10433     return SDValue();
10434
10435   // Lastly, can we determine that the bits defined by OrCI
10436   // are zero in Y?
10437   APInt KnownZero, KnownOne;
10438   computeKnownBits(DAG, Y, KnownZero, KnownOne);
10439   if ((OrCI & KnownZero) != OrCI)
10440     return SDValue();
10441
10442   // OK, we can do the combine.
10443   SDValue V = Y;
10444   SDLoc dl(X);
10445   EVT VT = X.getValueType();
10446   unsigned BitInX = AndC->getAPIntValue().logBase2();
10447   
10448   if (BitInX != 0) {
10449     // We must shift X first.
10450     X = DAG.getNode(ISD::SRL, dl, VT, X,
10451                     DAG.getConstant(BitInX, dl, VT));
10452   }
10453
10454   for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits();
10455        BitInY < NumActiveBits; ++BitInY) {
10456     if (OrCI[BitInY] == 0)
10457       continue;
10458     APInt Mask(VT.getSizeInBits(), 0);
10459     Mask.setBit(BitInY);
10460     V = DAG.getNode(ARMISD::BFI, dl, VT, V, X,
10461                     // Confusingly, the operand is an *inverted* mask.
10462                     DAG.getConstant(~Mask, dl, VT));
10463   }
10464
10465   return V;
10466 }
10467
10468 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
10469 SDValue
10470 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
10471   SDValue Cmp = N->getOperand(4);
10472   if (Cmp.getOpcode() != ARMISD::CMPZ)
10473     // Only looking at EQ and NE cases.
10474     return SDValue();
10475
10476   EVT VT = N->getValueType(0);
10477   SDLoc dl(N);
10478   SDValue LHS = Cmp.getOperand(0);
10479   SDValue RHS = Cmp.getOperand(1);
10480   SDValue FalseVal = N->getOperand(0);
10481   SDValue TrueVal = N->getOperand(1);
10482   SDValue ARMcc = N->getOperand(2);
10483   ARMCC::CondCodes CC =
10484     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
10485
10486   // BFI is only available on V6T2+.
10487   if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) {
10488     SDValue R = PerformCMOVToBFICombine(N, DAG);
10489     if (R)
10490       return R;
10491   }
10492
10493   // Simplify
10494   //   mov     r1, r0
10495   //   cmp     r1, x
10496   //   mov     r0, y
10497   //   moveq   r0, x
10498   // to
10499   //   cmp     r0, x
10500   //   movne   r0, y
10501   //
10502   //   mov     r1, r0
10503   //   cmp     r1, x
10504   //   mov     r0, x
10505   //   movne   r0, y
10506   // to
10507   //   cmp     r0, x
10508   //   movne   r0, y
10509   /// FIXME: Turn this into a target neutral optimization?
10510   SDValue Res;
10511   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
10512     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
10513                       N->getOperand(3), Cmp);
10514   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
10515     SDValue ARMcc;
10516     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
10517     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
10518                       N->getOperand(3), NewCmp);
10519   }
10520
10521   if (Res.getNode()) {
10522     APInt KnownZero, KnownOne;
10523     DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
10524     // Capture demanded bits information that would be otherwise lost.
10525     if (KnownZero == 0xfffffffe)
10526       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10527                         DAG.getValueType(MVT::i1));
10528     else if (KnownZero == 0xffffff00)
10529       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10530                         DAG.getValueType(MVT::i8));
10531     else if (KnownZero == 0xffff0000)
10532       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10533                         DAG.getValueType(MVT::i16));
10534   }
10535
10536   return Res;
10537 }
10538
10539 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
10540                                              DAGCombinerInfo &DCI) const {
10541   switch (N->getOpcode()) {
10542   default: break;
10543   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
10544   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
10545   case ISD::SUB:        return PerformSUBCombine(N, DCI);
10546   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
10547   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
10548   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
10549   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
10550   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
10551   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
10552   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
10553   case ISD::STORE:      return PerformSTORECombine(N, DCI);
10554   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
10555   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
10556   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
10557   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
10558   case ISD::FP_TO_SINT:
10559   case ISD::FP_TO_UINT:
10560     return PerformVCVTCombine(N, DCI.DAG, Subtarget);
10561   case ISD::FDIV:
10562     return PerformVDIVCombine(N, DCI.DAG, Subtarget);
10563   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
10564   case ISD::SHL:
10565   case ISD::SRA:
10566   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
10567   case ISD::SIGN_EXTEND:
10568   case ISD::ZERO_EXTEND:
10569   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
10570   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
10571   case ISD::LOAD:       return PerformLOADCombine(N, DCI);
10572   case ARMISD::VLD2DUP:
10573   case ARMISD::VLD3DUP:
10574   case ARMISD::VLD4DUP:
10575     return PerformVLDCombine(N, DCI);
10576   case ARMISD::BUILD_VECTOR:
10577     return PerformARMBUILD_VECTORCombine(N, DCI);
10578   case ISD::INTRINSIC_VOID:
10579   case ISD::INTRINSIC_W_CHAIN:
10580     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10581     case Intrinsic::arm_neon_vld1:
10582     case Intrinsic::arm_neon_vld2:
10583     case Intrinsic::arm_neon_vld3:
10584     case Intrinsic::arm_neon_vld4:
10585     case Intrinsic::arm_neon_vld2lane:
10586     case Intrinsic::arm_neon_vld3lane:
10587     case Intrinsic::arm_neon_vld4lane:
10588     case Intrinsic::arm_neon_vst1:
10589     case Intrinsic::arm_neon_vst2:
10590     case Intrinsic::arm_neon_vst3:
10591     case Intrinsic::arm_neon_vst4:
10592     case Intrinsic::arm_neon_vst2lane:
10593     case Intrinsic::arm_neon_vst3lane:
10594     case Intrinsic::arm_neon_vst4lane:
10595       return PerformVLDCombine(N, DCI);
10596     default: break;
10597     }
10598     break;
10599   }
10600   return SDValue();
10601 }
10602
10603 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
10604                                                           EVT VT) const {
10605   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
10606 }
10607
10608 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
10609                                                        unsigned,
10610                                                        unsigned,
10611                                                        bool *Fast) const {
10612   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
10613   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
10614
10615   switch (VT.getSimpleVT().SimpleTy) {
10616   default:
10617     return false;
10618   case MVT::i8:
10619   case MVT::i16:
10620   case MVT::i32: {
10621     // Unaligned access can use (for example) LRDB, LRDH, LDR
10622     if (AllowsUnaligned) {
10623       if (Fast)
10624         *Fast = Subtarget->hasV7Ops();
10625       return true;
10626     }
10627     return false;
10628   }
10629   case MVT::f64:
10630   case MVT::v2f64: {
10631     // For any little-endian targets with neon, we can support unaligned ld/st
10632     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10633     // A big-endian target may also explicitly support unaligned accesses
10634     if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
10635       if (Fast)
10636         *Fast = true;
10637       return true;
10638     }
10639     return false;
10640   }
10641   }
10642 }
10643
10644 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10645                        unsigned AlignCheck) {
10646   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10647           (DstAlign == 0 || DstAlign % AlignCheck == 0));
10648 }
10649
10650 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10651                                            unsigned DstAlign, unsigned SrcAlign,
10652                                            bool IsMemset, bool ZeroMemset,
10653                                            bool MemcpyStrSrc,
10654                                            MachineFunction &MF) const {
10655   const Function *F = MF.getFunction();
10656
10657   // See if we can use NEON instructions for this...
10658   if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
10659       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10660     bool Fast;
10661     if (Size >= 16 &&
10662         (memOpAlign(SrcAlign, DstAlign, 16) ||
10663          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
10664       return MVT::v2f64;
10665     } else if (Size >= 8 &&
10666                (memOpAlign(SrcAlign, DstAlign, 8) ||
10667                 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
10668                  Fast))) {
10669       return MVT::f64;
10670     }
10671   }
10672
10673   // Lowering to i32/i16 if the size permits.
10674   if (Size >= 4)
10675     return MVT::i32;
10676   else if (Size >= 2)
10677     return MVT::i16;
10678
10679   // Let the target-independent logic figure it out.
10680   return MVT::Other;
10681 }
10682
10683 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10684   if (Val.getOpcode() != ISD::LOAD)
10685     return false;
10686
10687   EVT VT1 = Val.getValueType();
10688   if (!VT1.isSimple() || !VT1.isInteger() ||
10689       !VT2.isSimple() || !VT2.isInteger())
10690     return false;
10691
10692   switch (VT1.getSimpleVT().SimpleTy) {
10693   default: break;
10694   case MVT::i1:
10695   case MVT::i8:
10696   case MVT::i16:
10697     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10698     return true;
10699   }
10700
10701   return false;
10702 }
10703
10704 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
10705   EVT VT = ExtVal.getValueType();
10706
10707   if (!isTypeLegal(VT))
10708     return false;
10709
10710   // Don't create a loadext if we can fold the extension into a wide/long
10711   // instruction.
10712   // If there's more than one user instruction, the loadext is desirable no
10713   // matter what.  There can be two uses by the same instruction.
10714   if (ExtVal->use_empty() ||
10715       !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
10716     return true;
10717
10718   SDNode *U = *ExtVal->use_begin();
10719   if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
10720        U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
10721     return false;
10722
10723   return true;
10724 }
10725
10726 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10727   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10728     return false;
10729
10730   if (!isTypeLegal(EVT::getEVT(Ty1)))
10731     return false;
10732
10733   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10734
10735   // Assuming the caller doesn't have a zeroext or signext return parameter,
10736   // truncation all the way down to i1 is valid.
10737   return true;
10738 }
10739
10740
10741 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10742   if (V < 0)
10743     return false;
10744
10745   unsigned Scale = 1;
10746   switch (VT.getSimpleVT().SimpleTy) {
10747   default: return false;
10748   case MVT::i1:
10749   case MVT::i8:
10750     // Scale == 1;
10751     break;
10752   case MVT::i16:
10753     // Scale == 2;
10754     Scale = 2;
10755     break;
10756   case MVT::i32:
10757     // Scale == 4;
10758     Scale = 4;
10759     break;
10760   }
10761
10762   if ((V & (Scale - 1)) != 0)
10763     return false;
10764   V /= Scale;
10765   return V == (V & ((1LL << 5) - 1));
10766 }
10767
10768 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10769                                       const ARMSubtarget *Subtarget) {
10770   bool isNeg = false;
10771   if (V < 0) {
10772     isNeg = true;
10773     V = - V;
10774   }
10775
10776   switch (VT.getSimpleVT().SimpleTy) {
10777   default: return false;
10778   case MVT::i1:
10779   case MVT::i8:
10780   case MVT::i16:
10781   case MVT::i32:
10782     // + imm12 or - imm8
10783     if (isNeg)
10784       return V == (V & ((1LL << 8) - 1));
10785     return V == (V & ((1LL << 12) - 1));
10786   case MVT::f32:
10787   case MVT::f64:
10788     // Same as ARM mode. FIXME: NEON?
10789     if (!Subtarget->hasVFP2())
10790       return false;
10791     if ((V & 3) != 0)
10792       return false;
10793     V >>= 2;
10794     return V == (V & ((1LL << 8) - 1));
10795   }
10796 }
10797
10798 /// isLegalAddressImmediate - Return true if the integer value can be used
10799 /// as the offset of the target addressing mode for load / store of the
10800 /// given type.
10801 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10802                                     const ARMSubtarget *Subtarget) {
10803   if (V == 0)
10804     return true;
10805
10806   if (!VT.isSimple())
10807     return false;
10808
10809   if (Subtarget->isThumb1Only())
10810     return isLegalT1AddressImmediate(V, VT);
10811   else if (Subtarget->isThumb2())
10812     return isLegalT2AddressImmediate(V, VT, Subtarget);
10813
10814   // ARM mode.
10815   if (V < 0)
10816     V = - V;
10817   switch (VT.getSimpleVT().SimpleTy) {
10818   default: return false;
10819   case MVT::i1:
10820   case MVT::i8:
10821   case MVT::i32:
10822     // +- imm12
10823     return V == (V & ((1LL << 12) - 1));
10824   case MVT::i16:
10825     // +- imm8
10826     return V == (V & ((1LL << 8) - 1));
10827   case MVT::f32:
10828   case MVT::f64:
10829     if (!Subtarget->hasVFP2()) // FIXME: NEON?
10830       return false;
10831     if ((V & 3) != 0)
10832       return false;
10833     V >>= 2;
10834     return V == (V & ((1LL << 8) - 1));
10835   }
10836 }
10837
10838 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10839                                                       EVT VT) const {
10840   int Scale = AM.Scale;
10841   if (Scale < 0)
10842     return false;
10843
10844   switch (VT.getSimpleVT().SimpleTy) {
10845   default: return false;
10846   case MVT::i1:
10847   case MVT::i8:
10848   case MVT::i16:
10849   case MVT::i32:
10850     if (Scale == 1)
10851       return true;
10852     // r + r << imm
10853     Scale = Scale & ~1;
10854     return Scale == 2 || Scale == 4 || Scale == 8;
10855   case MVT::i64:
10856     // r + r
10857     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10858       return true;
10859     return false;
10860   case MVT::isVoid:
10861     // Note, we allow "void" uses (basically, uses that aren't loads or
10862     // stores), because arm allows folding a scale into many arithmetic
10863     // operations.  This should be made more precise and revisited later.
10864
10865     // Allow r << imm, but the imm has to be a multiple of two.
10866     if (Scale & 1) return false;
10867     return isPowerOf2_32(Scale);
10868   }
10869 }
10870
10871 /// isLegalAddressingMode - Return true if the addressing mode represented
10872 /// by AM is legal for this target, for a load/store of the specified type.
10873 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
10874                                               const AddrMode &AM, Type *Ty,
10875                                               unsigned AS) const {
10876   EVT VT = getValueType(DL, Ty, true);
10877   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10878     return false;
10879
10880   // Can never fold addr of global into load/store.
10881   if (AM.BaseGV)
10882     return false;
10883
10884   switch (AM.Scale) {
10885   case 0:  // no scale reg, must be "r+i" or "r", or "i".
10886     break;
10887   case 1:
10888     if (Subtarget->isThumb1Only())
10889       return false;
10890     // FALL THROUGH.
10891   default:
10892     // ARM doesn't support any R+R*scale+imm addr modes.
10893     if (AM.BaseOffs)
10894       return false;
10895
10896     if (!VT.isSimple())
10897       return false;
10898
10899     if (Subtarget->isThumb2())
10900       return isLegalT2ScaledAddressingMode(AM, VT);
10901
10902     int Scale = AM.Scale;
10903     switch (VT.getSimpleVT().SimpleTy) {
10904     default: return false;
10905     case MVT::i1:
10906     case MVT::i8:
10907     case MVT::i32:
10908       if (Scale < 0) Scale = -Scale;
10909       if (Scale == 1)
10910         return true;
10911       // r + r << imm
10912       return isPowerOf2_32(Scale & ~1);
10913     case MVT::i16:
10914     case MVT::i64:
10915       // r + r
10916       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10917         return true;
10918       return false;
10919
10920     case MVT::isVoid:
10921       // Note, we allow "void" uses (basically, uses that aren't loads or
10922       // stores), because arm allows folding a scale into many arithmetic
10923       // operations.  This should be made more precise and revisited later.
10924
10925       // Allow r << imm, but the imm has to be a multiple of two.
10926       if (Scale & 1) return false;
10927       return isPowerOf2_32(Scale);
10928     }
10929   }
10930   return true;
10931 }
10932
10933 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10934 /// icmp immediate, that is the target has icmp instructions which can compare
10935 /// a register against the immediate without having to materialize the
10936 /// immediate into a register.
10937 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10938   // Thumb2 and ARM modes can use cmn for negative immediates.
10939   if (!Subtarget->isThumb())
10940     return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
10941   if (Subtarget->isThumb2())
10942     return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
10943   // Thumb1 doesn't have cmn, and only 8-bit immediates.
10944   return Imm >= 0 && Imm <= 255;
10945 }
10946
10947 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10948 /// *or sub* immediate, that is the target has add or sub instructions which can
10949 /// add a register with the immediate without having to materialize the
10950 /// immediate into a register.
10951 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10952   // Same encoding for add/sub, just flip the sign.
10953   int64_t AbsImm = std::abs(Imm);
10954   if (!Subtarget->isThumb())
10955     return ARM_AM::getSOImmVal(AbsImm) != -1;
10956   if (Subtarget->isThumb2())
10957     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10958   // Thumb1 only has 8-bit unsigned immediate.
10959   return AbsImm >= 0 && AbsImm <= 255;
10960 }
10961
10962 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10963                                       bool isSEXTLoad, SDValue &Base,
10964                                       SDValue &Offset, bool &isInc,
10965                                       SelectionDAG &DAG) {
10966   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10967     return false;
10968
10969   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10970     // AddressingMode 3
10971     Base = Ptr->getOperand(0);
10972     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10973       int RHSC = (int)RHS->getZExtValue();
10974       if (RHSC < 0 && RHSC > -256) {
10975         assert(Ptr->getOpcode() == ISD::ADD);
10976         isInc = false;
10977         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10978         return true;
10979       }
10980     }
10981     isInc = (Ptr->getOpcode() == ISD::ADD);
10982     Offset = Ptr->getOperand(1);
10983     return true;
10984   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10985     // AddressingMode 2
10986     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10987       int RHSC = (int)RHS->getZExtValue();
10988       if (RHSC < 0 && RHSC > -0x1000) {
10989         assert(Ptr->getOpcode() == ISD::ADD);
10990         isInc = false;
10991         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10992         Base = Ptr->getOperand(0);
10993         return true;
10994       }
10995     }
10996
10997     if (Ptr->getOpcode() == ISD::ADD) {
10998       isInc = true;
10999       ARM_AM::ShiftOpc ShOpcVal=
11000         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
11001       if (ShOpcVal != ARM_AM::no_shift) {
11002         Base = Ptr->getOperand(1);
11003         Offset = Ptr->getOperand(0);
11004       } else {
11005         Base = Ptr->getOperand(0);
11006         Offset = Ptr->getOperand(1);
11007       }
11008       return true;
11009     }
11010
11011     isInc = (Ptr->getOpcode() == ISD::ADD);
11012     Base = Ptr->getOperand(0);
11013     Offset = Ptr->getOperand(1);
11014     return true;
11015   }
11016
11017   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
11018   return false;
11019 }
11020
11021 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
11022                                      bool isSEXTLoad, SDValue &Base,
11023                                      SDValue &Offset, bool &isInc,
11024                                      SelectionDAG &DAG) {
11025   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
11026     return false;
11027
11028   Base = Ptr->getOperand(0);
11029   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
11030     int RHSC = (int)RHS->getZExtValue();
11031     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
11032       assert(Ptr->getOpcode() == ISD::ADD);
11033       isInc = false;
11034       Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
11035       return true;
11036     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
11037       isInc = Ptr->getOpcode() == ISD::ADD;
11038       Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
11039       return true;
11040     }
11041   }
11042
11043   return false;
11044 }
11045
11046 /// getPreIndexedAddressParts - returns true by value, base pointer and
11047 /// offset pointer and addressing mode by reference if the node's address
11048 /// can be legally represented as pre-indexed load / store address.
11049 bool
11050 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
11051                                              SDValue &Offset,
11052                                              ISD::MemIndexedMode &AM,
11053                                              SelectionDAG &DAG) const {
11054   if (Subtarget->isThumb1Only())
11055     return false;
11056
11057   EVT VT;
11058   SDValue Ptr;
11059   bool isSEXTLoad = false;
11060   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11061     Ptr = LD->getBasePtr();
11062     VT  = LD->getMemoryVT();
11063     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
11064   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11065     Ptr = ST->getBasePtr();
11066     VT  = ST->getMemoryVT();
11067   } else
11068     return false;
11069
11070   bool isInc;
11071   bool isLegal = false;
11072   if (Subtarget->isThumb2())
11073     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
11074                                        Offset, isInc, DAG);
11075   else
11076     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
11077                                         Offset, isInc, DAG);
11078   if (!isLegal)
11079     return false;
11080
11081   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
11082   return true;
11083 }
11084
11085 /// getPostIndexedAddressParts - returns true by value, base pointer and
11086 /// offset pointer and addressing mode by reference if this node can be
11087 /// combined with a load / store to form a post-indexed load / store.
11088 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
11089                                                    SDValue &Base,
11090                                                    SDValue &Offset,
11091                                                    ISD::MemIndexedMode &AM,
11092                                                    SelectionDAG &DAG) const {
11093   if (Subtarget->isThumb1Only())
11094     return false;
11095
11096   EVT VT;
11097   SDValue Ptr;
11098   bool isSEXTLoad = false;
11099   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11100     VT  = LD->getMemoryVT();
11101     Ptr = LD->getBasePtr();
11102     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
11103   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11104     VT  = ST->getMemoryVT();
11105     Ptr = ST->getBasePtr();
11106   } else
11107     return false;
11108
11109   bool isInc;
11110   bool isLegal = false;
11111   if (Subtarget->isThumb2())
11112     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
11113                                        isInc, DAG);
11114   else
11115     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
11116                                         isInc, DAG);
11117   if (!isLegal)
11118     return false;
11119
11120   if (Ptr != Base) {
11121     // Swap base ptr and offset to catch more post-index load / store when
11122     // it's legal. In Thumb2 mode, offset must be an immediate.
11123     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
11124         !Subtarget->isThumb2())
11125       std::swap(Base, Offset);
11126
11127     // Post-indexed load / store update the base pointer.
11128     if (Ptr != Base)
11129       return false;
11130   }
11131
11132   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
11133   return true;
11134 }
11135
11136 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
11137                                                       APInt &KnownZero,
11138                                                       APInt &KnownOne,
11139                                                       const SelectionDAG &DAG,
11140                                                       unsigned Depth) const {
11141   unsigned BitWidth = KnownOne.getBitWidth();
11142   KnownZero = KnownOne = APInt(BitWidth, 0);
11143   switch (Op.getOpcode()) {
11144   default: break;
11145   case ARMISD::ADDC:
11146   case ARMISD::ADDE:
11147   case ARMISD::SUBC:
11148   case ARMISD::SUBE:
11149     // These nodes' second result is a boolean
11150     if (Op.getResNo() == 0)
11151       break;
11152     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
11153     break;
11154   case ARMISD::CMOV: {
11155     // Bits are known zero/one if known on the LHS and RHS.
11156     DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
11157     if (KnownZero == 0 && KnownOne == 0) return;
11158
11159     APInt KnownZeroRHS, KnownOneRHS;
11160     DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
11161     KnownZero &= KnownZeroRHS;
11162     KnownOne  &= KnownOneRHS;
11163     return;
11164   }
11165   case ISD::INTRINSIC_W_CHAIN: {
11166     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
11167     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
11168     switch (IntID) {
11169     default: return;
11170     case Intrinsic::arm_ldaex:
11171     case Intrinsic::arm_ldrex: {
11172       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
11173       unsigned MemBits = VT.getScalarType().getSizeInBits();
11174       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
11175       return;
11176     }
11177     }
11178   }
11179   }
11180 }
11181
11182 //===----------------------------------------------------------------------===//
11183 //                           ARM Inline Assembly Support
11184 //===----------------------------------------------------------------------===//
11185
11186 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
11187   // Looking for "rev" which is V6+.
11188   if (!Subtarget->hasV6Ops())
11189     return false;
11190
11191   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
11192   std::string AsmStr = IA->getAsmString();
11193   SmallVector<StringRef, 4> AsmPieces;
11194   SplitString(AsmStr, AsmPieces, ";\n");
11195
11196   switch (AsmPieces.size()) {
11197   default: return false;
11198   case 1:
11199     AsmStr = AsmPieces[0];
11200     AsmPieces.clear();
11201     SplitString(AsmStr, AsmPieces, " \t,");
11202
11203     // rev $0, $1
11204     if (AsmPieces.size() == 3 &&
11205         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
11206         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
11207       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
11208       if (Ty && Ty->getBitWidth() == 32)
11209         return IntrinsicLowering::LowerToByteSwap(CI);
11210     }
11211     break;
11212   }
11213
11214   return false;
11215 }
11216
11217 /// getConstraintType - Given a constraint letter, return the type of
11218 /// constraint it is for this target.
11219 ARMTargetLowering::ConstraintType
11220 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
11221   if (Constraint.size() == 1) {
11222     switch (Constraint[0]) {
11223     default:  break;
11224     case 'l': return C_RegisterClass;
11225     case 'w': return C_RegisterClass;
11226     case 'h': return C_RegisterClass;
11227     case 'x': return C_RegisterClass;
11228     case 't': return C_RegisterClass;
11229     case 'j': return C_Other; // Constant for movw.
11230       // An address with a single base register. Due to the way we
11231       // currently handle addresses it is the same as an 'r' memory constraint.
11232     case 'Q': return C_Memory;
11233     }
11234   } else if (Constraint.size() == 2) {
11235     switch (Constraint[0]) {
11236     default: break;
11237     // All 'U+' constraints are addresses.
11238     case 'U': return C_Memory;
11239     }
11240   }
11241   return TargetLowering::getConstraintType(Constraint);
11242 }
11243
11244 /// Examine constraint type and operand type and determine a weight value.
11245 /// This object must already have been set up with the operand type
11246 /// and the current alternative constraint selected.
11247 TargetLowering::ConstraintWeight
11248 ARMTargetLowering::getSingleConstraintMatchWeight(
11249     AsmOperandInfo &info, const char *constraint) const {
11250   ConstraintWeight weight = CW_Invalid;
11251   Value *CallOperandVal = info.CallOperandVal;
11252     // If we don't have a value, we can't do a match,
11253     // but allow it at the lowest weight.
11254   if (!CallOperandVal)
11255     return CW_Default;
11256   Type *type = CallOperandVal->getType();
11257   // Look at the constraint type.
11258   switch (*constraint) {
11259   default:
11260     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
11261     break;
11262   case 'l':
11263     if (type->isIntegerTy()) {
11264       if (Subtarget->isThumb())
11265         weight = CW_SpecificReg;
11266       else
11267         weight = CW_Register;
11268     }
11269     break;
11270   case 'w':
11271     if (type->isFloatingPointTy())
11272       weight = CW_Register;
11273     break;
11274   }
11275   return weight;
11276 }
11277
11278 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
11279 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
11280     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
11281   if (Constraint.size() == 1) {
11282     // GCC ARM Constraint Letters
11283     switch (Constraint[0]) {
11284     case 'l': // Low regs or general regs.
11285       if (Subtarget->isThumb())
11286         return RCPair(0U, &ARM::tGPRRegClass);
11287       return RCPair(0U, &ARM::GPRRegClass);
11288     case 'h': // High regs or no regs.
11289       if (Subtarget->isThumb())
11290         return RCPair(0U, &ARM::hGPRRegClass);
11291       break;
11292     case 'r':
11293       if (Subtarget->isThumb1Only())
11294         return RCPair(0U, &ARM::tGPRRegClass);
11295       return RCPair(0U, &ARM::GPRRegClass);
11296     case 'w':
11297       if (VT == MVT::Other)
11298         break;
11299       if (VT == MVT::f32)
11300         return RCPair(0U, &ARM::SPRRegClass);
11301       if (VT.getSizeInBits() == 64)
11302         return RCPair(0U, &ARM::DPRRegClass);
11303       if (VT.getSizeInBits() == 128)
11304         return RCPair(0U, &ARM::QPRRegClass);
11305       break;
11306     case 'x':
11307       if (VT == MVT::Other)
11308         break;
11309       if (VT == MVT::f32)
11310         return RCPair(0U, &ARM::SPR_8RegClass);
11311       if (VT.getSizeInBits() == 64)
11312         return RCPair(0U, &ARM::DPR_8RegClass);
11313       if (VT.getSizeInBits() == 128)
11314         return RCPair(0U, &ARM::QPR_8RegClass);
11315       break;
11316     case 't':
11317       if (VT == MVT::f32)
11318         return RCPair(0U, &ARM::SPRRegClass);
11319       break;
11320     }
11321   }
11322   if (StringRef("{cc}").equals_lower(Constraint))
11323     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
11324
11325   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11326 }
11327
11328 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
11329 /// vector.  If it is invalid, don't add anything to Ops.
11330 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11331                                                      std::string &Constraint,
11332                                                      std::vector<SDValue>&Ops,
11333                                                      SelectionDAG &DAG) const {
11334   SDValue Result;
11335
11336   // Currently only support length 1 constraints.
11337   if (Constraint.length() != 1) return;
11338
11339   char ConstraintLetter = Constraint[0];
11340   switch (ConstraintLetter) {
11341   default: break;
11342   case 'j':
11343   case 'I': case 'J': case 'K': case 'L':
11344   case 'M': case 'N': case 'O':
11345     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
11346     if (!C)
11347       return;
11348
11349     int64_t CVal64 = C->getSExtValue();
11350     int CVal = (int) CVal64;
11351     // None of these constraints allow values larger than 32 bits.  Check
11352     // that the value fits in an int.
11353     if (CVal != CVal64)
11354       return;
11355
11356     switch (ConstraintLetter) {
11357       case 'j':
11358         // Constant suitable for movw, must be between 0 and
11359         // 65535.
11360         if (Subtarget->hasV6T2Ops())
11361           if (CVal >= 0 && CVal <= 65535)
11362             break;
11363         return;
11364       case 'I':
11365         if (Subtarget->isThumb1Only()) {
11366           // This must be a constant between 0 and 255, for ADD
11367           // immediates.
11368           if (CVal >= 0 && CVal <= 255)
11369             break;
11370         } else if (Subtarget->isThumb2()) {
11371           // A constant that can be used as an immediate value in a
11372           // data-processing instruction.
11373           if (ARM_AM::getT2SOImmVal(CVal) != -1)
11374             break;
11375         } else {
11376           // A constant that can be used as an immediate value in a
11377           // data-processing instruction.
11378           if (ARM_AM::getSOImmVal(CVal) != -1)
11379             break;
11380         }
11381         return;
11382
11383       case 'J':
11384         if (Subtarget->isThumb()) {  // FIXME thumb2
11385           // This must be a constant between -255 and -1, for negated ADD
11386           // immediates. This can be used in GCC with an "n" modifier that
11387           // prints the negated value, for use with SUB instructions. It is
11388           // not useful otherwise but is implemented for compatibility.
11389           if (CVal >= -255 && CVal <= -1)
11390             break;
11391         } else {
11392           // This must be a constant between -4095 and 4095. It is not clear
11393           // what this constraint is intended for. Implemented for
11394           // compatibility with GCC.
11395           if (CVal >= -4095 && CVal <= 4095)
11396             break;
11397         }
11398         return;
11399
11400       case 'K':
11401         if (Subtarget->isThumb1Only()) {
11402           // A 32-bit value where only one byte has a nonzero value. Exclude
11403           // zero to match GCC. This constraint is used by GCC internally for
11404           // constants that can be loaded with a move/shift combination.
11405           // It is not useful otherwise but is implemented for compatibility.
11406           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
11407             break;
11408         } else if (Subtarget->isThumb2()) {
11409           // A constant whose bitwise inverse can be used as an immediate
11410           // value in a data-processing instruction. This can be used in GCC
11411           // with a "B" modifier that prints the inverted value, for use with
11412           // BIC and MVN instructions. It is not useful otherwise but is
11413           // implemented for compatibility.
11414           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
11415             break;
11416         } else {
11417           // A constant whose bitwise inverse can be used as an immediate
11418           // value in a data-processing instruction. This can be used in GCC
11419           // with a "B" modifier that prints the inverted value, for use with
11420           // BIC and MVN instructions. It is not useful otherwise but is
11421           // implemented for compatibility.
11422           if (ARM_AM::getSOImmVal(~CVal) != -1)
11423             break;
11424         }
11425         return;
11426
11427       case 'L':
11428         if (Subtarget->isThumb1Only()) {
11429           // This must be a constant between -7 and 7,
11430           // for 3-operand ADD/SUB immediate instructions.
11431           if (CVal >= -7 && CVal < 7)
11432             break;
11433         } else if (Subtarget->isThumb2()) {
11434           // A constant whose negation can be used as an immediate value in a
11435           // data-processing instruction. This can be used in GCC with an "n"
11436           // modifier that prints the negated value, for use with SUB
11437           // instructions. It is not useful otherwise but is implemented for
11438           // compatibility.
11439           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
11440             break;
11441         } else {
11442           // A constant whose negation can be used as an immediate value in a
11443           // data-processing instruction. This can be used in GCC with an "n"
11444           // modifier that prints the negated value, for use with SUB
11445           // instructions. It is not useful otherwise but is implemented for
11446           // compatibility.
11447           if (ARM_AM::getSOImmVal(-CVal) != -1)
11448             break;
11449         }
11450         return;
11451
11452       case 'M':
11453         if (Subtarget->isThumb()) { // FIXME thumb2
11454           // This must be a multiple of 4 between 0 and 1020, for
11455           // ADD sp + immediate.
11456           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
11457             break;
11458         } else {
11459           // A power of two or a constant between 0 and 32.  This is used in
11460           // GCC for the shift amount on shifted register operands, but it is
11461           // useful in general for any shift amounts.
11462           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
11463             break;
11464         }
11465         return;
11466
11467       case 'N':
11468         if (Subtarget->isThumb()) {  // FIXME thumb2
11469           // This must be a constant between 0 and 31, for shift amounts.
11470           if (CVal >= 0 && CVal <= 31)
11471             break;
11472         }
11473         return;
11474
11475       case 'O':
11476         if (Subtarget->isThumb()) {  // FIXME thumb2
11477           // This must be a multiple of 4 between -508 and 508, for
11478           // ADD/SUB sp = sp + immediate.
11479           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
11480             break;
11481         }
11482         return;
11483     }
11484     Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
11485     break;
11486   }
11487
11488   if (Result.getNode()) {
11489     Ops.push_back(Result);
11490     return;
11491   }
11492   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11493 }
11494
11495 static RTLIB::Libcall getDivRemLibcall(
11496     const SDNode *N, MVT::SimpleValueType SVT) {
11497   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
11498           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
11499          "Unhandled Opcode in getDivRemLibcall");
11500   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
11501                   N->getOpcode() == ISD::SREM;
11502   RTLIB::Libcall LC;
11503   switch (SVT) {
11504   default: llvm_unreachable("Unexpected request for libcall!");
11505   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
11506   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
11507   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
11508   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
11509   }
11510   return LC;
11511 }
11512
11513 static TargetLowering::ArgListTy getDivRemArgList(
11514     const SDNode *N, LLVMContext *Context) {
11515   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
11516           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
11517          "Unhandled Opcode in getDivRemArgList");
11518   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
11519                   N->getOpcode() == ISD::SREM;
11520   TargetLowering::ArgListTy Args;
11521   TargetLowering::ArgListEntry Entry;
11522   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11523     EVT ArgVT = N->getOperand(i).getValueType();
11524     Type *ArgTy = ArgVT.getTypeForEVT(*Context);
11525     Entry.Node = N->getOperand(i);
11526     Entry.Ty = ArgTy;
11527     Entry.isSExt = isSigned;
11528     Entry.isZExt = !isSigned;
11529     Args.push_back(Entry);
11530   }
11531   return Args;
11532 }
11533
11534 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
11535   assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid()) &&
11536          "Register-based DivRem lowering only");
11537   unsigned Opcode = Op->getOpcode();
11538   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
11539          "Invalid opcode for Div/Rem lowering");
11540   bool isSigned = (Opcode == ISD::SDIVREM);
11541   EVT VT = Op->getValueType(0);
11542   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
11543
11544   RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(),
11545                                        VT.getSimpleVT().SimpleTy);
11546   SDValue InChain = DAG.getEntryNode();
11547
11548   TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(),
11549                                                     DAG.getContext());
11550
11551   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11552                                          getPointerTy(DAG.getDataLayout()));
11553
11554   Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
11555
11556   SDLoc dl(Op);
11557   TargetLowering::CallLoweringInfo CLI(DAG);
11558   CLI.setDebugLoc(dl).setChain(InChain)
11559     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
11560     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
11561
11562   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
11563   return CallInfo.first;
11564 }
11565
11566 // Lowers REM using divmod helpers
11567 // see RTABI section 4.2/4.3
11568 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
11569   // Build return types (div and rem)
11570   std::vector<Type*> RetTyParams;
11571   Type *RetTyElement;
11572
11573   switch (N->getValueType(0).getSimpleVT().SimpleTy) {
11574   default: llvm_unreachable("Unexpected request for libcall!");
11575   case MVT::i8:   RetTyElement = Type::getInt8Ty(*DAG.getContext());  break;
11576   case MVT::i16:  RetTyElement = Type::getInt16Ty(*DAG.getContext()); break;
11577   case MVT::i32:  RetTyElement = Type::getInt32Ty(*DAG.getContext()); break;
11578   case MVT::i64:  RetTyElement = Type::getInt64Ty(*DAG.getContext()); break;
11579   }
11580
11581   RetTyParams.push_back(RetTyElement);
11582   RetTyParams.push_back(RetTyElement);
11583   ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams);
11584   Type *RetTy = StructType::get(*DAG.getContext(), ret);
11585
11586   RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT().
11587                                                              SimpleTy);
11588   SDValue InChain = DAG.getEntryNode();
11589   TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext());
11590   bool isSigned = N->getOpcode() == ISD::SREM;
11591   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11592                                          getPointerTy(DAG.getDataLayout()));
11593
11594   // Lower call
11595   CallLoweringInfo CLI(DAG);
11596   CLI.setChain(InChain)
11597      .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args), 0)
11598      .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N));
11599   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
11600
11601   // Return second (rem) result operand (first contains div)
11602   SDNode *ResNode = CallResult.first.getNode();
11603   assert(ResNode->getNumOperands() == 2 && "divmod should return two operands");
11604   return ResNode->getOperand(1);
11605 }
11606
11607 SDValue
11608 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
11609   assert(Subtarget->isTargetWindows() && "unsupported target platform");
11610   SDLoc DL(Op);
11611
11612   // Get the inputs.
11613   SDValue Chain = Op.getOperand(0);
11614   SDValue Size  = Op.getOperand(1);
11615
11616   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
11617                               DAG.getConstant(2, DL, MVT::i32));
11618
11619   SDValue Flag;
11620   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
11621   Flag = Chain.getValue(1);
11622
11623   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11624   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
11625
11626   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
11627   Chain = NewSP.getValue(1);
11628
11629   SDValue Ops[2] = { NewSP, Chain };
11630   return DAG.getMergeValues(Ops, DL);
11631 }
11632
11633 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
11634   assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
11635          "Unexpected type for custom-lowering FP_EXTEND");
11636
11637   RTLIB::Libcall LC;
11638   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
11639
11640   SDValue SrcVal = Op.getOperand(0);
11641   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
11642                      SDLoc(Op)).first;
11643 }
11644
11645 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
11646   assert(Op.getOperand(0).getValueType() == MVT::f64 &&
11647          Subtarget->isFPOnlySP() &&
11648          "Unexpected type for custom-lowering FP_ROUND");
11649
11650   RTLIB::Libcall LC;
11651   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
11652
11653   SDValue SrcVal = Op.getOperand(0);
11654   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
11655                      SDLoc(Op)).first;
11656 }
11657
11658 bool
11659 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11660   // The ARM target isn't yet aware of offsets.
11661   return false;
11662 }
11663
11664 bool ARM::isBitFieldInvertedMask(unsigned v) {
11665   if (v == 0xffffffff)
11666     return false;
11667
11668   // there can be 1's on either or both "outsides", all the "inside"
11669   // bits must be 0's
11670   return isShiftedMask_32(~v);
11671 }
11672
11673 /// isFPImmLegal - Returns true if the target can instruction select the
11674 /// specified FP immediate natively. If false, the legalizer will
11675 /// materialize the FP immediate as a load from a constant pool.
11676 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
11677   if (!Subtarget->hasVFP3())
11678     return false;
11679   if (VT == MVT::f32)
11680     return ARM_AM::getFP32Imm(Imm) != -1;
11681   if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
11682     return ARM_AM::getFP64Imm(Imm) != -1;
11683   return false;
11684 }
11685
11686 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
11687 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
11688 /// specified in the intrinsic calls.
11689 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11690                                            const CallInst &I,
11691                                            unsigned Intrinsic) const {
11692   switch (Intrinsic) {
11693   case Intrinsic::arm_neon_vld1:
11694   case Intrinsic::arm_neon_vld2:
11695   case Intrinsic::arm_neon_vld3:
11696   case Intrinsic::arm_neon_vld4:
11697   case Intrinsic::arm_neon_vld2lane:
11698   case Intrinsic::arm_neon_vld3lane:
11699   case Intrinsic::arm_neon_vld4lane: {
11700     Info.opc = ISD::INTRINSIC_W_CHAIN;
11701     // Conservatively set memVT to the entire set of vectors loaded.
11702     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11703     uint64_t NumElts = DL.getTypeAllocSize(I.getType()) / 8;
11704     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11705     Info.ptrVal = I.getArgOperand(0);
11706     Info.offset = 0;
11707     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11708     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11709     Info.vol = false; // volatile loads with NEON intrinsics not supported
11710     Info.readMem = true;
11711     Info.writeMem = false;
11712     return true;
11713   }
11714   case Intrinsic::arm_neon_vst1:
11715   case Intrinsic::arm_neon_vst2:
11716   case Intrinsic::arm_neon_vst3:
11717   case Intrinsic::arm_neon_vst4:
11718   case Intrinsic::arm_neon_vst2lane:
11719   case Intrinsic::arm_neon_vst3lane:
11720   case Intrinsic::arm_neon_vst4lane: {
11721     Info.opc = ISD::INTRINSIC_VOID;
11722     // Conservatively set memVT to the entire set of vectors stored.
11723     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11724     unsigned NumElts = 0;
11725     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11726       Type *ArgTy = I.getArgOperand(ArgI)->getType();
11727       if (!ArgTy->isVectorTy())
11728         break;
11729       NumElts += DL.getTypeAllocSize(ArgTy) / 8;
11730     }
11731     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11732     Info.ptrVal = I.getArgOperand(0);
11733     Info.offset = 0;
11734     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11735     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11736     Info.vol = false; // volatile stores with NEON intrinsics not supported
11737     Info.readMem = false;
11738     Info.writeMem = true;
11739     return true;
11740   }
11741   case Intrinsic::arm_ldaex:
11742   case Intrinsic::arm_ldrex: {
11743     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11744     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11745     Info.opc = ISD::INTRINSIC_W_CHAIN;
11746     Info.memVT = MVT::getVT(PtrTy->getElementType());
11747     Info.ptrVal = I.getArgOperand(0);
11748     Info.offset = 0;
11749     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11750     Info.vol = true;
11751     Info.readMem = true;
11752     Info.writeMem = false;
11753     return true;
11754   }
11755   case Intrinsic::arm_stlex:
11756   case Intrinsic::arm_strex: {
11757     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11758     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11759     Info.opc = ISD::INTRINSIC_W_CHAIN;
11760     Info.memVT = MVT::getVT(PtrTy->getElementType());
11761     Info.ptrVal = I.getArgOperand(1);
11762     Info.offset = 0;
11763     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11764     Info.vol = true;
11765     Info.readMem = false;
11766     Info.writeMem = true;
11767     return true;
11768   }
11769   case Intrinsic::arm_stlexd:
11770   case Intrinsic::arm_strexd: {
11771     Info.opc = ISD::INTRINSIC_W_CHAIN;
11772     Info.memVT = MVT::i64;
11773     Info.ptrVal = I.getArgOperand(2);
11774     Info.offset = 0;
11775     Info.align = 8;
11776     Info.vol = true;
11777     Info.readMem = false;
11778     Info.writeMem = true;
11779     return true;
11780   }
11781   case Intrinsic::arm_ldaexd:
11782   case Intrinsic::arm_ldrexd: {
11783     Info.opc = ISD::INTRINSIC_W_CHAIN;
11784     Info.memVT = MVT::i64;
11785     Info.ptrVal = I.getArgOperand(0);
11786     Info.offset = 0;
11787     Info.align = 8;
11788     Info.vol = true;
11789     Info.readMem = true;
11790     Info.writeMem = false;
11791     return true;
11792   }
11793   default:
11794     break;
11795   }
11796
11797   return false;
11798 }
11799
11800 /// \brief Returns true if it is beneficial to convert a load of a constant
11801 /// to just the constant itself.
11802 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11803                                                           Type *Ty) const {
11804   assert(Ty->isIntegerTy());
11805
11806   unsigned Bits = Ty->getPrimitiveSizeInBits();
11807   if (Bits == 0 || Bits > 32)
11808     return false;
11809   return true;
11810 }
11811
11812 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
11813                                         ARM_MB::MemBOpt Domain) const {
11814   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11815
11816   // First, if the target has no DMB, see what fallback we can use.
11817   if (!Subtarget->hasDataBarrier()) {
11818     // Some ARMv6 cpus can support data barriers with an mcr instruction.
11819     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
11820     // here.
11821     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
11822       Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
11823       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
11824                         Builder.getInt32(0), Builder.getInt32(7),
11825                         Builder.getInt32(10), Builder.getInt32(5)};
11826       return Builder.CreateCall(MCR, args);
11827     } else {
11828       // Instead of using barriers, atomic accesses on these subtargets use
11829       // libcalls.
11830       llvm_unreachable("makeDMB on a target so old that it has no barriers");
11831     }
11832   } else {
11833     Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
11834     // Only a full system barrier exists in the M-class architectures.
11835     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
11836     Constant *CDomain = Builder.getInt32(Domain);
11837     return Builder.CreateCall(DMB, CDomain);
11838   }
11839 }
11840
11841 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11842 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11843                                          AtomicOrdering Ord, bool IsStore,
11844                                          bool IsLoad) const {
11845   if (!getInsertFencesForAtomic())
11846     return nullptr;
11847
11848   switch (Ord) {
11849   case NotAtomic:
11850   case Unordered:
11851     llvm_unreachable("Invalid fence: unordered/non-atomic");
11852   case Monotonic:
11853   case Acquire:
11854     return nullptr; // Nothing to do
11855   case SequentiallyConsistent:
11856     if (!IsStore)
11857       return nullptr; // Nothing to do
11858     /*FALLTHROUGH*/
11859   case Release:
11860   case AcquireRelease:
11861     if (Subtarget->isSwift())
11862       return makeDMB(Builder, ARM_MB::ISHST);
11863     // FIXME: add a comment with a link to documentation justifying this.
11864     else
11865       return makeDMB(Builder, ARM_MB::ISH);
11866   }
11867   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
11868 }
11869
11870 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11871                                           AtomicOrdering Ord, bool IsStore,
11872                                           bool IsLoad) const {
11873   if (!getInsertFencesForAtomic())
11874     return nullptr;
11875
11876   switch (Ord) {
11877   case NotAtomic:
11878   case Unordered:
11879     llvm_unreachable("Invalid fence: unordered/not-atomic");
11880   case Monotonic:
11881   case Release:
11882     return nullptr; // Nothing to do
11883   case Acquire:
11884   case AcquireRelease:
11885   case SequentiallyConsistent:
11886     return makeDMB(Builder, ARM_MB::ISH);
11887   }
11888   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
11889 }
11890
11891 // Loads and stores less than 64-bits are already atomic; ones above that
11892 // are doomed anyway, so defer to the default libcall and blame the OS when
11893 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11894 // anything for those.
11895 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11896   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11897   return (Size == 64) && !Subtarget->isMClass();
11898 }
11899
11900 // Loads and stores less than 64-bits are already atomic; ones above that
11901 // are doomed anyway, so defer to the default libcall and blame the OS when
11902 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11903 // anything for those.
11904 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
11905 // guarantee, see DDI0406C ARM architecture reference manual,
11906 // sections A8.8.72-74 LDRD)
11907 TargetLowering::AtomicExpansionKind
11908 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11909   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11910   return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLSC
11911                                                   : AtomicExpansionKind::None;
11912 }
11913
11914 // For the real atomic operations, we have ldrex/strex up to 32 bits,
11915 // and up to 64 bits on the non-M profiles
11916 TargetLowering::AtomicExpansionKind
11917 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11918   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11919   return (Size <= (Subtarget->isMClass() ? 32U : 64U))
11920              ? AtomicExpansionKind::LLSC
11921              : AtomicExpansionKind::None;
11922 }
11923
11924 bool ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(
11925     AtomicCmpXchgInst *AI) const {
11926   return true;
11927 }
11928
11929 // This has so far only been implemented for MachO.
11930 bool ARMTargetLowering::useLoadStackGuardNode() const {
11931   return Subtarget->isTargetMachO();
11932 }
11933
11934 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
11935                                                   unsigned &Cost) const {
11936   // If we do not have NEON, vector types are not natively supported.
11937   if (!Subtarget->hasNEON())
11938     return false;
11939
11940   // Floating point values and vector values map to the same register file.
11941   // Therefore, although we could do a store extract of a vector type, this is
11942   // better to leave at float as we have more freedom in the addressing mode for
11943   // those.
11944   if (VectorTy->isFPOrFPVectorTy())
11945     return false;
11946
11947   // If the index is unknown at compile time, this is very expensive to lower
11948   // and it is not possible to combine the store with the extract.
11949   if (!isa<ConstantInt>(Idx))
11950     return false;
11951
11952   assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
11953   unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
11954   // We can do a store + vector extract on any vector that fits perfectly in a D
11955   // or Q register.
11956   if (BitWidth == 64 || BitWidth == 128) {
11957     Cost = 0;
11958     return true;
11959   }
11960   return false;
11961 }
11962
11963 bool ARMTargetLowering::isCheapToSpeculateCttz() const {
11964   return Subtarget->hasV6T2Ops();
11965 }
11966
11967 bool ARMTargetLowering::isCheapToSpeculateCtlz() const {
11968   return Subtarget->hasV6T2Ops();
11969 }
11970
11971 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11972                                          AtomicOrdering Ord) const {
11973   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11974   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11975   bool IsAcquire = isAtLeastAcquire(Ord);
11976
11977   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
11978   // intrinsic must return {i32, i32} and we have to recombine them into a
11979   // single i64 here.
11980   if (ValTy->getPrimitiveSizeInBits() == 64) {
11981     Intrinsic::ID Int =
11982         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
11983     Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
11984
11985     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11986     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
11987
11988     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11989     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11990     if (!Subtarget->isLittle())
11991       std::swap (Lo, Hi);
11992     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11993     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11994     return Builder.CreateOr(
11995         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
11996   }
11997
11998   Type *Tys[] = { Addr->getType() };
11999   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
12000   Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
12001
12002   return Builder.CreateTruncOrBitCast(
12003       Builder.CreateCall(Ldrex, Addr),
12004       cast<PointerType>(Addr->getType())->getElementType());
12005 }
12006
12007 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
12008     IRBuilder<> &Builder) const {
12009   if (!Subtarget->hasV7Ops())
12010     return;
12011   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
12012   Builder.CreateCall(llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_clrex));
12013 }
12014
12015 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
12016                                                Value *Addr,
12017                                                AtomicOrdering Ord) const {
12018   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
12019   bool IsRelease = isAtLeastRelease(Ord);
12020
12021   // Since the intrinsics must have legal type, the i64 intrinsics take two
12022   // parameters: "i32, i32". We must marshal Val into the appropriate form
12023   // before the call.
12024   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
12025     Intrinsic::ID Int =
12026         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
12027     Function *Strex = Intrinsic::getDeclaration(M, Int);
12028     Type *Int32Ty = Type::getInt32Ty(M->getContext());
12029
12030     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
12031     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
12032     if (!Subtarget->isLittle())
12033       std::swap (Lo, Hi);
12034     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
12035     return Builder.CreateCall(Strex, {Lo, Hi, Addr});
12036   }
12037
12038   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
12039   Type *Tys[] = { Addr->getType() };
12040   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
12041
12042   return Builder.CreateCall(
12043       Strex, {Builder.CreateZExtOrBitCast(
12044                   Val, Strex->getFunctionType()->getParamType(0)),
12045               Addr});
12046 }
12047
12048 /// \brief Lower an interleaved load into a vldN intrinsic.
12049 ///
12050 /// E.g. Lower an interleaved load (Factor = 2):
12051 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
12052 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
12053 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
12054 ///
12055 ///      Into:
12056 ///        %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
12057 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
12058 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
12059 bool ARMTargetLowering::lowerInterleavedLoad(
12060     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
12061     ArrayRef<unsigned> Indices, unsigned Factor) const {
12062   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
12063          "Invalid interleave factor");
12064   assert(!Shuffles.empty() && "Empty shufflevector input");
12065   assert(Shuffles.size() == Indices.size() &&
12066          "Unmatched number of shufflevectors and indices");
12067
12068   VectorType *VecTy = Shuffles[0]->getType();
12069   Type *EltTy = VecTy->getVectorElementType();
12070
12071   const DataLayout &DL = LI->getModule()->getDataLayout();
12072   unsigned VecSize = DL.getTypeAllocSizeInBits(VecTy);
12073   bool EltIs64Bits = DL.getTypeAllocSizeInBits(EltTy) == 64;
12074
12075   // Skip if we do not have NEON and skip illegal vector types and vector types
12076   // with i64/f64 elements (vldN doesn't support i64/f64 elements).
12077   if (!Subtarget->hasNEON() || (VecSize != 64 && VecSize != 128) || EltIs64Bits)
12078     return false;
12079
12080   // A pointer vector can not be the return type of the ldN intrinsics. Need to
12081   // load integer vectors first and then convert to pointer vectors.
12082   if (EltTy->isPointerTy())
12083     VecTy =
12084         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
12085
12086   static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
12087                                             Intrinsic::arm_neon_vld3,
12088                                             Intrinsic::arm_neon_vld4};
12089
12090   IRBuilder<> Builder(LI);
12091   SmallVector<Value *, 2> Ops;
12092
12093   Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
12094   Ops.push_back(Builder.CreateBitCast(LI->getPointerOperand(), Int8Ptr));
12095   Ops.push_back(Builder.getInt32(LI->getAlignment()));
12096
12097   Type *Tys[] = { VecTy, Int8Ptr };
12098   Function *VldnFunc =
12099       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
12100   CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
12101
12102   // Replace uses of each shufflevector with the corresponding vector loaded
12103   // by ldN.
12104   for (unsigned i = 0; i < Shuffles.size(); i++) {
12105     ShuffleVectorInst *SV = Shuffles[i];
12106     unsigned Index = Indices[i];
12107
12108     Value *SubVec = Builder.CreateExtractValue(VldN, Index);
12109
12110     // Convert the integer vector to pointer vector if the element is pointer.
12111     if (EltTy->isPointerTy())
12112       SubVec = Builder.CreateIntToPtr(SubVec, SV->getType());
12113
12114     SV->replaceAllUsesWith(SubVec);
12115   }
12116
12117   return true;
12118 }
12119
12120 /// \brief Get a mask consisting of sequential integers starting from \p Start.
12121 ///
12122 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
12123 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
12124                                    unsigned NumElts) {
12125   SmallVector<Constant *, 16> Mask;
12126   for (unsigned i = 0; i < NumElts; i++)
12127     Mask.push_back(Builder.getInt32(Start + i));
12128
12129   return ConstantVector::get(Mask);
12130 }
12131
12132 /// \brief Lower an interleaved store into a vstN intrinsic.
12133 ///
12134 /// E.g. Lower an interleaved store (Factor = 3):
12135 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
12136 ///                                  <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
12137 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
12138 ///
12139 ///      Into:
12140 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
12141 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
12142 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
12143 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
12144 ///
12145 /// Note that the new shufflevectors will be removed and we'll only generate one
12146 /// vst3 instruction in CodeGen.
12147 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
12148                                               ShuffleVectorInst *SVI,
12149                                               unsigned Factor) const {
12150   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
12151          "Invalid interleave factor");
12152
12153   VectorType *VecTy = SVI->getType();
12154   assert(VecTy->getVectorNumElements() % Factor == 0 &&
12155          "Invalid interleaved store");
12156
12157   unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
12158   Type *EltTy = VecTy->getVectorElementType();
12159   VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
12160
12161   const DataLayout &DL = SI->getModule()->getDataLayout();
12162   unsigned SubVecSize = DL.getTypeAllocSizeInBits(SubVecTy);
12163   bool EltIs64Bits = DL.getTypeAllocSizeInBits(EltTy) == 64;
12164
12165   // Skip if we do not have NEON and skip illegal vector types and vector types
12166   // with i64/f64 elements (vstN doesn't support i64/f64 elements).
12167   if (!Subtarget->hasNEON() || (SubVecSize != 64 && SubVecSize != 128) ||
12168       EltIs64Bits)
12169     return false;
12170
12171   Value *Op0 = SVI->getOperand(0);
12172   Value *Op1 = SVI->getOperand(1);
12173   IRBuilder<> Builder(SI);
12174
12175   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
12176   // vectors to integer vectors.
12177   if (EltTy->isPointerTy()) {
12178     Type *IntTy = DL.getIntPtrType(EltTy);
12179
12180     // Convert to the corresponding integer vector.
12181     Type *IntVecTy =
12182         VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
12183     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
12184     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
12185
12186     SubVecTy = VectorType::get(IntTy, NumSubElts);
12187   }
12188
12189   static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
12190                                              Intrinsic::arm_neon_vst3,
12191                                              Intrinsic::arm_neon_vst4};
12192   SmallVector<Value *, 6> Ops;
12193
12194   Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
12195   Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), Int8Ptr));
12196
12197   Type *Tys[] = { Int8Ptr, SubVecTy };
12198   Function *VstNFunc = Intrinsic::getDeclaration(
12199       SI->getModule(), StoreInts[Factor - 2], Tys);
12200
12201   // Split the shufflevector operands into sub vectors for the new vstN call.
12202   for (unsigned i = 0; i < Factor; i++)
12203     Ops.push_back(Builder.CreateShuffleVector(
12204         Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
12205
12206   Ops.push_back(Builder.getInt32(SI->getAlignment()));
12207   Builder.CreateCall(VstNFunc, Ops);
12208   return true;
12209 }
12210
12211 enum HABaseType {
12212   HA_UNKNOWN = 0,
12213   HA_FLOAT,
12214   HA_DOUBLE,
12215   HA_VECT64,
12216   HA_VECT128
12217 };
12218
12219 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
12220                                    uint64_t &Members) {
12221   if (auto *ST = dyn_cast<StructType>(Ty)) {
12222     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
12223       uint64_t SubMembers = 0;
12224       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
12225         return false;
12226       Members += SubMembers;
12227     }
12228   } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
12229     uint64_t SubMembers = 0;
12230     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
12231       return false;
12232     Members += SubMembers * AT->getNumElements();
12233   } else if (Ty->isFloatTy()) {
12234     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
12235       return false;
12236     Members = 1;
12237     Base = HA_FLOAT;
12238   } else if (Ty->isDoubleTy()) {
12239     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
12240       return false;
12241     Members = 1;
12242     Base = HA_DOUBLE;
12243   } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
12244     Members = 1;
12245     switch (Base) {
12246     case HA_FLOAT:
12247     case HA_DOUBLE:
12248       return false;
12249     case HA_VECT64:
12250       return VT->getBitWidth() == 64;
12251     case HA_VECT128:
12252       return VT->getBitWidth() == 128;
12253     case HA_UNKNOWN:
12254       switch (VT->getBitWidth()) {
12255       case 64:
12256         Base = HA_VECT64;
12257         return true;
12258       case 128:
12259         Base = HA_VECT128;
12260         return true;
12261       default:
12262         return false;
12263       }
12264     }
12265   }
12266
12267   return (Members > 0 && Members <= 4);
12268 }
12269
12270 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
12271 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
12272 /// passing according to AAPCS rules.
12273 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
12274     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
12275   if (getEffectiveCallingConv(CallConv, isVarArg) !=
12276       CallingConv::ARM_AAPCS_VFP)
12277     return false;
12278
12279   HABaseType Base = HA_UNKNOWN;
12280   uint64_t Members = 0;
12281   bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
12282   DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
12283
12284   bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
12285   return IsHA || IsIntArray;
12286 }
12287
12288 unsigned ARMTargetLowering::getExceptionPointerRegister(
12289     const Constant *PersonalityFn) const {
12290   // Platforms which do not use SjLj EH may return values in these registers
12291   // via the personality function.
12292   return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0;
12293 }
12294
12295 unsigned ARMTargetLowering::getExceptionSelectorRegister(
12296     const Constant *PersonalityFn) const {
12297   // Platforms which do not use SjLj EH may return values in these registers
12298   // via the personality function.
12299   return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1;
12300 }