[ARM] Enable vector extload combine for legal types.
[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/Intrinsics.h"
45 #include "llvm/IR/Type.h"
46 #include "llvm/MC/MCSectionMachO.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Support/MathExtras.h"
51 #include "llvm/Target/TargetOptions.h"
52 #include <utility>
53 using namespace llvm;
54
55 #define DEBUG_TYPE "arm-isel"
56
57 STATISTIC(NumTailCalls, "Number of tail calls");
58 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
59 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
60
61 cl::opt<bool>
62 EnableARMLongCalls("arm-long-calls", cl::Hidden,
63   cl::desc("Generate calls via indirect call instructions"),
64   cl::init(false));
65
66 static cl::opt<bool>
67 ARMInterworking("arm-interworking", cl::Hidden,
68   cl::desc("Enable / disable ARM interworking (for debugging only)"),
69   cl::init(true));
70
71 namespace {
72   class ARMCCState : public CCState {
73   public:
74     ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
75                SmallVectorImpl<CCValAssign> &locs, LLVMContext &C,
76                ParmContext PC)
77         : CCState(CC, isVarArg, MF, locs, C) {
78       assert(((PC == Call) || (PC == Prologue)) &&
79              "ARMCCState users must specify whether their context is call"
80              "or prologue generation.");
81       CallOrPrologue = PC;
82     }
83   };
84 }
85
86 // The APCS parameter registers.
87 static const MCPhysReg GPRArgRegs[] = {
88   ARM::R0, ARM::R1, ARM::R2, ARM::R3
89 };
90
91 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
92                                        MVT PromotedBitwiseVT) {
93   if (VT != PromotedLdStVT) {
94     setOperationAction(ISD::LOAD, VT, Promote);
95     AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
96
97     setOperationAction(ISD::STORE, VT, Promote);
98     AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
99   }
100
101   MVT ElemTy = VT.getVectorElementType();
102   if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
103     setOperationAction(ISD::SETCC, VT, Custom);
104   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
105   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
106   if (ElemTy == MVT::i32) {
107     setOperationAction(ISD::SINT_TO_FP, VT, Custom);
108     setOperationAction(ISD::UINT_TO_FP, VT, Custom);
109     setOperationAction(ISD::FP_TO_SINT, VT, Custom);
110     setOperationAction(ISD::FP_TO_UINT, VT, Custom);
111   } else {
112     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
113     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
114     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
115     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
116   }
117   setOperationAction(ISD::BUILD_VECTOR,      VT, Custom);
118   setOperationAction(ISD::VECTOR_SHUFFLE,    VT, Custom);
119   setOperationAction(ISD::CONCAT_VECTORS,    VT, Legal);
120   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
121   setOperationAction(ISD::SELECT,            VT, Expand);
122   setOperationAction(ISD::SELECT_CC,         VT, Expand);
123   setOperationAction(ISD::VSELECT,           VT, Expand);
124   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
125   if (VT.isInteger()) {
126     setOperationAction(ISD::SHL, VT, Custom);
127     setOperationAction(ISD::SRA, VT, Custom);
128     setOperationAction(ISD::SRL, VT, Custom);
129   }
130
131   // Promote all bit-wise operations.
132   if (VT.isInteger() && VT != PromotedBitwiseVT) {
133     setOperationAction(ISD::AND, VT, Promote);
134     AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
135     setOperationAction(ISD::OR,  VT, Promote);
136     AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
137     setOperationAction(ISD::XOR, VT, Promote);
138     AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
139   }
140
141   // Neon does not support vector divide/remainder operations.
142   setOperationAction(ISD::SDIV, VT, Expand);
143   setOperationAction(ISD::UDIV, VT, Expand);
144   setOperationAction(ISD::FDIV, VT, Expand);
145   setOperationAction(ISD::SREM, VT, Expand);
146   setOperationAction(ISD::UREM, VT, Expand);
147   setOperationAction(ISD::FREM, VT, Expand);
148 }
149
150 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
151   addRegisterClass(VT, &ARM::DPRRegClass);
152   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
153 }
154
155 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
156   addRegisterClass(VT, &ARM::DPairRegClass);
157   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
158 }
159
160 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM,
161                                      const ARMSubtarget &STI)
162     : TargetLowering(TM), Subtarget(&STI) {
163   RegInfo = Subtarget->getRegisterInfo();
164   Itins = Subtarget->getInstrItineraryData();
165
166   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
167
168   if (Subtarget->isTargetMachO()) {
169     // Uses VFP for Thumb libfuncs if available.
170     if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
171         Subtarget->hasARMOps() && !TM.Options.UseSoftFloat) {
172       // Single-precision floating-point arithmetic.
173       setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
174       setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
175       setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
176       setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
177
178       // Double-precision floating-point arithmetic.
179       setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
180       setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
181       setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
182       setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
183
184       // Single-precision comparisons.
185       setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
186       setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
187       setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
188       setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
189       setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
190       setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
191       setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
192       setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
193
194       setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
195       setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
196       setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
197       setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
198       setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
199       setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
200       setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
201       setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
202
203       // Double-precision comparisons.
204       setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
205       setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
206       setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
207       setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
208       setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
209       setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
210       setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
211       setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
212
213       setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
214       setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
215       setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
216       setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
217       setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
218       setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
219       setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
220       setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
221
222       // Floating-point to integer conversions.
223       // i64 conversions are done via library routines even when generating VFP
224       // instructions, so use the same ones.
225       setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
226       setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
227       setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
228       setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
229
230       // Conversions between floating types.
231       setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
232       setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
233
234       // Integer to floating-point conversions.
235       // i64 conversions are done via library routines even when generating VFP
236       // instructions, so use the same ones.
237       // FIXME: There appears to be some naming inconsistency in ARM libgcc:
238       // e.g., __floatunsidf vs. __floatunssidfvfp.
239       setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
240       setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
241       setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
242       setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
243     }
244   }
245
246   // These libcalls are not available in 32-bit.
247   setLibcallName(RTLIB::SHL_I128, nullptr);
248   setLibcallName(RTLIB::SRL_I128, nullptr);
249   setLibcallName(RTLIB::SRA_I128, nullptr);
250
251   if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO() &&
252       !Subtarget->isTargetWindows()) {
253     static const struct {
254       const RTLIB::Libcall Op;
255       const char * const Name;
256       const CallingConv::ID CC;
257       const ISD::CondCode Cond;
258     } LibraryCalls[] = {
259       // Double-precision floating-point arithmetic helper functions
260       // RTABI chapter 4.1.2, Table 2
261       { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
262       { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
263       { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
264       { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
265
266       // Double-precision floating-point comparison helper functions
267       // RTABI chapter 4.1.2, Table 3
268       { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
269       { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
270       { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
271       { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
272       { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
273       { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
274       { RTLIB::UO_F64,  "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
275       { RTLIB::O_F64,   "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
276
277       // Single-precision floating-point arithmetic helper functions
278       // RTABI chapter 4.1.2, Table 4
279       { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
280       { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
281       { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
282       { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
283
284       // Single-precision floating-point comparison helper functions
285       // RTABI chapter 4.1.2, Table 5
286       { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
287       { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
288       { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
289       { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
290       { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
291       { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
292       { RTLIB::UO_F32,  "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
293       { RTLIB::O_F32,   "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
294
295       // Floating-point to integer conversions.
296       // RTABI chapter 4.1.2, Table 6
297       { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
298       { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
299       { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
300       { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
301       { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
302       { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
303       { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
304       { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
305
306       // Conversions between floating types.
307       // RTABI chapter 4.1.2, Table 7
308       { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
309       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
310       { RTLIB::FPEXT_F32_F64,   "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
311
312       // Integer to floating-point conversions.
313       // RTABI chapter 4.1.2, Table 8
314       { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
315       { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
316       { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
317       { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
318       { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
319       { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
320       { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
321       { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
322
323       // Long long helper functions
324       // RTABI chapter 4.2, Table 9
325       { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
326       { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
327       { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
328       { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
329
330       // Integer division functions
331       // RTABI chapter 4.3.1
332       { RTLIB::SDIV_I8,  "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
333       { RTLIB::SDIV_I16, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
334       { RTLIB::SDIV_I32, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
335       { RTLIB::SDIV_I64, "__aeabi_ldivmod",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
336       { RTLIB::UDIV_I8,  "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
337       { RTLIB::UDIV_I16, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
338       { RTLIB::UDIV_I32, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
339       { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
340
341       // Memory operations
342       // RTABI chapter 4.3.4
343       { RTLIB::MEMCPY,  "__aeabi_memcpy",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
344       { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
345       { RTLIB::MEMSET,  "__aeabi_memset",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
346     };
347
348     for (const auto &LC : LibraryCalls) {
349       setLibcallName(LC.Op, LC.Name);
350       setLibcallCallingConv(LC.Op, LC.CC);
351       if (LC.Cond != ISD::SETCC_INVALID)
352         setCmpLibcallCC(LC.Op, LC.Cond);
353     }
354   }
355
356   if (Subtarget->isTargetWindows()) {
357     static const struct {
358       const RTLIB::Libcall Op;
359       const char * const Name;
360       const CallingConv::ID CC;
361     } LibraryCalls[] = {
362       { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
363       { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
364       { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
365       { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
366       { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
367       { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
368       { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
369       { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
370     };
371
372     for (const auto &LC : LibraryCalls) {
373       setLibcallName(LC.Op, LC.Name);
374       setLibcallCallingConv(LC.Op, LC.CC);
375     }
376   }
377
378   // Use divmod compiler-rt calls for iOS 5.0 and later.
379   if (Subtarget->getTargetTriple().isiOS() &&
380       !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
381     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
382     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
383   }
384
385   // The half <-> float conversion functions are always soft-float, but are
386   // needed for some targets which use a hard-float calling convention by
387   // default.
388   if (Subtarget->isAAPCS_ABI()) {
389     setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
390     setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
391     setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
392   } else {
393     setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
394     setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
395     setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
396   }
397
398   if (Subtarget->isThumb1Only())
399     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
400   else
401     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
402   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
403       !Subtarget->isThumb1Only()) {
404     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
405     addRegisterClass(MVT::f64, &ARM::DPRRegClass);
406   }
407
408   for (MVT VT : MVT::vector_valuetypes()) {
409     for (MVT InnerVT : MVT::vector_valuetypes()) {
410       setTruncStoreAction(VT, InnerVT, Expand);
411       setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
412       setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
413       setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
414     }
415
416     setOperationAction(ISD::MULHS, VT, Expand);
417     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
418     setOperationAction(ISD::MULHU, VT, Expand);
419     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
420
421     setOperationAction(ISD::BSWAP, VT, Expand);
422   }
423
424   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
425   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
426
427   if (Subtarget->hasNEON()) {
428     addDRTypeForNEON(MVT::v2f32);
429     addDRTypeForNEON(MVT::v8i8);
430     addDRTypeForNEON(MVT::v4i16);
431     addDRTypeForNEON(MVT::v2i32);
432     addDRTypeForNEON(MVT::v1i64);
433
434     addQRTypeForNEON(MVT::v4f32);
435     addQRTypeForNEON(MVT::v2f64);
436     addQRTypeForNEON(MVT::v16i8);
437     addQRTypeForNEON(MVT::v8i16);
438     addQRTypeForNEON(MVT::v4i32);
439     addQRTypeForNEON(MVT::v2i64);
440
441     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
442     // neither Neon nor VFP support any arithmetic operations on it.
443     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
444     // supported for v4f32.
445     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
446     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
447     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
448     // FIXME: Code duplication: FDIV and FREM are expanded always, see
449     // ARMTargetLowering::addTypeForNEON method for details.
450     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
451     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
452     // FIXME: Create unittest.
453     // In another words, find a way when "copysign" appears in DAG with vector
454     // operands.
455     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
456     // FIXME: Code duplication: SETCC has custom operation action, see
457     // ARMTargetLowering::addTypeForNEON method for details.
458     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
459     // FIXME: Create unittest for FNEG and for FABS.
460     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
461     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
462     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
463     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
464     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
465     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
466     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
467     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
468     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
469     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
470     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
471     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
472     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
473     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
474     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
475     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
476     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
477     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
478     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
479
480     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
481     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
482     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
483     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
484     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
485     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
486     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
487     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
488     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
489     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
490     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
491     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
492     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
493     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
494     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
495
496     // Mark v2f32 intrinsics.
497     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
498     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
499     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
500     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
501     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
502     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
503     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
504     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
505     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
506     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
507     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
508     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
509     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
510     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
511     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
512
513     // Neon does not support some operations on v1i64 and v2i64 types.
514     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
515     // Custom handling for some quad-vector types to detect VMULL.
516     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
517     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
518     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
519     // Custom handling for some vector types to avoid expensive expansions
520     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
521     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
522     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
523     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
524     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
525     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
526     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
527     // a destination type that is wider than the source, and nor does
528     // it have a FP_TO_[SU]INT instruction with a narrower destination than
529     // source.
530     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
531     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
532     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
533     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
534
535     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
536     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
537
538     // NEON does not have single instruction CTPOP for vectors with element
539     // types wider than 8-bits.  However, custom lowering can leverage the
540     // v8i8/v16i8 vcnt instruction.
541     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
542     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
543     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
544     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
545
546     // NEON only has FMA instructions as of VFP4.
547     if (!Subtarget->hasVFP4()) {
548       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
549       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
550     }
551
552     setTargetDAGCombine(ISD::INTRINSIC_VOID);
553     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
554     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
555     setTargetDAGCombine(ISD::SHL);
556     setTargetDAGCombine(ISD::SRL);
557     setTargetDAGCombine(ISD::SRA);
558     setTargetDAGCombine(ISD::SIGN_EXTEND);
559     setTargetDAGCombine(ISD::ZERO_EXTEND);
560     setTargetDAGCombine(ISD::ANY_EXTEND);
561     setTargetDAGCombine(ISD::SELECT_CC);
562     setTargetDAGCombine(ISD::BUILD_VECTOR);
563     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
564     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
565     setTargetDAGCombine(ISD::STORE);
566     setTargetDAGCombine(ISD::FP_TO_SINT);
567     setTargetDAGCombine(ISD::FP_TO_UINT);
568     setTargetDAGCombine(ISD::FDIV);
569     setTargetDAGCombine(ISD::LOAD);
570
571     // It is legal to extload from v4i8 to v4i16 or v4i32.
572     MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
573                   MVT::v4i16, MVT::v2i16,
574                   MVT::v2i32};
575     for (unsigned i = 0; i < 6; ++i) {
576       for (MVT VT : MVT::integer_vector_valuetypes()) {
577         setLoadExtAction(ISD::EXTLOAD, VT, Tys[i], Legal);
578         setLoadExtAction(ISD::ZEXTLOAD, VT, Tys[i], Legal);
579         setLoadExtAction(ISD::SEXTLOAD, VT, Tys[i], Legal);
580       }
581     }
582   }
583
584   // ARM and Thumb2 support UMLAL/SMLAL.
585   if (!Subtarget->isThumb1Only())
586     setTargetDAGCombine(ISD::ADDC);
587
588   if (Subtarget->isFPOnlySP()) {
589     // When targetting a floating-point unit with only single-precision
590     // operations, f64 is legal for the few double-precision instructions which
591     // are present However, no double-precision operations other than moves,
592     // loads and stores are provided by the hardware.
593     setOperationAction(ISD::FADD,       MVT::f64, Expand);
594     setOperationAction(ISD::FSUB,       MVT::f64, Expand);
595     setOperationAction(ISD::FMUL,       MVT::f64, Expand);
596     setOperationAction(ISD::FMA,        MVT::f64, Expand);
597     setOperationAction(ISD::FDIV,       MVT::f64, Expand);
598     setOperationAction(ISD::FREM,       MVT::f64, Expand);
599     setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
600     setOperationAction(ISD::FGETSIGN,   MVT::f64, Expand);
601     setOperationAction(ISD::FNEG,       MVT::f64, Expand);
602     setOperationAction(ISD::FABS,       MVT::f64, Expand);
603     setOperationAction(ISD::FSQRT,      MVT::f64, Expand);
604     setOperationAction(ISD::FSIN,       MVT::f64, Expand);
605     setOperationAction(ISD::FCOS,       MVT::f64, Expand);
606     setOperationAction(ISD::FPOWI,      MVT::f64, Expand);
607     setOperationAction(ISD::FPOW,       MVT::f64, Expand);
608     setOperationAction(ISD::FLOG,       MVT::f64, Expand);
609     setOperationAction(ISD::FLOG2,      MVT::f64, Expand);
610     setOperationAction(ISD::FLOG10,     MVT::f64, Expand);
611     setOperationAction(ISD::FEXP,       MVT::f64, Expand);
612     setOperationAction(ISD::FEXP2,      MVT::f64, Expand);
613     setOperationAction(ISD::FCEIL,      MVT::f64, Expand);
614     setOperationAction(ISD::FTRUNC,     MVT::f64, Expand);
615     setOperationAction(ISD::FRINT,      MVT::f64, Expand);
616     setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
617     setOperationAction(ISD::FFLOOR,     MVT::f64, Expand);
618     setOperationAction(ISD::FP_ROUND,   MVT::f32, Custom);
619     setOperationAction(ISD::FP_EXTEND,  MVT::f64, Custom);
620   }
621
622   computeRegisterProperties(Subtarget->getRegisterInfo());
623
624   // ARM does not have floating-point extending loads.
625   for (MVT VT : MVT::fp_valuetypes()) {
626     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
627     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
628   }
629
630   // ... or truncating stores
631   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
632   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
633   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
634
635   // ARM does not have i1 sign extending load.
636   for (MVT VT : MVT::integer_valuetypes())
637     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
638
639   // ARM supports all 4 flavors of integer indexed load / store.
640   if (!Subtarget->isThumb1Only()) {
641     for (unsigned im = (unsigned)ISD::PRE_INC;
642          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
643       setIndexedLoadAction(im,  MVT::i1,  Legal);
644       setIndexedLoadAction(im,  MVT::i8,  Legal);
645       setIndexedLoadAction(im,  MVT::i16, Legal);
646       setIndexedLoadAction(im,  MVT::i32, Legal);
647       setIndexedStoreAction(im, MVT::i1,  Legal);
648       setIndexedStoreAction(im, MVT::i8,  Legal);
649       setIndexedStoreAction(im, MVT::i16, Legal);
650       setIndexedStoreAction(im, MVT::i32, Legal);
651     }
652   }
653
654   setOperationAction(ISD::SADDO, MVT::i32, Custom);
655   setOperationAction(ISD::UADDO, MVT::i32, Custom);
656   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
657   setOperationAction(ISD::USUBO, MVT::i32, Custom);
658
659   // i64 operation support.
660   setOperationAction(ISD::MUL,     MVT::i64, Expand);
661   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
662   if (Subtarget->isThumb1Only()) {
663     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
664     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
665   }
666   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
667       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
668     setOperationAction(ISD::MULHS, MVT::i32, Expand);
669
670   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
671   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
672   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
673   setOperationAction(ISD::SRL,       MVT::i64, Custom);
674   setOperationAction(ISD::SRA,       MVT::i64, Custom);
675
676   if (!Subtarget->isThumb1Only()) {
677     // FIXME: We should do this for Thumb1 as well.
678     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
679     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
680     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
681     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
682   }
683
684   // ARM does not have ROTL.
685   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
686   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
687   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
688   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
689     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
690
691   // These just redirect to CTTZ and CTLZ on ARM.
692   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
693   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
694
695   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
696
697   // Only ARMv6 has BSWAP.
698   if (!Subtarget->hasV6Ops())
699     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
700
701   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
702       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
703     // These are expanded into libcalls if the cpu doesn't have HW divider.
704     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
705     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
706   }
707
708   // FIXME: Also set divmod for SREM on EABI
709   setOperationAction(ISD::SREM,  MVT::i32, Expand);
710   setOperationAction(ISD::UREM,  MVT::i32, Expand);
711   // Register based DivRem for AEABI (RTABI 4.2)
712   if (Subtarget->isTargetAEABI()) {
713     setLibcallName(RTLIB::SDIVREM_I8,  "__aeabi_idivmod");
714     setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
715     setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
716     setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
717     setLibcallName(RTLIB::UDIVREM_I8,  "__aeabi_uidivmod");
718     setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
719     setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
720     setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
721
722     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
723     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
724     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
725     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
726     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
727     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
728     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
729     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
730
731     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
732     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
733   } else {
734     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
735     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
736   }
737
738   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
739   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
740   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
741   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
742   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
743
744   setOperationAction(ISD::TRAP, MVT::Other, Legal);
745
746   // Use the default implementation.
747   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
748   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
749   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
750   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
751   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
752   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
753
754   if (!Subtarget->isTargetMachO()) {
755     // Non-MachO platforms may return values in these registers via the
756     // personality function.
757     setExceptionPointerRegister(ARM::R0);
758     setExceptionSelectorRegister(ARM::R1);
759   }
760
761   if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
762     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
763   else
764     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
765
766   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
767   // the default expansion. If we are targeting a single threaded system,
768   // then set them all for expand so we can lower them later into their
769   // non-atomic form.
770   if (TM.Options.ThreadModel == ThreadModel::Single)
771     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
772   else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
773     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
774     // to ldrex/strex loops already.
775     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
776
777     // On v8, we have particularly efficient implementations of atomic fences
778     // if they can be combined with nearby atomic loads and stores.
779     if (!Subtarget->hasV8Ops()) {
780       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
781       setInsertFencesForAtomic(true);
782     }
783   } else {
784     // If there's anything we can use as a barrier, go through custom lowering
785     // for ATOMIC_FENCE.
786     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
787                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
788
789     // Set them all for expansion, which will force libcalls.
790     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
791     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
792     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
793     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
794     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
795     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
796     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
797     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
798     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
799     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
800     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
801     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
802     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
803     // Unordered/Monotonic case.
804     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
805     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
806   }
807
808   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
809
810   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
811   if (!Subtarget->hasV6Ops()) {
812     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
813     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
814   }
815   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
816
817   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
818       !Subtarget->isThumb1Only()) {
819     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
820     // iff target supports vfp2.
821     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
822     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
823   }
824
825   // We want to custom lower some of our intrinsics.
826   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
827   if (Subtarget->isTargetDarwin()) {
828     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
829     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
830     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
831   }
832
833   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
834   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
835   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
836   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
837   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
838   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
839   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
840   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
841   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
842
843   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
844   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
845   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
846   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
847   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
848
849   // We don't support sin/cos/fmod/copysign/pow
850   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
851   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
852   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
853   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
854   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
855   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
856   setOperationAction(ISD::FREM,      MVT::f64, Expand);
857   setOperationAction(ISD::FREM,      MVT::f32, Expand);
858   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
859       !Subtarget->isThumb1Only()) {
860     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
861     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
862   }
863   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
864   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
865
866   if (!Subtarget->hasVFP4()) {
867     setOperationAction(ISD::FMA, MVT::f64, Expand);
868     setOperationAction(ISD::FMA, MVT::f32, Expand);
869   }
870
871   // Various VFP goodness
872   if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
873     // int <-> fp are custom expanded into bit_convert + ARMISD ops.
874     if (Subtarget->hasVFP2()) {
875       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
876       setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
877       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
878       setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
879     }
880
881     // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
882     if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
883       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
884       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
885     }
886
887     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
888     if (!Subtarget->hasFP16()) {
889       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
890       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
891     }
892   }
893
894   // Combine sin / cos into one node or libcall if possible.
895   if (Subtarget->hasSinCos()) {
896     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
897     setLibcallName(RTLIB::SINCOS_F64, "sincos");
898     if (Subtarget->getTargetTriple().isiOS()) {
899       // For iOS, we don't want to the normal expansion of a libcall to
900       // sincos. We want to issue a libcall to __sincos_stret.
901       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
902       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
903     }
904   }
905
906   // FP-ARMv8 implements a lot of rounding-like FP operations.
907   if (Subtarget->hasFPARMv8()) {
908     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
909     setOperationAction(ISD::FCEIL, MVT::f32, Legal);
910     setOperationAction(ISD::FROUND, MVT::f32, Legal);
911     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
912     setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
913     setOperationAction(ISD::FRINT, MVT::f32, Legal);
914     if (!Subtarget->isFPOnlySP()) {
915       setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
916       setOperationAction(ISD::FCEIL, MVT::f64, Legal);
917       setOperationAction(ISD::FROUND, MVT::f64, Legal);
918       setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
919       setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
920       setOperationAction(ISD::FRINT, MVT::f64, Legal);
921     }
922   }
923   // We have target-specific dag combine patterns for the following nodes:
924   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
925   setTargetDAGCombine(ISD::ADD);
926   setTargetDAGCombine(ISD::SUB);
927   setTargetDAGCombine(ISD::MUL);
928   setTargetDAGCombine(ISD::AND);
929   setTargetDAGCombine(ISD::OR);
930   setTargetDAGCombine(ISD::XOR);
931
932   if (Subtarget->hasV6Ops())
933     setTargetDAGCombine(ISD::SRL);
934
935   setStackPointerRegisterToSaveRestore(ARM::SP);
936
937   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
938       !Subtarget->hasVFP2())
939     setSchedulingPreference(Sched::RegPressure);
940   else
941     setSchedulingPreference(Sched::Hybrid);
942
943   //// temporary - rewrite interface to use type
944   MaxStoresPerMemset = 8;
945   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
946   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
947   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
948   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
949   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
950
951   // On ARM arguments smaller than 4 bytes are extended, so all arguments
952   // are at least 4 bytes aligned.
953   setMinStackArgumentAlignment(4);
954
955   // Prefer likely predicted branches to selects on out-of-order cores.
956   PredictableSelectIsExpensive = Subtarget->isLikeA9();
957
958   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
959 }
960
961 // FIXME: It might make sense to define the representative register class as the
962 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
963 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
964 // SPR's representative would be DPR_VFP2. This should work well if register
965 // pressure tracking were modified such that a register use would increment the
966 // pressure of the register class's representative and all of it's super
967 // classes' representatives transitively. We have not implemented this because
968 // of the difficulty prior to coalescing of modeling operand register classes
969 // due to the common occurrence of cross class copies and subregister insertions
970 // and extractions.
971 std::pair<const TargetRegisterClass *, uint8_t>
972 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
973                                            MVT VT) const {
974   const TargetRegisterClass *RRC = nullptr;
975   uint8_t Cost = 1;
976   switch (VT.SimpleTy) {
977   default:
978     return TargetLowering::findRepresentativeClass(TRI, VT);
979   // Use DPR as representative register class for all floating point
980   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
981   // the cost is 1 for both f32 and f64.
982   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
983   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
984     RRC = &ARM::DPRRegClass;
985     // When NEON is used for SP, only half of the register file is available
986     // because operations that define both SP and DP results will be constrained
987     // to the VFP2 class (D0-D15). We currently model this constraint prior to
988     // coalescing by double-counting the SP regs. See the FIXME above.
989     if (Subtarget->useNEONForSinglePrecisionFP())
990       Cost = 2;
991     break;
992   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
993   case MVT::v4f32: case MVT::v2f64:
994     RRC = &ARM::DPRRegClass;
995     Cost = 2;
996     break;
997   case MVT::v4i64:
998     RRC = &ARM::DPRRegClass;
999     Cost = 4;
1000     break;
1001   case MVT::v8i64:
1002     RRC = &ARM::DPRRegClass;
1003     Cost = 8;
1004     break;
1005   }
1006   return std::make_pair(RRC, Cost);
1007 }
1008
1009 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1010   switch (Opcode) {
1011   default: return nullptr;
1012   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1013   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1014   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1015   case ARMISD::CALL:          return "ARMISD::CALL";
1016   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1017   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1018   case ARMISD::tCALL:         return "ARMISD::tCALL";
1019   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1020   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1021   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1022   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1023   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1024   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1025   case ARMISD::CMP:           return "ARMISD::CMP";
1026   case ARMISD::CMN:           return "ARMISD::CMN";
1027   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1028   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1029   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1030   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1031   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1032
1033   case ARMISD::CMOV:          return "ARMISD::CMOV";
1034
1035   case ARMISD::RBIT:          return "ARMISD::RBIT";
1036
1037   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
1038   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
1039   case ARMISD::SITOF:         return "ARMISD::SITOF";
1040   case ARMISD::UITOF:         return "ARMISD::UITOF";
1041
1042   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1043   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1044   case ARMISD::RRX:           return "ARMISD::RRX";
1045
1046   case ARMISD::ADDC:          return "ARMISD::ADDC";
1047   case ARMISD::ADDE:          return "ARMISD::ADDE";
1048   case ARMISD::SUBC:          return "ARMISD::SUBC";
1049   case ARMISD::SUBE:          return "ARMISD::SUBE";
1050
1051   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1052   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1053
1054   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1055   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
1056
1057   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1058
1059   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1060
1061   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1062
1063   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1064
1065   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1066
1067   case ARMISD::WIN__CHKSTK:   return "ARMISD:::WIN__CHKSTK";
1068
1069   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1070   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1071   case ARMISD::VCGE:          return "ARMISD::VCGE";
1072   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1073   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1074   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1075   case ARMISD::VCGT:          return "ARMISD::VCGT";
1076   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1077   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1078   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1079   case ARMISD::VTST:          return "ARMISD::VTST";
1080
1081   case ARMISD::VSHL:          return "ARMISD::VSHL";
1082   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1083   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1084   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1085   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1086   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1087   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1088   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1089   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1090   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1091   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1092   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1093   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1094   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1095   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1096   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1097   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1098   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1099   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1100   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1101   case ARMISD::VDUP:          return "ARMISD::VDUP";
1102   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1103   case ARMISD::VEXT:          return "ARMISD::VEXT";
1104   case ARMISD::VREV64:        return "ARMISD::VREV64";
1105   case ARMISD::VREV32:        return "ARMISD::VREV32";
1106   case ARMISD::VREV16:        return "ARMISD::VREV16";
1107   case ARMISD::VZIP:          return "ARMISD::VZIP";
1108   case ARMISD::VUZP:          return "ARMISD::VUZP";
1109   case ARMISD::VTRN:          return "ARMISD::VTRN";
1110   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1111   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1112   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1113   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1114   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1115   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1116   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1117   case ARMISD::FMAX:          return "ARMISD::FMAX";
1118   case ARMISD::FMIN:          return "ARMISD::FMIN";
1119   case ARMISD::VMAXNM:        return "ARMISD::VMAX";
1120   case ARMISD::VMINNM:        return "ARMISD::VMIN";
1121   case ARMISD::BFI:           return "ARMISD::BFI";
1122   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1123   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1124   case ARMISD::VBSL:          return "ARMISD::VBSL";
1125   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1126   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1127   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1128   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1129   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1130   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1131   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1132   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1133   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1134   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1135   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1136   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1137   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1138   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1139   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1140   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1141   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1142   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1143   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1144   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1145   }
1146 }
1147
1148 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1149   if (!VT.isVector()) return getPointerTy();
1150   return VT.changeVectorElementTypeToInteger();
1151 }
1152
1153 /// getRegClassFor - Return the register class that should be used for the
1154 /// specified value type.
1155 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1156   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1157   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1158   // load / store 4 to 8 consecutive D registers.
1159   if (Subtarget->hasNEON()) {
1160     if (VT == MVT::v4i64)
1161       return &ARM::QQPRRegClass;
1162     if (VT == MVT::v8i64)
1163       return &ARM::QQQQPRRegClass;
1164   }
1165   return TargetLowering::getRegClassFor(VT);
1166 }
1167
1168 // Create a fast isel object.
1169 FastISel *
1170 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1171                                   const TargetLibraryInfo *libInfo) const {
1172   return ARM::createFastISel(funcInfo, libInfo);
1173 }
1174
1175 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1176   unsigned NumVals = N->getNumValues();
1177   if (!NumVals)
1178     return Sched::RegPressure;
1179
1180   for (unsigned i = 0; i != NumVals; ++i) {
1181     EVT VT = N->getValueType(i);
1182     if (VT == MVT::Glue || VT == MVT::Other)
1183       continue;
1184     if (VT.isFloatingPoint() || VT.isVector())
1185       return Sched::ILP;
1186   }
1187
1188   if (!N->isMachineOpcode())
1189     return Sched::RegPressure;
1190
1191   // Load are scheduled for latency even if there instruction itinerary
1192   // is not available.
1193   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1194   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1195
1196   if (MCID.getNumDefs() == 0)
1197     return Sched::RegPressure;
1198   if (!Itins->isEmpty() &&
1199       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1200     return Sched::ILP;
1201
1202   return Sched::RegPressure;
1203 }
1204
1205 //===----------------------------------------------------------------------===//
1206 // Lowering Code
1207 //===----------------------------------------------------------------------===//
1208
1209 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1210 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1211   switch (CC) {
1212   default: llvm_unreachable("Unknown condition code!");
1213   case ISD::SETNE:  return ARMCC::NE;
1214   case ISD::SETEQ:  return ARMCC::EQ;
1215   case ISD::SETGT:  return ARMCC::GT;
1216   case ISD::SETGE:  return ARMCC::GE;
1217   case ISD::SETLT:  return ARMCC::LT;
1218   case ISD::SETLE:  return ARMCC::LE;
1219   case ISD::SETUGT: return ARMCC::HI;
1220   case ISD::SETUGE: return ARMCC::HS;
1221   case ISD::SETULT: return ARMCC::LO;
1222   case ISD::SETULE: return ARMCC::LS;
1223   }
1224 }
1225
1226 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1227 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1228                         ARMCC::CondCodes &CondCode2) {
1229   CondCode2 = ARMCC::AL;
1230   switch (CC) {
1231   default: llvm_unreachable("Unknown FP condition!");
1232   case ISD::SETEQ:
1233   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1234   case ISD::SETGT:
1235   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1236   case ISD::SETGE:
1237   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1238   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1239   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1240   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1241   case ISD::SETO:   CondCode = ARMCC::VC; break;
1242   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1243   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1244   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1245   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1246   case ISD::SETLT:
1247   case ISD::SETULT: CondCode = ARMCC::LT; break;
1248   case ISD::SETLE:
1249   case ISD::SETULE: CondCode = ARMCC::LE; break;
1250   case ISD::SETNE:
1251   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1252   }
1253 }
1254
1255 //===----------------------------------------------------------------------===//
1256 //                      Calling Convention Implementation
1257 //===----------------------------------------------------------------------===//
1258
1259 #include "ARMGenCallingConv.inc"
1260
1261 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1262 /// account presence of floating point hardware and calling convention
1263 /// limitations, such as support for variadic functions.
1264 CallingConv::ID
1265 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1266                                            bool isVarArg) const {
1267   switch (CC) {
1268   default:
1269     llvm_unreachable("Unsupported calling convention");
1270   case CallingConv::ARM_AAPCS:
1271   case CallingConv::ARM_APCS:
1272   case CallingConv::GHC:
1273     return CC;
1274   case CallingConv::ARM_AAPCS_VFP:
1275     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1276   case CallingConv::C:
1277     if (!Subtarget->isAAPCS_ABI())
1278       return CallingConv::ARM_APCS;
1279     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1280              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1281              !isVarArg)
1282       return CallingConv::ARM_AAPCS_VFP;
1283     else
1284       return CallingConv::ARM_AAPCS;
1285   case CallingConv::Fast:
1286     if (!Subtarget->isAAPCS_ABI()) {
1287       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1288         return CallingConv::Fast;
1289       return CallingConv::ARM_APCS;
1290     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1291       return CallingConv::ARM_AAPCS_VFP;
1292     else
1293       return CallingConv::ARM_AAPCS;
1294   }
1295 }
1296
1297 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1298 /// CallingConvention.
1299 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1300                                                  bool Return,
1301                                                  bool isVarArg) const {
1302   switch (getEffectiveCallingConv(CC, isVarArg)) {
1303   default:
1304     llvm_unreachable("Unsupported calling convention");
1305   case CallingConv::ARM_APCS:
1306     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1307   case CallingConv::ARM_AAPCS:
1308     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1309   case CallingConv::ARM_AAPCS_VFP:
1310     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1311   case CallingConv::Fast:
1312     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1313   case CallingConv::GHC:
1314     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1315   }
1316 }
1317
1318 /// LowerCallResult - Lower the result values of a call into the
1319 /// appropriate copies out of appropriate physical registers.
1320 SDValue
1321 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1322                                    CallingConv::ID CallConv, bool isVarArg,
1323                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1324                                    SDLoc dl, SelectionDAG &DAG,
1325                                    SmallVectorImpl<SDValue> &InVals,
1326                                    bool isThisReturn, SDValue ThisVal) const {
1327
1328   // Assign locations to each value returned by this call.
1329   SmallVector<CCValAssign, 16> RVLocs;
1330   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1331                     *DAG.getContext(), Call);
1332   CCInfo.AnalyzeCallResult(Ins,
1333                            CCAssignFnForNode(CallConv, /* Return*/ true,
1334                                              isVarArg));
1335
1336   // Copy all of the result registers out of their specified physreg.
1337   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1338     CCValAssign VA = RVLocs[i];
1339
1340     // Pass 'this' value directly from the argument to return value, to avoid
1341     // reg unit interference
1342     if (i == 0 && isThisReturn) {
1343       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1344              "unexpected return calling convention register assignment");
1345       InVals.push_back(ThisVal);
1346       continue;
1347     }
1348
1349     SDValue Val;
1350     if (VA.needsCustom()) {
1351       // Handle f64 or half of a v2f64.
1352       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1353                                       InFlag);
1354       Chain = Lo.getValue(1);
1355       InFlag = Lo.getValue(2);
1356       VA = RVLocs[++i]; // skip ahead to next loc
1357       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1358                                       InFlag);
1359       Chain = Hi.getValue(1);
1360       InFlag = Hi.getValue(2);
1361       if (!Subtarget->isLittle())
1362         std::swap (Lo, Hi);
1363       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1364
1365       if (VA.getLocVT() == MVT::v2f64) {
1366         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1367         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1368                           DAG.getConstant(0, MVT::i32));
1369
1370         VA = RVLocs[++i]; // skip ahead to next loc
1371         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1372         Chain = Lo.getValue(1);
1373         InFlag = Lo.getValue(2);
1374         VA = RVLocs[++i]; // skip ahead to next loc
1375         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1376         Chain = Hi.getValue(1);
1377         InFlag = Hi.getValue(2);
1378         if (!Subtarget->isLittle())
1379           std::swap (Lo, Hi);
1380         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1381         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1382                           DAG.getConstant(1, MVT::i32));
1383       }
1384     } else {
1385       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1386                                InFlag);
1387       Chain = Val.getValue(1);
1388       InFlag = Val.getValue(2);
1389     }
1390
1391     switch (VA.getLocInfo()) {
1392     default: llvm_unreachable("Unknown loc info!");
1393     case CCValAssign::Full: break;
1394     case CCValAssign::BCvt:
1395       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1396       break;
1397     }
1398
1399     InVals.push_back(Val);
1400   }
1401
1402   return Chain;
1403 }
1404
1405 /// LowerMemOpCallTo - Store the argument to the stack.
1406 SDValue
1407 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1408                                     SDValue StackPtr, SDValue Arg,
1409                                     SDLoc dl, SelectionDAG &DAG,
1410                                     const CCValAssign &VA,
1411                                     ISD::ArgFlagsTy Flags) const {
1412   unsigned LocMemOffset = VA.getLocMemOffset();
1413   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1414   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1415   return DAG.getStore(Chain, dl, Arg, PtrOff,
1416                       MachinePointerInfo::getStack(LocMemOffset),
1417                       false, false, 0);
1418 }
1419
1420 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1421                                          SDValue Chain, SDValue &Arg,
1422                                          RegsToPassVector &RegsToPass,
1423                                          CCValAssign &VA, CCValAssign &NextVA,
1424                                          SDValue &StackPtr,
1425                                          SmallVectorImpl<SDValue> &MemOpChains,
1426                                          ISD::ArgFlagsTy Flags) const {
1427
1428   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1429                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1430   unsigned id = Subtarget->isLittle() ? 0 : 1;
1431   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1432
1433   if (NextVA.isRegLoc())
1434     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1435   else {
1436     assert(NextVA.isMemLoc());
1437     if (!StackPtr.getNode())
1438       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1439
1440     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1441                                            dl, DAG, NextVA,
1442                                            Flags));
1443   }
1444 }
1445
1446 /// LowerCall - Lowering a call into a callseq_start <-
1447 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1448 /// nodes.
1449 SDValue
1450 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1451                              SmallVectorImpl<SDValue> &InVals) const {
1452   SelectionDAG &DAG                     = CLI.DAG;
1453   SDLoc &dl                          = CLI.DL;
1454   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1455   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1456   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1457   SDValue Chain                         = CLI.Chain;
1458   SDValue Callee                        = CLI.Callee;
1459   bool &isTailCall                      = CLI.IsTailCall;
1460   CallingConv::ID CallConv              = CLI.CallConv;
1461   bool doesNotRet                       = CLI.DoesNotReturn;
1462   bool isVarArg                         = CLI.IsVarArg;
1463
1464   MachineFunction &MF = DAG.getMachineFunction();
1465   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1466   bool isThisReturn   = false;
1467   bool isSibCall      = false;
1468
1469   // Disable tail calls if they're not supported.
1470   if (!Subtarget->supportsTailCall() || MF.getTarget().Options.DisableTailCalls)
1471     isTailCall = false;
1472
1473   if (isTailCall) {
1474     // Check if it's really possible to do a tail call.
1475     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1476                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1477                                                    Outs, OutVals, Ins, DAG);
1478     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1479       report_fatal_error("failed to perform tail call elimination on a call "
1480                          "site marked musttail");
1481     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1482     // detected sibcalls.
1483     if (isTailCall) {
1484       ++NumTailCalls;
1485       isSibCall = true;
1486     }
1487   }
1488
1489   // Analyze operands of the call, assigning locations to each operand.
1490   SmallVector<CCValAssign, 16> ArgLocs;
1491   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1492                     *DAG.getContext(), Call);
1493   CCInfo.AnalyzeCallOperands(Outs,
1494                              CCAssignFnForNode(CallConv, /* Return*/ false,
1495                                                isVarArg));
1496
1497   // Get a count of how many bytes are to be pushed on the stack.
1498   unsigned NumBytes = CCInfo.getNextStackOffset();
1499
1500   // For tail calls, memory operands are available in our caller's stack.
1501   if (isSibCall)
1502     NumBytes = 0;
1503
1504   // Adjust the stack pointer for the new arguments...
1505   // These operations are automatically eliminated by the prolog/epilog pass
1506   if (!isSibCall)
1507     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1508                                  dl);
1509
1510   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1511
1512   RegsToPassVector RegsToPass;
1513   SmallVector<SDValue, 8> MemOpChains;
1514
1515   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1516   // of tail call optimization, arguments are handled later.
1517   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1518        i != e;
1519        ++i, ++realArgIdx) {
1520     CCValAssign &VA = ArgLocs[i];
1521     SDValue Arg = OutVals[realArgIdx];
1522     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1523     bool isByVal = Flags.isByVal();
1524
1525     // Promote the value if needed.
1526     switch (VA.getLocInfo()) {
1527     default: llvm_unreachable("Unknown loc info!");
1528     case CCValAssign::Full: break;
1529     case CCValAssign::SExt:
1530       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1531       break;
1532     case CCValAssign::ZExt:
1533       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1534       break;
1535     case CCValAssign::AExt:
1536       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1537       break;
1538     case CCValAssign::BCvt:
1539       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1540       break;
1541     }
1542
1543     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1544     if (VA.needsCustom()) {
1545       if (VA.getLocVT() == MVT::v2f64) {
1546         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1547                                   DAG.getConstant(0, MVT::i32));
1548         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1549                                   DAG.getConstant(1, MVT::i32));
1550
1551         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1552                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1553
1554         VA = ArgLocs[++i]; // skip ahead to next loc
1555         if (VA.isRegLoc()) {
1556           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1557                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1558         } else {
1559           assert(VA.isMemLoc());
1560
1561           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1562                                                  dl, DAG, VA, Flags));
1563         }
1564       } else {
1565         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1566                          StackPtr, MemOpChains, Flags);
1567       }
1568     } else if (VA.isRegLoc()) {
1569       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1570         assert(VA.getLocVT() == MVT::i32 &&
1571                "unexpected calling convention register assignment");
1572         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1573                "unexpected use of 'returned'");
1574         isThisReturn = true;
1575       }
1576       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1577     } else if (isByVal) {
1578       assert(VA.isMemLoc());
1579       unsigned offset = 0;
1580
1581       // True if this byval aggregate will be split between registers
1582       // and memory.
1583       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1584       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1585
1586       if (CurByValIdx < ByValArgsCount) {
1587
1588         unsigned RegBegin, RegEnd;
1589         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1590
1591         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1592         unsigned int i, j;
1593         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1594           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1595           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1596           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1597                                      MachinePointerInfo(),
1598                                      false, false, false,
1599                                      DAG.InferPtrAlignment(AddArg));
1600           MemOpChains.push_back(Load.getValue(1));
1601           RegsToPass.push_back(std::make_pair(j, Load));
1602         }
1603
1604         // If parameter size outsides register area, "offset" value
1605         // helps us to calculate stack slot for remained part properly.
1606         offset = RegEnd - RegBegin;
1607
1608         CCInfo.nextInRegsParam();
1609       }
1610
1611       if (Flags.getByValSize() > 4*offset) {
1612         unsigned LocMemOffset = VA.getLocMemOffset();
1613         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1614         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1615                                   StkPtrOff);
1616         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1617         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1618         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1619                                            MVT::i32);
1620         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1621
1622         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1623         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1624         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1625                                           Ops));
1626       }
1627     } else if (!isSibCall) {
1628       assert(VA.isMemLoc());
1629
1630       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1631                                              dl, DAG, VA, Flags));
1632     }
1633   }
1634
1635   if (!MemOpChains.empty())
1636     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1637
1638   // Build a sequence of copy-to-reg nodes chained together with token chain
1639   // and flag operands which copy the outgoing args into the appropriate regs.
1640   SDValue InFlag;
1641   // Tail call byval lowering might overwrite argument registers so in case of
1642   // tail call optimization the copies to registers are lowered later.
1643   if (!isTailCall)
1644     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1645       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1646                                RegsToPass[i].second, InFlag);
1647       InFlag = Chain.getValue(1);
1648     }
1649
1650   // For tail calls lower the arguments to the 'real' stack slot.
1651   if (isTailCall) {
1652     // Force all the incoming stack arguments to be loaded from the stack
1653     // before any new outgoing arguments are stored to the stack, because the
1654     // outgoing stack slots may alias the incoming argument stack slots, and
1655     // the alias isn't otherwise explicit. This is slightly more conservative
1656     // than necessary, because it means that each store effectively depends
1657     // on every argument instead of just those arguments it would clobber.
1658
1659     // Do not flag preceding copytoreg stuff together with the following stuff.
1660     InFlag = SDValue();
1661     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1662       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1663                                RegsToPass[i].second, InFlag);
1664       InFlag = Chain.getValue(1);
1665     }
1666     InFlag = SDValue();
1667   }
1668
1669   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1670   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1671   // node so that legalize doesn't hack it.
1672   bool isDirect = false;
1673   bool isARMFunc = false;
1674   bool isLocalARMFunc = false;
1675   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1676
1677   if (EnableARMLongCalls) {
1678     assert((Subtarget->isTargetWindows() ||
1679             getTargetMachine().getRelocationModel() == Reloc::Static) &&
1680            "long-calls with non-static relocation model!");
1681     // Handle a global address or an external symbol. If it's not one of
1682     // those, the target's already in a register, so we don't need to do
1683     // anything extra.
1684     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1685       const GlobalValue *GV = G->getGlobal();
1686       // Create a constant pool entry for the callee address
1687       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1688       ARMConstantPoolValue *CPV =
1689         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1690
1691       // Get the address of the callee into a register
1692       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1693       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1694       Callee = DAG.getLoad(getPointerTy(), dl,
1695                            DAG.getEntryNode(), CPAddr,
1696                            MachinePointerInfo::getConstantPool(),
1697                            false, false, false, 0);
1698     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1699       const char *Sym = S->getSymbol();
1700
1701       // Create a constant pool entry for the callee address
1702       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1703       ARMConstantPoolValue *CPV =
1704         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1705                                       ARMPCLabelIndex, 0);
1706       // Get the address of the callee into a register
1707       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1708       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1709       Callee = DAG.getLoad(getPointerTy(), dl,
1710                            DAG.getEntryNode(), CPAddr,
1711                            MachinePointerInfo::getConstantPool(),
1712                            false, false, false, 0);
1713     }
1714   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1715     const GlobalValue *GV = G->getGlobal();
1716     isDirect = true;
1717     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1718     bool isStub = (isExt && Subtarget->isTargetMachO()) &&
1719                    getTargetMachine().getRelocationModel() != Reloc::Static;
1720     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1721     // ARM call to a local ARM function is predicable.
1722     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1723     // tBX takes a register source operand.
1724     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1725       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1726       Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1727                            DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
1728                                                       0, ARMII::MO_NONLAZY));
1729       Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
1730                            MachinePointerInfo::getGOT(), false, false, true, 0);
1731     } else if (Subtarget->isTargetCOFF()) {
1732       assert(Subtarget->isTargetWindows() &&
1733              "Windows is the only supported COFF target");
1734       unsigned TargetFlags = GV->hasDLLImportStorageClass()
1735                                  ? ARMII::MO_DLLIMPORT
1736                                  : ARMII::MO_NO_FLAG;
1737       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), /*Offset=*/0,
1738                                           TargetFlags);
1739       if (GV->hasDLLImportStorageClass())
1740         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
1741                              DAG.getNode(ARMISD::Wrapper, dl, getPointerTy(),
1742                                          Callee), MachinePointerInfo::getGOT(),
1743                              false, false, false, 0);
1744     } else {
1745       // On ELF targets for PIC code, direct calls should go through the PLT
1746       unsigned OpFlags = 0;
1747       if (Subtarget->isTargetELF() &&
1748           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1749         OpFlags = ARMII::MO_PLT;
1750       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1751     }
1752   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1753     isDirect = true;
1754     bool isStub = Subtarget->isTargetMachO() &&
1755                   getTargetMachine().getRelocationModel() != Reloc::Static;
1756     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1757     // tBX takes a register source operand.
1758     const char *Sym = S->getSymbol();
1759     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1760       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1761       ARMConstantPoolValue *CPV =
1762         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1763                                       ARMPCLabelIndex, 4);
1764       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1765       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1766       Callee = DAG.getLoad(getPointerTy(), dl,
1767                            DAG.getEntryNode(), CPAddr,
1768                            MachinePointerInfo::getConstantPool(),
1769                            false, false, false, 0);
1770       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1771       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1772                            getPointerTy(), Callee, PICLabel);
1773     } else {
1774       unsigned OpFlags = 0;
1775       // On ELF targets for PIC code, direct calls should go through the PLT
1776       if (Subtarget->isTargetELF() &&
1777                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1778         OpFlags = ARMII::MO_PLT;
1779       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1780     }
1781   }
1782
1783   // FIXME: handle tail calls differently.
1784   unsigned CallOpc;
1785   bool HasMinSizeAttr = MF.getFunction()->hasFnAttribute(Attribute::MinSize);
1786   if (Subtarget->isThumb()) {
1787     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1788       CallOpc = ARMISD::CALL_NOLINK;
1789     else
1790       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1791   } else {
1792     if (!isDirect && !Subtarget->hasV5TOps())
1793       CallOpc = ARMISD::CALL_NOLINK;
1794     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1795                // Emit regular call when code size is the priority
1796                !HasMinSizeAttr)
1797       // "mov lr, pc; b _foo" to avoid confusing the RSP
1798       CallOpc = ARMISD::CALL_NOLINK;
1799     else
1800       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1801   }
1802
1803   std::vector<SDValue> Ops;
1804   Ops.push_back(Chain);
1805   Ops.push_back(Callee);
1806
1807   // Add argument registers to the end of the list so that they are known live
1808   // into the call.
1809   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1810     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1811                                   RegsToPass[i].second.getValueType()));
1812
1813   // Add a register mask operand representing the call-preserved registers.
1814   if (!isTailCall) {
1815     const uint32_t *Mask;
1816     const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
1817     if (isThisReturn) {
1818       // For 'this' returns, use the R0-preserving mask if applicable
1819       Mask = ARI->getThisReturnPreservedMask(CallConv);
1820       if (!Mask) {
1821         // Set isThisReturn to false if the calling convention is not one that
1822         // allows 'returned' to be modeled in this way, so LowerCallResult does
1823         // not try to pass 'this' straight through
1824         isThisReturn = false;
1825         Mask = ARI->getCallPreservedMask(CallConv);
1826       }
1827     } else
1828       Mask = ARI->getCallPreservedMask(CallConv);
1829
1830     assert(Mask && "Missing call preserved mask for calling convention");
1831     Ops.push_back(DAG.getRegisterMask(Mask));
1832   }
1833
1834   if (InFlag.getNode())
1835     Ops.push_back(InFlag);
1836
1837   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1838   if (isTailCall)
1839     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1840
1841   // Returns a chain and a flag for retval copy to use.
1842   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1843   InFlag = Chain.getValue(1);
1844
1845   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1846                              DAG.getIntPtrConstant(0, true), InFlag, dl);
1847   if (!Ins.empty())
1848     InFlag = Chain.getValue(1);
1849
1850   // Handle result values, copying them out of physregs into vregs that we
1851   // return.
1852   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1853                          InVals, isThisReturn,
1854                          isThisReturn ? OutVals[0] : SDValue());
1855 }
1856
1857 /// HandleByVal - Every parameter *after* a byval parameter is passed
1858 /// on the stack.  Remember the next parameter register to allocate,
1859 /// and then confiscate the rest of the parameter registers to insure
1860 /// this.
1861 void
1862 ARMTargetLowering::HandleByVal(
1863     CCState *State, unsigned &size, unsigned Align) const {
1864   unsigned reg = State->AllocateReg(GPRArgRegs);
1865   assert((State->getCallOrPrologue() == Prologue ||
1866           State->getCallOrPrologue() == Call) &&
1867          "unhandled ParmContext");
1868
1869   if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1870     if (Subtarget->isAAPCS_ABI() && Align > 4) {
1871       unsigned AlignInRegs = Align / 4;
1872       unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1873       for (unsigned i = 0; i < Waste; ++i)
1874         reg = State->AllocateReg(GPRArgRegs);
1875     }
1876     if (reg != 0) {
1877       unsigned excess = 4 * (ARM::R4 - reg);
1878
1879       // Special case when NSAA != SP and parameter size greater than size of
1880       // all remained GPR regs. In that case we can't split parameter, we must
1881       // send it to stack. We also must set NCRN to R4, so waste all
1882       // remained registers.
1883       const unsigned NSAAOffset = State->getNextStackOffset();
1884       if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1885         while (State->AllocateReg(GPRArgRegs))
1886           ;
1887         return;
1888       }
1889
1890       // First register for byval parameter is the first register that wasn't
1891       // allocated before this method call, so it would be "reg".
1892       // If parameter is small enough to be saved in range [reg, r4), then
1893       // the end (first after last) register would be reg + param-size-in-regs,
1894       // else parameter would be splitted between registers and stack,
1895       // end register would be r4 in this case.
1896       unsigned ByValRegBegin = reg;
1897       unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1898       State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1899       // Note, first register is allocated in the beginning of function already,
1900       // allocate remained amount of registers we need.
1901       for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1902         State->AllocateReg(GPRArgRegs);
1903       // A byval parameter that is split between registers and memory needs its
1904       // size truncated here.
1905       // In the case where the entire structure fits in registers, we set the
1906       // size in memory to zero.
1907       if (size < excess)
1908         size = 0;
1909       else
1910         size -= excess;
1911     }
1912   }
1913 }
1914
1915 /// MatchingStackOffset - Return true if the given stack call argument is
1916 /// already available in the same position (relatively) of the caller's
1917 /// incoming argument stack.
1918 static
1919 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1920                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1921                          const TargetInstrInfo *TII) {
1922   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1923   int FI = INT_MAX;
1924   if (Arg.getOpcode() == ISD::CopyFromReg) {
1925     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1926     if (!TargetRegisterInfo::isVirtualRegister(VR))
1927       return false;
1928     MachineInstr *Def = MRI->getVRegDef(VR);
1929     if (!Def)
1930       return false;
1931     if (!Flags.isByVal()) {
1932       if (!TII->isLoadFromStackSlot(Def, FI))
1933         return false;
1934     } else {
1935       return false;
1936     }
1937   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1938     if (Flags.isByVal())
1939       // ByVal argument is passed in as a pointer but it's now being
1940       // dereferenced. e.g.
1941       // define @foo(%struct.X* %A) {
1942       //   tail call @bar(%struct.X* byval %A)
1943       // }
1944       return false;
1945     SDValue Ptr = Ld->getBasePtr();
1946     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1947     if (!FINode)
1948       return false;
1949     FI = FINode->getIndex();
1950   } else
1951     return false;
1952
1953   assert(FI != INT_MAX);
1954   if (!MFI->isFixedObjectIndex(FI))
1955     return false;
1956   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1957 }
1958
1959 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1960 /// for tail call optimization. Targets which want to do tail call
1961 /// optimization should implement this function.
1962 bool
1963 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1964                                                      CallingConv::ID CalleeCC,
1965                                                      bool isVarArg,
1966                                                      bool isCalleeStructRet,
1967                                                      bool isCallerStructRet,
1968                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1969                                     const SmallVectorImpl<SDValue> &OutVals,
1970                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1971                                                      SelectionDAG& DAG) const {
1972   const Function *CallerF = DAG.getMachineFunction().getFunction();
1973   CallingConv::ID CallerCC = CallerF->getCallingConv();
1974   bool CCMatch = CallerCC == CalleeCC;
1975
1976   // Look for obvious safe cases to perform tail call optimization that do not
1977   // require ABI changes. This is what gcc calls sibcall.
1978
1979   // Do not sibcall optimize vararg calls unless the call site is not passing
1980   // any arguments.
1981   if (isVarArg && !Outs.empty())
1982     return false;
1983
1984   // Exception-handling functions need a special set of instructions to indicate
1985   // a return to the hardware. Tail-calling another function would probably
1986   // break this.
1987   if (CallerF->hasFnAttribute("interrupt"))
1988     return false;
1989
1990   // Also avoid sibcall optimization if either caller or callee uses struct
1991   // return semantics.
1992   if (isCalleeStructRet || isCallerStructRet)
1993     return false;
1994
1995   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1996   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1997   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1998   // support in the assembler and linker to be used. This would need to be
1999   // fixed to fully support tail calls in Thumb1.
2000   //
2001   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
2002   // LR.  This means if we need to reload LR, it takes an extra instructions,
2003   // which outweighs the value of the tail call; but here we don't know yet
2004   // whether LR is going to be used.  Probably the right approach is to
2005   // generate the tail call here and turn it back into CALL/RET in
2006   // emitEpilogue if LR is used.
2007
2008   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
2009   // but we need to make sure there are enough registers; the only valid
2010   // registers are the 4 used for parameters.  We don't currently do this
2011   // case.
2012   if (Subtarget->isThumb1Only())
2013     return false;
2014
2015   // Externally-defined functions with weak linkage should not be
2016   // tail-called on ARM when the OS does not support dynamic
2017   // pre-emption of symbols, as the AAELF spec requires normal calls
2018   // to undefined weak functions to be replaced with a NOP or jump to the
2019   // next instruction. The behaviour of branch instructions in this
2020   // situation (as used for tail calls) is implementation-defined, so we
2021   // cannot rely on the linker replacing the tail call with a return.
2022   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2023     const GlobalValue *GV = G->getGlobal();
2024     const Triple TT(getTargetMachine().getTargetTriple());
2025     if (GV->hasExternalWeakLinkage() &&
2026         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2027       return false;
2028   }
2029
2030   // If the calling conventions do not match, then we'd better make sure the
2031   // results are returned in the same way as what the caller expects.
2032   if (!CCMatch) {
2033     SmallVector<CCValAssign, 16> RVLocs1;
2034     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2035                        *DAG.getContext(), Call);
2036     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2037
2038     SmallVector<CCValAssign, 16> RVLocs2;
2039     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2040                        *DAG.getContext(), Call);
2041     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2042
2043     if (RVLocs1.size() != RVLocs2.size())
2044       return false;
2045     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2046       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2047         return false;
2048       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2049         return false;
2050       if (RVLocs1[i].isRegLoc()) {
2051         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2052           return false;
2053       } else {
2054         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2055           return false;
2056       }
2057     }
2058   }
2059
2060   // If Caller's vararg or byval argument has been split between registers and
2061   // stack, do not perform tail call, since part of the argument is in caller's
2062   // local frame.
2063   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2064                                       getInfo<ARMFunctionInfo>();
2065   if (AFI_Caller->getArgRegsSaveSize())
2066     return false;
2067
2068   // If the callee takes no arguments then go on to check the results of the
2069   // call.
2070   if (!Outs.empty()) {
2071     // Check if stack adjustment is needed. For now, do not do this if any
2072     // argument is passed on the stack.
2073     SmallVector<CCValAssign, 16> ArgLocs;
2074     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2075                       *DAG.getContext(), Call);
2076     CCInfo.AnalyzeCallOperands(Outs,
2077                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2078     if (CCInfo.getNextStackOffset()) {
2079       MachineFunction &MF = DAG.getMachineFunction();
2080
2081       // Check if the arguments are already laid out in the right way as
2082       // the caller's fixed stack objects.
2083       MachineFrameInfo *MFI = MF.getFrameInfo();
2084       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2085       const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2086       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2087            i != e;
2088            ++i, ++realArgIdx) {
2089         CCValAssign &VA = ArgLocs[i];
2090         EVT RegVT = VA.getLocVT();
2091         SDValue Arg = OutVals[realArgIdx];
2092         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2093         if (VA.getLocInfo() == CCValAssign::Indirect)
2094           return false;
2095         if (VA.needsCustom()) {
2096           // f64 and vector types are split into multiple registers or
2097           // register/stack-slot combinations.  The types will not match
2098           // the registers; give up on memory f64 refs until we figure
2099           // out what to do about this.
2100           if (!VA.isRegLoc())
2101             return false;
2102           if (!ArgLocs[++i].isRegLoc())
2103             return false;
2104           if (RegVT == MVT::v2f64) {
2105             if (!ArgLocs[++i].isRegLoc())
2106               return false;
2107             if (!ArgLocs[++i].isRegLoc())
2108               return false;
2109           }
2110         } else if (!VA.isRegLoc()) {
2111           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2112                                    MFI, MRI, TII))
2113             return false;
2114         }
2115       }
2116     }
2117   }
2118
2119   return true;
2120 }
2121
2122 bool
2123 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2124                                   MachineFunction &MF, bool isVarArg,
2125                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2126                                   LLVMContext &Context) const {
2127   SmallVector<CCValAssign, 16> RVLocs;
2128   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2129   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2130                                                     isVarArg));
2131 }
2132
2133 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2134                                     SDLoc DL, SelectionDAG &DAG) {
2135   const MachineFunction &MF = DAG.getMachineFunction();
2136   const Function *F = MF.getFunction();
2137
2138   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2139
2140   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2141   // version of the "preferred return address". These offsets affect the return
2142   // instruction if this is a return from PL1 without hypervisor extensions.
2143   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2144   //    SWI:     0      "subs pc, lr, #0"
2145   //    ABORT:   +4     "subs pc, lr, #4"
2146   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2147   // UNDEF varies depending on where the exception came from ARM or Thumb
2148   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2149
2150   int64_t LROffset;
2151   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2152       IntKind == "ABORT")
2153     LROffset = 4;
2154   else if (IntKind == "SWI" || IntKind == "UNDEF")
2155     LROffset = 0;
2156   else
2157     report_fatal_error("Unsupported interrupt attribute. If present, value "
2158                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2159
2160   RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2161
2162   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2163 }
2164
2165 SDValue
2166 ARMTargetLowering::LowerReturn(SDValue Chain,
2167                                CallingConv::ID CallConv, bool isVarArg,
2168                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2169                                const SmallVectorImpl<SDValue> &OutVals,
2170                                SDLoc dl, SelectionDAG &DAG) const {
2171
2172   // CCValAssign - represent the assignment of the return value to a location.
2173   SmallVector<CCValAssign, 16> RVLocs;
2174
2175   // CCState - Info about the registers and stack slots.
2176   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2177                     *DAG.getContext(), Call);
2178
2179   // Analyze outgoing return values.
2180   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2181                                                isVarArg));
2182
2183   SDValue Flag;
2184   SmallVector<SDValue, 4> RetOps;
2185   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2186   bool isLittleEndian = Subtarget->isLittle();
2187
2188   MachineFunction &MF = DAG.getMachineFunction();
2189   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2190   AFI->setReturnRegsCount(RVLocs.size());
2191
2192   // Copy the result values into the output registers.
2193   for (unsigned i = 0, realRVLocIdx = 0;
2194        i != RVLocs.size();
2195        ++i, ++realRVLocIdx) {
2196     CCValAssign &VA = RVLocs[i];
2197     assert(VA.isRegLoc() && "Can only return in registers!");
2198
2199     SDValue Arg = OutVals[realRVLocIdx];
2200
2201     switch (VA.getLocInfo()) {
2202     default: llvm_unreachable("Unknown loc info!");
2203     case CCValAssign::Full: break;
2204     case CCValAssign::BCvt:
2205       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2206       break;
2207     }
2208
2209     if (VA.needsCustom()) {
2210       if (VA.getLocVT() == MVT::v2f64) {
2211         // Extract the first half and return it in two registers.
2212         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2213                                    DAG.getConstant(0, MVT::i32));
2214         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2215                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2216
2217         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2218                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2219                                  Flag);
2220         Flag = Chain.getValue(1);
2221         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2222         VA = RVLocs[++i]; // skip ahead to next loc
2223         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2224                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2225                                  Flag);
2226         Flag = Chain.getValue(1);
2227         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2228         VA = RVLocs[++i]; // skip ahead to next loc
2229
2230         // Extract the 2nd half and fall through to handle it as an f64 value.
2231         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2232                           DAG.getConstant(1, MVT::i32));
2233       }
2234       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2235       // available.
2236       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2237                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2238       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2239                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2240                                Flag);
2241       Flag = Chain.getValue(1);
2242       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2243       VA = RVLocs[++i]; // skip ahead to next loc
2244       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2245                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2246                                Flag);
2247     } else
2248       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2249
2250     // Guarantee that all emitted copies are
2251     // stuck together, avoiding something bad.
2252     Flag = Chain.getValue(1);
2253     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2254   }
2255
2256   // Update chain and glue.
2257   RetOps[0] = Chain;
2258   if (Flag.getNode())
2259     RetOps.push_back(Flag);
2260
2261   // CPUs which aren't M-class use a special sequence to return from
2262   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2263   // though we use "subs pc, lr, #N").
2264   //
2265   // M-class CPUs actually use a normal return sequence with a special
2266   // (hardware-provided) value in LR, so the normal code path works.
2267   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2268       !Subtarget->isMClass()) {
2269     if (Subtarget->isThumb1Only())
2270       report_fatal_error("interrupt attribute is not supported in Thumb1");
2271     return LowerInterruptReturn(RetOps, dl, DAG);
2272   }
2273
2274   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2275 }
2276
2277 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2278   if (N->getNumValues() != 1)
2279     return false;
2280   if (!N->hasNUsesOfValue(1, 0))
2281     return false;
2282
2283   SDValue TCChain = Chain;
2284   SDNode *Copy = *N->use_begin();
2285   if (Copy->getOpcode() == ISD::CopyToReg) {
2286     // If the copy has a glue operand, we conservatively assume it isn't safe to
2287     // perform a tail call.
2288     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2289       return false;
2290     TCChain = Copy->getOperand(0);
2291   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2292     SDNode *VMov = Copy;
2293     // f64 returned in a pair of GPRs.
2294     SmallPtrSet<SDNode*, 2> Copies;
2295     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2296          UI != UE; ++UI) {
2297       if (UI->getOpcode() != ISD::CopyToReg)
2298         return false;
2299       Copies.insert(*UI);
2300     }
2301     if (Copies.size() > 2)
2302       return false;
2303
2304     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2305          UI != UE; ++UI) {
2306       SDValue UseChain = UI->getOperand(0);
2307       if (Copies.count(UseChain.getNode()))
2308         // Second CopyToReg
2309         Copy = *UI;
2310       else {
2311         // We are at the top of this chain.
2312         // If the copy has a glue operand, we conservatively assume it
2313         // isn't safe to perform a tail call.
2314         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2315           return false;
2316         // First CopyToReg
2317         TCChain = UseChain;
2318       }
2319     }
2320   } else if (Copy->getOpcode() == ISD::BITCAST) {
2321     // f32 returned in a single GPR.
2322     if (!Copy->hasOneUse())
2323       return false;
2324     Copy = *Copy->use_begin();
2325     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2326       return false;
2327     // If the copy has a glue operand, we conservatively assume it isn't safe to
2328     // perform a tail call.
2329     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2330       return false;
2331     TCChain = Copy->getOperand(0);
2332   } else {
2333     return false;
2334   }
2335
2336   bool HasRet = false;
2337   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2338        UI != UE; ++UI) {
2339     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2340         UI->getOpcode() != ARMISD::INTRET_FLAG)
2341       return false;
2342     HasRet = true;
2343   }
2344
2345   if (!HasRet)
2346     return false;
2347
2348   Chain = TCChain;
2349   return true;
2350 }
2351
2352 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2353   if (!Subtarget->supportsTailCall())
2354     return false;
2355
2356   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2357     return false;
2358
2359   return !Subtarget->isThumb1Only();
2360 }
2361
2362 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2363 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2364 // one of the above mentioned nodes. It has to be wrapped because otherwise
2365 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2366 // be used to form addressing mode. These wrapped nodes will be selected
2367 // into MOVi.
2368 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2369   EVT PtrVT = Op.getValueType();
2370   // FIXME there is no actual debug info here
2371   SDLoc dl(Op);
2372   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2373   SDValue Res;
2374   if (CP->isMachineConstantPoolEntry())
2375     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2376                                     CP->getAlignment());
2377   else
2378     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2379                                     CP->getAlignment());
2380   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2381 }
2382
2383 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2384   return MachineJumpTableInfo::EK_Inline;
2385 }
2386
2387 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2388                                              SelectionDAG &DAG) const {
2389   MachineFunction &MF = DAG.getMachineFunction();
2390   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2391   unsigned ARMPCLabelIndex = 0;
2392   SDLoc DL(Op);
2393   EVT PtrVT = getPointerTy();
2394   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2395   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2396   SDValue CPAddr;
2397   if (RelocM == Reloc::Static) {
2398     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2399   } else {
2400     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2401     ARMPCLabelIndex = AFI->createPICLabelUId();
2402     ARMConstantPoolValue *CPV =
2403       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2404                                       ARMCP::CPBlockAddress, PCAdj);
2405     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2406   }
2407   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2408   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2409                                MachinePointerInfo::getConstantPool(),
2410                                false, false, false, 0);
2411   if (RelocM == Reloc::Static)
2412     return Result;
2413   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2414   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2415 }
2416
2417 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2418 SDValue
2419 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2420                                                  SelectionDAG &DAG) const {
2421   SDLoc dl(GA);
2422   EVT PtrVT = getPointerTy();
2423   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2424   MachineFunction &MF = DAG.getMachineFunction();
2425   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2426   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2427   ARMConstantPoolValue *CPV =
2428     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2429                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2430   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2431   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2432   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2433                          MachinePointerInfo::getConstantPool(),
2434                          false, false, false, 0);
2435   SDValue Chain = Argument.getValue(1);
2436
2437   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2438   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2439
2440   // call __tls_get_addr.
2441   ArgListTy Args;
2442   ArgListEntry Entry;
2443   Entry.Node = Argument;
2444   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2445   Args.push_back(Entry);
2446
2447   // FIXME: is there useful debug info available here?
2448   TargetLowering::CallLoweringInfo CLI(DAG);
2449   CLI.setDebugLoc(dl).setChain(Chain)
2450     .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2451                DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2452                0);
2453
2454   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2455   return CallResult.first;
2456 }
2457
2458 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2459 // "local exec" model.
2460 SDValue
2461 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2462                                         SelectionDAG &DAG,
2463                                         TLSModel::Model model) const {
2464   const GlobalValue *GV = GA->getGlobal();
2465   SDLoc dl(GA);
2466   SDValue Offset;
2467   SDValue Chain = DAG.getEntryNode();
2468   EVT PtrVT = getPointerTy();
2469   // Get the Thread Pointer
2470   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2471
2472   if (model == TLSModel::InitialExec) {
2473     MachineFunction &MF = DAG.getMachineFunction();
2474     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2475     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2476     // Initial exec model.
2477     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2478     ARMConstantPoolValue *CPV =
2479       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2480                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2481                                       true);
2482     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2483     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2484     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2485                          MachinePointerInfo::getConstantPool(),
2486                          false, false, false, 0);
2487     Chain = Offset.getValue(1);
2488
2489     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2490     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2491
2492     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2493                          MachinePointerInfo::getConstantPool(),
2494                          false, false, false, 0);
2495   } else {
2496     // local exec model
2497     assert(model == TLSModel::LocalExec);
2498     ARMConstantPoolValue *CPV =
2499       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2500     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2501     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2502     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2503                          MachinePointerInfo::getConstantPool(),
2504                          false, false, false, 0);
2505   }
2506
2507   // The address of the thread local variable is the add of the thread
2508   // pointer with the offset of the variable.
2509   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2510 }
2511
2512 SDValue
2513 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2514   // TODO: implement the "local dynamic" model
2515   assert(Subtarget->isTargetELF() &&
2516          "TLS not implemented for non-ELF targets");
2517   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2518
2519   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2520
2521   switch (model) {
2522     case TLSModel::GeneralDynamic:
2523     case TLSModel::LocalDynamic:
2524       return LowerToTLSGeneralDynamicModel(GA, DAG);
2525     case TLSModel::InitialExec:
2526     case TLSModel::LocalExec:
2527       return LowerToTLSExecModels(GA, DAG, model);
2528   }
2529   llvm_unreachable("bogus TLS model");
2530 }
2531
2532 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2533                                                  SelectionDAG &DAG) const {
2534   EVT PtrVT = getPointerTy();
2535   SDLoc dl(Op);
2536   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2537   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2538     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2539     ARMConstantPoolValue *CPV =
2540       ARMConstantPoolConstant::Create(GV,
2541                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2542     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2543     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2544     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2545                                  CPAddr,
2546                                  MachinePointerInfo::getConstantPool(),
2547                                  false, false, false, 0);
2548     SDValue Chain = Result.getValue(1);
2549     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2550     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2551     if (!UseGOTOFF)
2552       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2553                            MachinePointerInfo::getGOT(),
2554                            false, false, false, 0);
2555     return Result;
2556   }
2557
2558   // If we have T2 ops, we can materialize the address directly via movt/movw
2559   // pair. This is always cheaper.
2560   if (Subtarget->useMovt(DAG.getMachineFunction())) {
2561     ++NumMovwMovt;
2562     // FIXME: Once remat is capable of dealing with instructions with register
2563     // operands, expand this into two nodes.
2564     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2565                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2566   } else {
2567     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2568     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2569     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2570                        MachinePointerInfo::getConstantPool(),
2571                        false, false, false, 0);
2572   }
2573 }
2574
2575 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2576                                                     SelectionDAG &DAG) const {
2577   EVT PtrVT = getPointerTy();
2578   SDLoc dl(Op);
2579   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2580   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2581
2582   if (Subtarget->useMovt(DAG.getMachineFunction()))
2583     ++NumMovwMovt;
2584
2585   // FIXME: Once remat is capable of dealing with instructions with register
2586   // operands, expand this into multiple nodes
2587   unsigned Wrapper =
2588       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2589
2590   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2591   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2592
2593   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2594     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2595                          MachinePointerInfo::getGOT(), false, false, false, 0);
2596   return Result;
2597 }
2598
2599 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2600                                                      SelectionDAG &DAG) const {
2601   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2602   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2603          "Windows on ARM expects to use movw/movt");
2604
2605   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2606   const ARMII::TOF TargetFlags =
2607     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2608   EVT PtrVT = getPointerTy();
2609   SDValue Result;
2610   SDLoc DL(Op);
2611
2612   ++NumMovwMovt;
2613
2614   // FIXME: Once remat is capable of dealing with instructions with register
2615   // operands, expand this into two nodes.
2616   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2617                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2618                                                   TargetFlags));
2619   if (GV->hasDLLImportStorageClass())
2620     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2621                          MachinePointerInfo::getGOT(), false, false, false, 0);
2622   return Result;
2623 }
2624
2625 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2626                                                     SelectionDAG &DAG) const {
2627   assert(Subtarget->isTargetELF() &&
2628          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2629   MachineFunction &MF = DAG.getMachineFunction();
2630   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2631   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2632   EVT PtrVT = getPointerTy();
2633   SDLoc dl(Op);
2634   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2635   ARMConstantPoolValue *CPV =
2636     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2637                                   ARMPCLabelIndex, PCAdj);
2638   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2639   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2640   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2641                                MachinePointerInfo::getConstantPool(),
2642                                false, false, false, 0);
2643   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2644   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2645 }
2646
2647 SDValue
2648 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2649   SDLoc dl(Op);
2650   SDValue Val = DAG.getConstant(0, MVT::i32);
2651   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2652                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2653                      Op.getOperand(1), Val);
2654 }
2655
2656 SDValue
2657 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2658   SDLoc dl(Op);
2659   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2660                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2661 }
2662
2663 SDValue
2664 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2665                                           const ARMSubtarget *Subtarget) const {
2666   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2667   SDLoc dl(Op);
2668   switch (IntNo) {
2669   default: return SDValue();    // Don't custom lower most intrinsics.
2670   case Intrinsic::arm_rbit: {
2671     assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2672            "RBIT intrinsic must have i32 type!");
2673     return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1));
2674   }
2675   case Intrinsic::arm_thread_pointer: {
2676     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2677     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2678   }
2679   case Intrinsic::eh_sjlj_lsda: {
2680     MachineFunction &MF = DAG.getMachineFunction();
2681     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2682     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2683     EVT PtrVT = getPointerTy();
2684     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2685     SDValue CPAddr;
2686     unsigned PCAdj = (RelocM != Reloc::PIC_)
2687       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2688     ARMConstantPoolValue *CPV =
2689       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2690                                       ARMCP::CPLSDA, PCAdj);
2691     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2692     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2693     SDValue Result =
2694       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2695                   MachinePointerInfo::getConstantPool(),
2696                   false, false, false, 0);
2697
2698     if (RelocM == Reloc::PIC_) {
2699       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2700       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2701     }
2702     return Result;
2703   }
2704   case Intrinsic::arm_neon_vmulls:
2705   case Intrinsic::arm_neon_vmullu: {
2706     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2707       ? ARMISD::VMULLs : ARMISD::VMULLu;
2708     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2709                        Op.getOperand(1), Op.getOperand(2));
2710   }
2711   }
2712 }
2713
2714 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2715                                  const ARMSubtarget *Subtarget) {
2716   // FIXME: handle "fence singlethread" more efficiently.
2717   SDLoc dl(Op);
2718   if (!Subtarget->hasDataBarrier()) {
2719     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2720     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2721     // here.
2722     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2723            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2724     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2725                        DAG.getConstant(0, MVT::i32));
2726   }
2727
2728   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2729   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2730   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
2731   if (Subtarget->isMClass()) {
2732     // Only a full system barrier exists in the M-class architectures.
2733     Domain = ARM_MB::SY;
2734   } else if (Subtarget->isSwift() && Ord == Release) {
2735     // Swift happens to implement ISHST barriers in a way that's compatible with
2736     // Release semantics but weaker than ISH so we'd be fools not to use
2737     // it. Beware: other processors probably don't!
2738     Domain = ARM_MB::ISHST;
2739   }
2740
2741   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2742                      DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2743                      DAG.getConstant(Domain, MVT::i32));
2744 }
2745
2746 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2747                              const ARMSubtarget *Subtarget) {
2748   // ARM pre v5TE and Thumb1 does not have preload instructions.
2749   if (!(Subtarget->isThumb2() ||
2750         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2751     // Just preserve the chain.
2752     return Op.getOperand(0);
2753
2754   SDLoc dl(Op);
2755   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2756   if (!isRead &&
2757       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2758     // ARMv7 with MP extension has PLDW.
2759     return Op.getOperand(0);
2760
2761   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2762   if (Subtarget->isThumb()) {
2763     // Invert the bits.
2764     isRead = ~isRead & 1;
2765     isData = ~isData & 1;
2766   }
2767
2768   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2769                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2770                      DAG.getConstant(isData, MVT::i32));
2771 }
2772
2773 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2774   MachineFunction &MF = DAG.getMachineFunction();
2775   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2776
2777   // vastart just stores the address of the VarArgsFrameIndex slot into the
2778   // memory location argument.
2779   SDLoc dl(Op);
2780   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2781   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2782   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2783   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2784                       MachinePointerInfo(SV), false, false, 0);
2785 }
2786
2787 SDValue
2788 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2789                                         SDValue &Root, SelectionDAG &DAG,
2790                                         SDLoc dl) const {
2791   MachineFunction &MF = DAG.getMachineFunction();
2792   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2793
2794   const TargetRegisterClass *RC;
2795   if (AFI->isThumb1OnlyFunction())
2796     RC = &ARM::tGPRRegClass;
2797   else
2798     RC = &ARM::GPRRegClass;
2799
2800   // Transform the arguments stored in physical registers into virtual ones.
2801   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2802   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2803
2804   SDValue ArgValue2;
2805   if (NextVA.isMemLoc()) {
2806     MachineFrameInfo *MFI = MF.getFrameInfo();
2807     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2808
2809     // Create load node to retrieve arguments from the stack.
2810     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2811     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2812                             MachinePointerInfo::getFixedStack(FI),
2813                             false, false, false, 0);
2814   } else {
2815     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2816     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2817   }
2818   if (!Subtarget->isLittle())
2819     std::swap (ArgValue, ArgValue2);
2820   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2821 }
2822
2823 void
2824 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2825                                   unsigned InRegsParamRecordIdx,
2826                                   unsigned ArgSize,
2827                                   unsigned &ArgRegsSize,
2828                                   unsigned &ArgRegsSaveSize)
2829   const {
2830   unsigned NumGPRs;
2831   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2832     unsigned RBegin, REnd;
2833     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2834     NumGPRs = REnd - RBegin;
2835   } else {
2836     unsigned int firstUnalloced;
2837     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs);
2838     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2839   }
2840
2841   unsigned Align = Subtarget->getFrameLowering()->getStackAlignment();
2842   ArgRegsSize = NumGPRs * 4;
2843
2844   // If parameter is split between stack and GPRs...
2845   if (NumGPRs && Align > 4 &&
2846       (ArgRegsSize < ArgSize ||
2847         InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2848     // Add padding for part of param recovered from GPRs.  For example,
2849     // if Align == 8, its last byte must be at address K*8 - 1.
2850     // We need to do it, since remained (stack) part of parameter has
2851     // stack alignment, and we need to "attach" "GPRs head" without gaps
2852     // to it:
2853     // Stack:
2854     // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2855     // [ [padding] [GPRs head] ] [        Tail passed via stack       ....
2856     //
2857     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2858     unsigned Padding =
2859         OffsetToAlignment(ArgRegsSize + AFI->getArgRegsSaveSize(), Align);
2860     ArgRegsSaveSize = ArgRegsSize + Padding;
2861   } else
2862     // We don't need to extend regs save size for byval parameters if they
2863     // are passed via GPRs only.
2864     ArgRegsSaveSize = ArgRegsSize;
2865 }
2866
2867 // The remaining GPRs hold either the beginning of variable-argument
2868 // data, or the beginning of an aggregate passed by value (usually
2869 // byval).  Either way, we allocate stack slots adjacent to the data
2870 // provided by our caller, and store the unallocated registers there.
2871 // If this is a variadic function, the va_list pointer will begin with
2872 // these values; otherwise, this reassembles a (byval) structure that
2873 // was split between registers and memory.
2874 // Return: The frame index registers were stored into.
2875 int
2876 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2877                                   SDLoc dl, SDValue &Chain,
2878                                   const Value *OrigArg,
2879                                   unsigned InRegsParamRecordIdx,
2880                                   unsigned OffsetFromOrigArg,
2881                                   unsigned ArgOffset,
2882                                   unsigned ArgSize,
2883                                   bool ForceMutable,
2884                                   unsigned ByValStoreOffset,
2885                                   unsigned TotalArgRegsSaveSize) const {
2886
2887   // Currently, two use-cases possible:
2888   // Case #1. Non-var-args function, and we meet first byval parameter.
2889   //          Setup first unallocated register as first byval register;
2890   //          eat all remained registers
2891   //          (these two actions are performed by HandleByVal method).
2892   //          Then, here, we initialize stack frame with
2893   //          "store-reg" instructions.
2894   // Case #2. Var-args function, that doesn't contain byval parameters.
2895   //          The same: eat all remained unallocated registers,
2896   //          initialize stack frame.
2897
2898   MachineFunction &MF = DAG.getMachineFunction();
2899   MachineFrameInfo *MFI = MF.getFrameInfo();
2900   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2901   unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2902   unsigned RBegin, REnd;
2903   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2904     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2905     firstRegToSaveIndex = RBegin - ARM::R0;
2906     lastRegToSaveIndex = REnd - ARM::R0;
2907   } else {
2908     firstRegToSaveIndex = CCInfo.getFirstUnallocated(GPRArgRegs);
2909     lastRegToSaveIndex = 4;
2910   }
2911
2912   unsigned ArgRegsSize, ArgRegsSaveSize;
2913   computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2914                  ArgRegsSize, ArgRegsSaveSize);
2915
2916   // Store any by-val regs to their spots on the stack so that they may be
2917   // loaded by deferencing the result of formal parameter pointer or va_next.
2918   // Note: once stack area for byval/varargs registers
2919   // was initialized, it can't be initialized again.
2920   if (ArgRegsSaveSize) {
2921     unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2922
2923     if (Padding) {
2924       assert(AFI->getStoredByValParamsPadding() == 0 &&
2925              "The only parameter may be padded.");
2926       AFI->setStoredByValParamsPadding(Padding);
2927     }
2928
2929     int FrameIndex = MFI->CreateFixedObject(ArgRegsSaveSize,
2930                                             Padding +
2931                                               ByValStoreOffset -
2932                                               (int64_t)TotalArgRegsSaveSize,
2933                                             false);
2934     SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2935     if (Padding) {
2936        MFI->CreateFixedObject(Padding,
2937                               ArgOffset + ByValStoreOffset -
2938                                 (int64_t)ArgRegsSaveSize,
2939                               false);
2940     }
2941
2942     SmallVector<SDValue, 4> MemOps;
2943     for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2944          ++firstRegToSaveIndex, ++i) {
2945       const TargetRegisterClass *RC;
2946       if (AFI->isThumb1OnlyFunction())
2947         RC = &ARM::tGPRRegClass;
2948       else
2949         RC = &ARM::GPRRegClass;
2950
2951       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2952       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2953       SDValue Store =
2954         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2955                      MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2956                      false, false, 0);
2957       MemOps.push_back(Store);
2958       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2959                         DAG.getConstant(4, getPointerTy()));
2960     }
2961
2962     AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2963
2964     if (!MemOps.empty())
2965       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2966     return FrameIndex;
2967   } else {
2968     if (ArgSize == 0) {
2969       // We cannot allocate a zero-byte object for the first variadic argument,
2970       // so just make up a size.
2971       ArgSize = 4;
2972     }
2973     // This will point to the next argument passed via stack.
2974     return MFI->CreateFixedObject(
2975       ArgSize, ArgOffset, !ForceMutable);
2976   }
2977 }
2978
2979 // Setup stack frame, the va_list pointer will start from.
2980 void
2981 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2982                                         SDLoc dl, SDValue &Chain,
2983                                         unsigned ArgOffset,
2984                                         unsigned TotalArgRegsSaveSize,
2985                                         bool ForceMutable) const {
2986   MachineFunction &MF = DAG.getMachineFunction();
2987   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2988
2989   // Try to store any remaining integer argument regs
2990   // to their spots on the stack so that they may be loaded by deferencing
2991   // the result of va_next.
2992   // If there is no regs to be stored, just point address after last
2993   // argument passed via stack.
2994   int FrameIndex =
2995     StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
2996                    CCInfo.getInRegsParamsCount(), 0, ArgOffset, 0, ForceMutable,
2997                    0, TotalArgRegsSaveSize);
2998
2999   AFI->setVarArgsFrameIndex(FrameIndex);
3000 }
3001
3002 SDValue
3003 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
3004                                         CallingConv::ID CallConv, bool isVarArg,
3005                                         const SmallVectorImpl<ISD::InputArg>
3006                                           &Ins,
3007                                         SDLoc dl, SelectionDAG &DAG,
3008                                         SmallVectorImpl<SDValue> &InVals)
3009                                           const {
3010   MachineFunction &MF = DAG.getMachineFunction();
3011   MachineFrameInfo *MFI = MF.getFrameInfo();
3012
3013   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3014
3015   // Assign locations to all of the incoming arguments.
3016   SmallVector<CCValAssign, 16> ArgLocs;
3017   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3018                     *DAG.getContext(), Prologue);
3019   CCInfo.AnalyzeFormalArguments(Ins,
3020                                 CCAssignFnForNode(CallConv, /* Return*/ false,
3021                                                   isVarArg));
3022
3023   SmallVector<SDValue, 16> ArgValues;
3024   int lastInsIndex = -1;
3025   SDValue ArgValue;
3026   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3027   unsigned CurArgIdx = 0;
3028
3029   // Initially ArgRegsSaveSize is zero.
3030   // Then we increase this value each time we meet byval parameter.
3031   // We also increase this value in case of varargs function.
3032   AFI->setArgRegsSaveSize(0);
3033
3034   unsigned ByValStoreOffset = 0;
3035   unsigned TotalArgRegsSaveSize = 0;
3036   unsigned ArgRegsSaveSizeMaxAlign = 4;
3037
3038   // Calculate the amount of stack space that we need to allocate to store
3039   // byval and variadic arguments that are passed in registers.
3040   // We need to know this before we allocate the first byval or variadic
3041   // argument, as they will be allocated a stack slot below the CFA (Canonical
3042   // Frame Address, the stack pointer at entry to the function).
3043   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3044     CCValAssign &VA = ArgLocs[i];
3045     if (VA.isMemLoc()) {
3046       int index = VA.getValNo();
3047       if (index != lastInsIndex) {
3048         ISD::ArgFlagsTy Flags = Ins[index].Flags;
3049         if (Flags.isByVal()) {
3050           unsigned ExtraArgRegsSize;
3051           unsigned ExtraArgRegsSaveSize;
3052           computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsProcessed(),
3053                          Flags.getByValSize(),
3054                          ExtraArgRegsSize, ExtraArgRegsSaveSize);
3055
3056           TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
3057           if (Flags.getByValAlign() > ArgRegsSaveSizeMaxAlign)
3058               ArgRegsSaveSizeMaxAlign = Flags.getByValAlign();
3059           CCInfo.nextInRegsParam();
3060         }
3061         lastInsIndex = index;
3062       }
3063     }
3064   }
3065   CCInfo.rewindByValRegsInfo();
3066   lastInsIndex = -1;
3067   if (isVarArg && MFI->hasVAStart()) {
3068     unsigned ExtraArgRegsSize;
3069     unsigned ExtraArgRegsSaveSize;
3070     computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsCount(), 0,
3071                    ExtraArgRegsSize, ExtraArgRegsSaveSize);
3072     TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
3073   }
3074   // If the arg regs save area contains N-byte aligned values, the
3075   // bottom of it must be at least N-byte aligned.
3076   TotalArgRegsSaveSize = RoundUpToAlignment(TotalArgRegsSaveSize, ArgRegsSaveSizeMaxAlign);
3077   TotalArgRegsSaveSize = std::min(TotalArgRegsSaveSize, 16U);
3078
3079   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3080     CCValAssign &VA = ArgLocs[i];
3081     if (Ins[VA.getValNo()].isOrigArg()) {
3082       std::advance(CurOrigArg,
3083                    Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3084       CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3085     }
3086     // Arguments stored in registers.
3087     if (VA.isRegLoc()) {
3088       EVT RegVT = VA.getLocVT();
3089
3090       if (VA.needsCustom()) {
3091         // f64 and vector types are split up into multiple registers or
3092         // combinations of registers and stack slots.
3093         if (VA.getLocVT() == MVT::v2f64) {
3094           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3095                                                    Chain, DAG, dl);
3096           VA = ArgLocs[++i]; // skip ahead to next loc
3097           SDValue ArgValue2;
3098           if (VA.isMemLoc()) {
3099             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3100             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3101             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3102                                     MachinePointerInfo::getFixedStack(FI),
3103                                     false, false, false, 0);
3104           } else {
3105             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3106                                              Chain, DAG, dl);
3107           }
3108           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3109           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3110                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
3111           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3112                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
3113         } else
3114           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3115
3116       } else {
3117         const TargetRegisterClass *RC;
3118
3119         if (RegVT == MVT::f32)
3120           RC = &ARM::SPRRegClass;
3121         else if (RegVT == MVT::f64)
3122           RC = &ARM::DPRRegClass;
3123         else if (RegVT == MVT::v2f64)
3124           RC = &ARM::QPRRegClass;
3125         else if (RegVT == MVT::i32)
3126           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3127                                            : &ARM::GPRRegClass;
3128         else
3129           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3130
3131         // Transform the arguments in physical registers into virtual ones.
3132         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3133         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3134       }
3135
3136       // If this is an 8 or 16-bit value, it is really passed promoted
3137       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3138       // truncate to the right size.
3139       switch (VA.getLocInfo()) {
3140       default: llvm_unreachable("Unknown loc info!");
3141       case CCValAssign::Full: break;
3142       case CCValAssign::BCvt:
3143         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3144         break;
3145       case CCValAssign::SExt:
3146         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3147                                DAG.getValueType(VA.getValVT()));
3148         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3149         break;
3150       case CCValAssign::ZExt:
3151         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3152                                DAG.getValueType(VA.getValVT()));
3153         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3154         break;
3155       }
3156
3157       InVals.push_back(ArgValue);
3158
3159     } else { // VA.isRegLoc()
3160
3161       // sanity check
3162       assert(VA.isMemLoc());
3163       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3164
3165       int index = VA.getValNo();
3166
3167       // Some Ins[] entries become multiple ArgLoc[] entries.
3168       // Process them only once.
3169       if (index != lastInsIndex)
3170         {
3171           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3172           // FIXME: For now, all byval parameter objects are marked mutable.
3173           // This can be changed with more analysis.
3174           // In case of tail call optimization mark all arguments mutable.
3175           // Since they could be overwritten by lowering of arguments in case of
3176           // a tail call.
3177           if (Flags.isByVal()) {
3178             assert(Ins[index].isOrigArg() &&
3179                    "Byval arguments cannot be implicit");
3180             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3181
3182             ByValStoreOffset = RoundUpToAlignment(ByValStoreOffset, Flags.getByValAlign());
3183             int FrameIndex = StoreByValRegs(
3184                 CCInfo, DAG, dl, Chain, CurOrigArg,
3185                 CurByValIndex,
3186                 Ins[VA.getValNo()].PartOffset,
3187                 VA.getLocMemOffset(),
3188                 Flags.getByValSize(),
3189                 true /*force mutable frames*/,
3190                 ByValStoreOffset,
3191                 TotalArgRegsSaveSize);
3192             ByValStoreOffset += Flags.getByValSize();
3193             ByValStoreOffset = std::min(ByValStoreOffset, 16U);
3194             InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3195             CCInfo.nextInRegsParam();
3196           } else {
3197             unsigned FIOffset = VA.getLocMemOffset();
3198             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3199                                             FIOffset, true);
3200
3201             // Create load nodes to retrieve arguments from the stack.
3202             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3203             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3204                                          MachinePointerInfo::getFixedStack(FI),
3205                                          false, false, false, 0));
3206           }
3207           lastInsIndex = index;
3208         }
3209     }
3210   }
3211
3212   // varargs
3213   if (isVarArg && MFI->hasVAStart())
3214     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3215                          CCInfo.getNextStackOffset(),
3216                          TotalArgRegsSaveSize);
3217
3218   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3219
3220   return Chain;
3221 }
3222
3223 /// isFloatingPointZero - Return true if this is +0.0.
3224 static bool isFloatingPointZero(SDValue Op) {
3225   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3226     return CFP->getValueAPF().isPosZero();
3227   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3228     // Maybe this has already been legalized into the constant pool?
3229     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3230       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3231       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3232         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3233           return CFP->getValueAPF().isPosZero();
3234     }
3235   } else if (Op->getOpcode() == ISD::BITCAST &&
3236              Op->getValueType(0) == MVT::f64) {
3237     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3238     // created by LowerConstantFP().
3239     SDValue BitcastOp = Op->getOperand(0);
3240     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM) {
3241       SDValue MoveOp = BitcastOp->getOperand(0);
3242       if (MoveOp->getOpcode() == ISD::TargetConstant &&
3243           cast<ConstantSDNode>(MoveOp)->getZExtValue() == 0) {
3244         return true;
3245       }
3246     }
3247   }
3248   return false;
3249 }
3250
3251 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3252 /// the given operands.
3253 SDValue
3254 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3255                              SDValue &ARMcc, SelectionDAG &DAG,
3256                              SDLoc dl) const {
3257   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3258     unsigned C = RHSC->getZExtValue();
3259     if (!isLegalICmpImmediate(C)) {
3260       // Constant does not fit, try adjusting it by one?
3261       switch (CC) {
3262       default: break;
3263       case ISD::SETLT:
3264       case ISD::SETGE:
3265         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3266           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3267           RHS = DAG.getConstant(C-1, MVT::i32);
3268         }
3269         break;
3270       case ISD::SETULT:
3271       case ISD::SETUGE:
3272         if (C != 0 && isLegalICmpImmediate(C-1)) {
3273           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3274           RHS = DAG.getConstant(C-1, MVT::i32);
3275         }
3276         break;
3277       case ISD::SETLE:
3278       case ISD::SETGT:
3279         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3280           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3281           RHS = DAG.getConstant(C+1, MVT::i32);
3282         }
3283         break;
3284       case ISD::SETULE:
3285       case ISD::SETUGT:
3286         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3287           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3288           RHS = DAG.getConstant(C+1, MVT::i32);
3289         }
3290         break;
3291       }
3292     }
3293   }
3294
3295   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3296   ARMISD::NodeType CompareType;
3297   switch (CondCode) {
3298   default:
3299     CompareType = ARMISD::CMP;
3300     break;
3301   case ARMCC::EQ:
3302   case ARMCC::NE:
3303     // Uses only Z Flag
3304     CompareType = ARMISD::CMPZ;
3305     break;
3306   }
3307   ARMcc = DAG.getConstant(CondCode, MVT::i32);
3308   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3309 }
3310
3311 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3312 SDValue
3313 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3314                              SDLoc dl) const {
3315   assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3316   SDValue Cmp;
3317   if (!isFloatingPointZero(RHS))
3318     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3319   else
3320     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3321   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3322 }
3323
3324 /// duplicateCmp - Glue values can have only one use, so this function
3325 /// duplicates a comparison node.
3326 SDValue
3327 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3328   unsigned Opc = Cmp.getOpcode();
3329   SDLoc DL(Cmp);
3330   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3331     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3332
3333   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3334   Cmp = Cmp.getOperand(0);
3335   Opc = Cmp.getOpcode();
3336   if (Opc == ARMISD::CMPFP)
3337     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3338   else {
3339     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3340     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3341   }
3342   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3343 }
3344
3345 std::pair<SDValue, SDValue>
3346 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3347                                  SDValue &ARMcc) const {
3348   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3349
3350   SDValue Value, OverflowCmp;
3351   SDValue LHS = Op.getOperand(0);
3352   SDValue RHS = Op.getOperand(1);
3353
3354
3355   // FIXME: We are currently always generating CMPs because we don't support
3356   // generating CMN through the backend. This is not as good as the natural
3357   // CMP case because it causes a register dependency and cannot be folded
3358   // later.
3359
3360   switch (Op.getOpcode()) {
3361   default:
3362     llvm_unreachable("Unknown overflow instruction!");
3363   case ISD::SADDO:
3364     ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3365     Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3366     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3367     break;
3368   case ISD::UADDO:
3369     ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3370     Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3371     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3372     break;
3373   case ISD::SSUBO:
3374     ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3375     Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3376     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3377     break;
3378   case ISD::USUBO:
3379     ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3380     Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3381     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3382     break;
3383   } // switch (...)
3384
3385   return std::make_pair(Value, OverflowCmp);
3386 }
3387
3388
3389 SDValue
3390 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3391   // Let legalize expand this if it isn't a legal type yet.
3392   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3393     return SDValue();
3394
3395   SDValue Value, OverflowCmp;
3396   SDValue ARMcc;
3397   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3398   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3399   // We use 0 and 1 as false and true values.
3400   SDValue TVal = DAG.getConstant(1, MVT::i32);
3401   SDValue FVal = DAG.getConstant(0, MVT::i32);
3402   EVT VT = Op.getValueType();
3403
3404   SDValue Overflow = DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, TVal, FVal,
3405                                  ARMcc, CCR, OverflowCmp);
3406
3407   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3408   return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), VTs, Value, Overflow);
3409 }
3410
3411
3412 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3413   SDValue Cond = Op.getOperand(0);
3414   SDValue SelectTrue = Op.getOperand(1);
3415   SDValue SelectFalse = Op.getOperand(2);
3416   SDLoc dl(Op);
3417   unsigned Opc = Cond.getOpcode();
3418
3419   if (Cond.getResNo() == 1 &&
3420       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3421        Opc == ISD::USUBO)) {
3422     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3423       return SDValue();
3424
3425     SDValue Value, OverflowCmp;
3426     SDValue ARMcc;
3427     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3428     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3429     EVT VT = Op.getValueType();
3430
3431     return getCMOV(SDLoc(Op), VT, SelectTrue, SelectFalse, ARMcc, CCR,
3432                    OverflowCmp, DAG);
3433   }
3434
3435   // Convert:
3436   //
3437   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3438   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3439   //
3440   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3441     const ConstantSDNode *CMOVTrue =
3442       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3443     const ConstantSDNode *CMOVFalse =
3444       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3445
3446     if (CMOVTrue && CMOVFalse) {
3447       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3448       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3449
3450       SDValue True;
3451       SDValue False;
3452       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3453         True = SelectTrue;
3454         False = SelectFalse;
3455       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3456         True = SelectFalse;
3457         False = SelectTrue;
3458       }
3459
3460       if (True.getNode() && False.getNode()) {
3461         EVT VT = Op.getValueType();
3462         SDValue ARMcc = Cond.getOperand(2);
3463         SDValue CCR = Cond.getOperand(3);
3464         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3465         assert(True.getValueType() == VT);
3466         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3467       }
3468     }
3469   }
3470
3471   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3472   // undefined bits before doing a full-word comparison with zero.
3473   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3474                      DAG.getConstant(1, Cond.getValueType()));
3475
3476   return DAG.getSelectCC(dl, Cond,
3477                          DAG.getConstant(0, Cond.getValueType()),
3478                          SelectTrue, SelectFalse, ISD::SETNE);
3479 }
3480
3481 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3482   if (CC == ISD::SETNE)
3483     return ISD::SETEQ;
3484   return ISD::getSetCCInverse(CC, true);
3485 }
3486
3487 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3488                                  bool &swpCmpOps, bool &swpVselOps) {
3489   // Start by selecting the GE condition code for opcodes that return true for
3490   // 'equality'
3491   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3492       CC == ISD::SETULE)
3493     CondCode = ARMCC::GE;
3494
3495   // and GT for opcodes that return false for 'equality'.
3496   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3497            CC == ISD::SETULT)
3498     CondCode = ARMCC::GT;
3499
3500   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3501   // to swap the compare operands.
3502   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3503       CC == ISD::SETULT)
3504     swpCmpOps = true;
3505
3506   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3507   // If we have an unordered opcode, we need to swap the operands to the VSEL
3508   // instruction (effectively negating the condition).
3509   //
3510   // This also has the effect of swapping which one of 'less' or 'greater'
3511   // returns true, so we also swap the compare operands. It also switches
3512   // whether we return true for 'equality', so we compensate by picking the
3513   // opposite condition code to our original choice.
3514   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3515       CC == ISD::SETUGT) {
3516     swpCmpOps = !swpCmpOps;
3517     swpVselOps = !swpVselOps;
3518     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3519   }
3520
3521   // 'ordered' is 'anything but unordered', so use the VS condition code and
3522   // swap the VSEL operands.
3523   if (CC == ISD::SETO) {
3524     CondCode = ARMCC::VS;
3525     swpVselOps = true;
3526   }
3527
3528   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3529   // code and swap the VSEL operands.
3530   if (CC == ISD::SETUNE) {
3531     CondCode = ARMCC::EQ;
3532     swpVselOps = true;
3533   }
3534 }
3535
3536 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3537                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3538                                    SDValue Cmp, SelectionDAG &DAG) const {
3539   if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3540     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3541                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3542     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3543                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3544
3545     SDValue TrueLow = TrueVal.getValue(0);
3546     SDValue TrueHigh = TrueVal.getValue(1);
3547     SDValue FalseLow = FalseVal.getValue(0);
3548     SDValue FalseHigh = FalseVal.getValue(1);
3549
3550     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3551                               ARMcc, CCR, Cmp);
3552     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3553                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
3554
3555     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3556   } else {
3557     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3558                        Cmp);
3559   }
3560 }
3561
3562 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3563   EVT VT = Op.getValueType();
3564   SDValue LHS = Op.getOperand(0);
3565   SDValue RHS = Op.getOperand(1);
3566   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3567   SDValue TrueVal = Op.getOperand(2);
3568   SDValue FalseVal = Op.getOperand(3);
3569   SDLoc dl(Op);
3570
3571   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3572     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3573                                                     dl);
3574
3575     // If softenSetCCOperands only returned one value, we should compare it to
3576     // zero.
3577     if (!RHS.getNode()) {
3578       RHS = DAG.getConstant(0, LHS.getValueType());
3579       CC = ISD::SETNE;
3580     }
3581   }
3582
3583   if (LHS.getValueType() == MVT::i32) {
3584     // Try to generate VSEL on ARMv8.
3585     // The VSEL instruction can't use all the usual ARM condition
3586     // codes: it only has two bits to select the condition code, so it's
3587     // constrained to use only GE, GT, VS and EQ.
3588     //
3589     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3590     // swap the operands of the previous compare instruction (effectively
3591     // inverting the compare condition, swapping 'less' and 'greater') and
3592     // sometimes need to swap the operands to the VSEL (which inverts the
3593     // condition in the sense of firing whenever the previous condition didn't)
3594     if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3595                                     TrueVal.getValueType() == MVT::f64)) {
3596       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3597       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3598           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3599         CC = getInverseCCForVSEL(CC);
3600         std::swap(TrueVal, FalseVal);
3601       }
3602     }
3603
3604     SDValue ARMcc;
3605     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3606     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3607     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3608   }
3609
3610   ARMCC::CondCodes CondCode, CondCode2;
3611   FPCCToARMCC(CC, CondCode, CondCode2);
3612
3613   // Try to generate VSEL on ARMv8.
3614   if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3615                                   TrueVal.getValueType() == MVT::f64)) {
3616     // We can select VMAXNM/VMINNM from a compare followed by a select with the
3617     // same operands, as follows:
3618     //   c = fcmp [ogt, olt, ugt, ult] a, b
3619     //   select c, a, b
3620     // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3621     // handled differently than the original code sequence.
3622     if (getTargetMachine().Options.UnsafeFPMath) {
3623       if (LHS == TrueVal && RHS == FalseVal) {
3624         if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3625           return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3626         if (CC == ISD::SETOLT || CC == ISD::SETULT)
3627           return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3628       } else if (LHS == FalseVal && RHS == TrueVal) {
3629         if (CC == ISD::SETOLT || CC == ISD::SETULT)
3630           return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3631         if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3632           return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3633       }
3634     }
3635
3636     bool swpCmpOps = false;
3637     bool swpVselOps = false;
3638     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3639
3640     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3641         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3642       if (swpCmpOps)
3643         std::swap(LHS, RHS);
3644       if (swpVselOps)
3645         std::swap(TrueVal, FalseVal);
3646     }
3647   }
3648
3649   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3650   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3651   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3652   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3653   if (CondCode2 != ARMCC::AL) {
3654     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3655     // FIXME: Needs another CMP because flag can have but one use.
3656     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3657     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3658   }
3659   return Result;
3660 }
3661
3662 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3663 /// to morph to an integer compare sequence.
3664 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3665                            const ARMSubtarget *Subtarget) {
3666   SDNode *N = Op.getNode();
3667   if (!N->hasOneUse())
3668     // Otherwise it requires moving the value from fp to integer registers.
3669     return false;
3670   if (!N->getNumValues())
3671     return false;
3672   EVT VT = Op.getValueType();
3673   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3674     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3675     // vmrs are very slow, e.g. cortex-a8.
3676     return false;
3677
3678   if (isFloatingPointZero(Op)) {
3679     SeenZero = true;
3680     return true;
3681   }
3682   return ISD::isNormalLoad(N);
3683 }
3684
3685 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3686   if (isFloatingPointZero(Op))
3687     return DAG.getConstant(0, MVT::i32);
3688
3689   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3690     return DAG.getLoad(MVT::i32, SDLoc(Op),
3691                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3692                        Ld->isVolatile(), Ld->isNonTemporal(),
3693                        Ld->isInvariant(), Ld->getAlignment());
3694
3695   llvm_unreachable("Unknown VFP cmp argument!");
3696 }
3697
3698 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3699                            SDValue &RetVal1, SDValue &RetVal2) {
3700   if (isFloatingPointZero(Op)) {
3701     RetVal1 = DAG.getConstant(0, MVT::i32);
3702     RetVal2 = DAG.getConstant(0, MVT::i32);
3703     return;
3704   }
3705
3706   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3707     SDValue Ptr = Ld->getBasePtr();
3708     RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3709                           Ld->getChain(), Ptr,
3710                           Ld->getPointerInfo(),
3711                           Ld->isVolatile(), Ld->isNonTemporal(),
3712                           Ld->isInvariant(), Ld->getAlignment());
3713
3714     EVT PtrType = Ptr.getValueType();
3715     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3716     SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3717                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
3718     RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3719                           Ld->getChain(), NewPtr,
3720                           Ld->getPointerInfo().getWithOffset(4),
3721                           Ld->isVolatile(), Ld->isNonTemporal(),
3722                           Ld->isInvariant(), NewAlign);
3723     return;
3724   }
3725
3726   llvm_unreachable("Unknown VFP cmp argument!");
3727 }
3728
3729 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3730 /// f32 and even f64 comparisons to integer ones.
3731 SDValue
3732 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3733   SDValue Chain = Op.getOperand(0);
3734   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3735   SDValue LHS = Op.getOperand(2);
3736   SDValue RHS = Op.getOperand(3);
3737   SDValue Dest = Op.getOperand(4);
3738   SDLoc dl(Op);
3739
3740   bool LHSSeenZero = false;
3741   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3742   bool RHSSeenZero = false;
3743   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3744   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3745     // If unsafe fp math optimization is enabled and there are no other uses of
3746     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3747     // to an integer comparison.
3748     if (CC == ISD::SETOEQ)
3749       CC = ISD::SETEQ;
3750     else if (CC == ISD::SETUNE)
3751       CC = ISD::SETNE;
3752
3753     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3754     SDValue ARMcc;
3755     if (LHS.getValueType() == MVT::f32) {
3756       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3757                         bitcastf32Toi32(LHS, DAG), Mask);
3758       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3759                         bitcastf32Toi32(RHS, DAG), Mask);
3760       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3761       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3762       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3763                          Chain, Dest, ARMcc, CCR, Cmp);
3764     }
3765
3766     SDValue LHS1, LHS2;
3767     SDValue RHS1, RHS2;
3768     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3769     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3770     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3771     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3772     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3773     ARMcc = DAG.getConstant(CondCode, MVT::i32);
3774     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3775     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3776     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3777   }
3778
3779   return SDValue();
3780 }
3781
3782 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3783   SDValue Chain = Op.getOperand(0);
3784   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3785   SDValue LHS = Op.getOperand(2);
3786   SDValue RHS = Op.getOperand(3);
3787   SDValue Dest = Op.getOperand(4);
3788   SDLoc dl(Op);
3789
3790   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3791     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3792                                                     dl);
3793
3794     // If softenSetCCOperands only returned one value, we should compare it to
3795     // zero.
3796     if (!RHS.getNode()) {
3797       RHS = DAG.getConstant(0, LHS.getValueType());
3798       CC = ISD::SETNE;
3799     }
3800   }
3801
3802   if (LHS.getValueType() == MVT::i32) {
3803     SDValue ARMcc;
3804     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3805     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3806     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3807                        Chain, Dest, ARMcc, CCR, Cmp);
3808   }
3809
3810   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3811
3812   if (getTargetMachine().Options.UnsafeFPMath &&
3813       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3814        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3815     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3816     if (Result.getNode())
3817       return Result;
3818   }
3819
3820   ARMCC::CondCodes CondCode, CondCode2;
3821   FPCCToARMCC(CC, CondCode, CondCode2);
3822
3823   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3824   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3825   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3826   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3827   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3828   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3829   if (CondCode2 != ARMCC::AL) {
3830     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3831     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3832     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3833   }
3834   return Res;
3835 }
3836
3837 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3838   SDValue Chain = Op.getOperand(0);
3839   SDValue Table = Op.getOperand(1);
3840   SDValue Index = Op.getOperand(2);
3841   SDLoc dl(Op);
3842
3843   EVT PTy = getPointerTy();
3844   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3845   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3846   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3847   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3848   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3849   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3850   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3851   if (Subtarget->isThumb2()) {
3852     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3853     // which does another jump to the destination. This also makes it easier
3854     // to translate it to TBB / TBH later.
3855     // FIXME: This might not work if the function is extremely large.
3856     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3857                        Addr, Op.getOperand(2), JTI, UId);
3858   }
3859   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3860     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3861                        MachinePointerInfo::getJumpTable(),
3862                        false, false, false, 0);
3863     Chain = Addr.getValue(1);
3864     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3865     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3866   } else {
3867     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3868                        MachinePointerInfo::getJumpTable(),
3869                        false, false, false, 0);
3870     Chain = Addr.getValue(1);
3871     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3872   }
3873 }
3874
3875 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3876   EVT VT = Op.getValueType();
3877   SDLoc dl(Op);
3878
3879   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3880     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3881       return Op;
3882     return DAG.UnrollVectorOp(Op.getNode());
3883   }
3884
3885   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3886          "Invalid type for custom lowering!");
3887   if (VT != MVT::v4i16)
3888     return DAG.UnrollVectorOp(Op.getNode());
3889
3890   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3891   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3892 }
3893
3894 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3895   EVT VT = Op.getValueType();
3896   if (VT.isVector())
3897     return LowerVectorFP_TO_INT(Op, DAG);
3898
3899   if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3900     RTLIB::Libcall LC;
3901     if (Op.getOpcode() == ISD::FP_TO_SINT)
3902       LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
3903                               Op.getValueType());
3904     else
3905       LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
3906                               Op.getValueType());
3907     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3908                        /*isSigned*/ false, SDLoc(Op)).first;
3909   }
3910
3911   SDLoc dl(Op);
3912   unsigned Opc;
3913
3914   switch (Op.getOpcode()) {
3915   default: llvm_unreachable("Invalid opcode!");
3916   case ISD::FP_TO_SINT:
3917     Opc = ARMISD::FTOSI;
3918     break;
3919   case ISD::FP_TO_UINT:
3920     Opc = ARMISD::FTOUI;
3921     break;
3922   }
3923   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3924   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3925 }
3926
3927 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3928   EVT VT = Op.getValueType();
3929   SDLoc dl(Op);
3930
3931   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3932     if (VT.getVectorElementType() == MVT::f32)
3933       return Op;
3934     return DAG.UnrollVectorOp(Op.getNode());
3935   }
3936
3937   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3938          "Invalid type for custom lowering!");
3939   if (VT != MVT::v4f32)
3940     return DAG.UnrollVectorOp(Op.getNode());
3941
3942   unsigned CastOpc;
3943   unsigned Opc;
3944   switch (Op.getOpcode()) {
3945   default: llvm_unreachable("Invalid opcode!");
3946   case ISD::SINT_TO_FP:
3947     CastOpc = ISD::SIGN_EXTEND;
3948     Opc = ISD::SINT_TO_FP;
3949     break;
3950   case ISD::UINT_TO_FP:
3951     CastOpc = ISD::ZERO_EXTEND;
3952     Opc = ISD::UINT_TO_FP;
3953     break;
3954   }
3955
3956   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3957   return DAG.getNode(Opc, dl, VT, Op);
3958 }
3959
3960 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
3961   EVT VT = Op.getValueType();
3962   if (VT.isVector())
3963     return LowerVectorINT_TO_FP(Op, DAG);
3964
3965   if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
3966     RTLIB::Libcall LC;
3967     if (Op.getOpcode() == ISD::SINT_TO_FP)
3968       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
3969                               Op.getValueType());
3970     else
3971       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
3972                               Op.getValueType());
3973     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3974                        /*isSigned*/ false, SDLoc(Op)).first;
3975   }
3976
3977   SDLoc dl(Op);
3978   unsigned Opc;
3979
3980   switch (Op.getOpcode()) {
3981   default: llvm_unreachable("Invalid opcode!");
3982   case ISD::SINT_TO_FP:
3983     Opc = ARMISD::SITOF;
3984     break;
3985   case ISD::UINT_TO_FP:
3986     Opc = ARMISD::UITOF;
3987     break;
3988   }
3989
3990   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3991   return DAG.getNode(Opc, dl, VT, Op);
3992 }
3993
3994 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3995   // Implement fcopysign with a fabs and a conditional fneg.
3996   SDValue Tmp0 = Op.getOperand(0);
3997   SDValue Tmp1 = Op.getOperand(1);
3998   SDLoc dl(Op);
3999   EVT VT = Op.getValueType();
4000   EVT SrcVT = Tmp1.getValueType();
4001   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
4002     Tmp0.getOpcode() == ARMISD::VMOVDRR;
4003   bool UseNEON = !InGPR && Subtarget->hasNEON();
4004
4005   if (UseNEON) {
4006     // Use VBSL to copy the sign bit.
4007     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
4008     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
4009                                DAG.getTargetConstant(EncodedVal, MVT::i32));
4010     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
4011     if (VT == MVT::f64)
4012       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4013                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
4014                          DAG.getConstant(32, MVT::i32));
4015     else /*if (VT == MVT::f32)*/
4016       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
4017     if (SrcVT == MVT::f32) {
4018       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4019       if (VT == MVT::f64)
4020         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4021                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4022                            DAG.getConstant(32, MVT::i32));
4023     } else if (VT == MVT::f32)
4024       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4025                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4026                          DAG.getConstant(32, MVT::i32));
4027     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4028     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4029
4030     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4031                                             MVT::i32);
4032     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4033     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4034                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4035
4036     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4037                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4038                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4039     if (VT == MVT::f32) {
4040       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4041       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4042                         DAG.getConstant(0, MVT::i32));
4043     } else {
4044       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4045     }
4046
4047     return Res;
4048   }
4049
4050   // Bitcast operand 1 to i32.
4051   if (SrcVT == MVT::f64)
4052     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4053                        Tmp1).getValue(1);
4054   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4055
4056   // Or in the signbit with integer operations.
4057   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
4058   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
4059   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4060   if (VT == MVT::f32) {
4061     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4062                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4063     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4064                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4065   }
4066
4067   // f64: Or the high part with signbit and then combine two parts.
4068   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4069                      Tmp0);
4070   SDValue Lo = Tmp0.getValue(0);
4071   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4072   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4073   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4074 }
4075
4076 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4077   MachineFunction &MF = DAG.getMachineFunction();
4078   MachineFrameInfo *MFI = MF.getFrameInfo();
4079   MFI->setReturnAddressIsTaken(true);
4080
4081   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4082     return SDValue();
4083
4084   EVT VT = Op.getValueType();
4085   SDLoc dl(Op);
4086   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4087   if (Depth) {
4088     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4089     SDValue Offset = DAG.getConstant(4, MVT::i32);
4090     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4091                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4092                        MachinePointerInfo(), false, false, false, 0);
4093   }
4094
4095   // Return LR, which contains the return address. Mark it an implicit live-in.
4096   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4097   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4098 }
4099
4100 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4101   const ARMBaseRegisterInfo &ARI =
4102     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4103   MachineFunction &MF = DAG.getMachineFunction();
4104   MachineFrameInfo *MFI = MF.getFrameInfo();
4105   MFI->setFrameAddressIsTaken(true);
4106
4107   EVT VT = Op.getValueType();
4108   SDLoc dl(Op);  // FIXME probably not meaningful
4109   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4110   unsigned FrameReg = ARI.getFrameRegister(MF);
4111   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4112   while (Depth--)
4113     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4114                             MachinePointerInfo(),
4115                             false, false, false, 0);
4116   return FrameAddr;
4117 }
4118
4119 // FIXME? Maybe this could be a TableGen attribute on some registers and
4120 // this table could be generated automatically from RegInfo.
4121 unsigned ARMTargetLowering::getRegisterByName(const char* RegName,
4122                                               EVT VT) const {
4123   unsigned Reg = StringSwitch<unsigned>(RegName)
4124                        .Case("sp", ARM::SP)
4125                        .Default(0);
4126   if (Reg)
4127     return Reg;
4128   report_fatal_error("Invalid register name global variable");
4129 }
4130
4131 /// ExpandBITCAST - If the target supports VFP, this function is called to
4132 /// expand a bit convert where either the source or destination type is i64 to
4133 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
4134 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4135 /// vectors), since the legalizer won't know what to do with that.
4136 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4137   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4138   SDLoc dl(N);
4139   SDValue Op = N->getOperand(0);
4140
4141   // This function is only supposed to be called for i64 types, either as the
4142   // source or destination of the bit convert.
4143   EVT SrcVT = Op.getValueType();
4144   EVT DstVT = N->getValueType(0);
4145   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4146          "ExpandBITCAST called for non-i64 type");
4147
4148   // Turn i64->f64 into VMOVDRR.
4149   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4150     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4151                              DAG.getConstant(0, MVT::i32));
4152     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4153                              DAG.getConstant(1, MVT::i32));
4154     return DAG.getNode(ISD::BITCAST, dl, DstVT,
4155                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4156   }
4157
4158   // Turn f64->i64 into VMOVRRD.
4159   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4160     SDValue Cvt;
4161     if (TLI.isBigEndian() && SrcVT.isVector() &&
4162         SrcVT.getVectorNumElements() > 1)
4163       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4164                         DAG.getVTList(MVT::i32, MVT::i32),
4165                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4166     else
4167       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4168                         DAG.getVTList(MVT::i32, MVT::i32), Op);
4169     // Merge the pieces into a single i64 value.
4170     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4171   }
4172
4173   return SDValue();
4174 }
4175
4176 /// getZeroVector - Returns a vector of specified type with all zero elements.
4177 /// Zero vectors are used to represent vector negation and in those cases
4178 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
4179 /// not support i64 elements, so sometimes the zero vectors will need to be
4180 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
4181 /// zero vector.
4182 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4183   assert(VT.isVector() && "Expected a vector type");
4184   // The canonical modified immediate encoding of a zero vector is....0!
4185   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
4186   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4187   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4188   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4189 }
4190
4191 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4192 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4193 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4194                                                 SelectionDAG &DAG) const {
4195   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4196   EVT VT = Op.getValueType();
4197   unsigned VTBits = VT.getSizeInBits();
4198   SDLoc dl(Op);
4199   SDValue ShOpLo = Op.getOperand(0);
4200   SDValue ShOpHi = Op.getOperand(1);
4201   SDValue ShAmt  = Op.getOperand(2);
4202   SDValue ARMcc;
4203   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4204
4205   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4206
4207   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4208                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
4209   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4210   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4211                                    DAG.getConstant(VTBits, MVT::i32));
4212   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4213   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4214   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4215
4216   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4217   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4218                           ARMcc, DAG, dl);
4219   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4220   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4221                            CCR, Cmp);
4222
4223   SDValue Ops[2] = { Lo, Hi };
4224   return DAG.getMergeValues(Ops, dl);
4225 }
4226
4227 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4228 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4229 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4230                                                SelectionDAG &DAG) const {
4231   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4232   EVT VT = Op.getValueType();
4233   unsigned VTBits = VT.getSizeInBits();
4234   SDLoc dl(Op);
4235   SDValue ShOpLo = Op.getOperand(0);
4236   SDValue ShOpHi = Op.getOperand(1);
4237   SDValue ShAmt  = Op.getOperand(2);
4238   SDValue ARMcc;
4239
4240   assert(Op.getOpcode() == ISD::SHL_PARTS);
4241   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4242                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
4243   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4244   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4245                                    DAG.getConstant(VTBits, MVT::i32));
4246   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4247   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4248
4249   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4250   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4251   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4252                           ARMcc, DAG, dl);
4253   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4254   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4255                            CCR, Cmp);
4256
4257   SDValue Ops[2] = { Lo, Hi };
4258   return DAG.getMergeValues(Ops, dl);
4259 }
4260
4261 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4262                                             SelectionDAG &DAG) const {
4263   // The rounding mode is in bits 23:22 of the FPSCR.
4264   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4265   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4266   // so that the shift + and get folded into a bitfield extract.
4267   SDLoc dl(Op);
4268   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4269                               DAG.getConstant(Intrinsic::arm_get_fpscr,
4270                                               MVT::i32));
4271   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4272                                   DAG.getConstant(1U << 22, MVT::i32));
4273   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4274                               DAG.getConstant(22, MVT::i32));
4275   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4276                      DAG.getConstant(3, MVT::i32));
4277 }
4278
4279 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4280                          const ARMSubtarget *ST) {
4281   EVT VT = N->getValueType(0);
4282   SDLoc dl(N);
4283
4284   if (!ST->hasV6T2Ops())
4285     return SDValue();
4286
4287   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4288   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4289 }
4290
4291 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4292 /// for each 16-bit element from operand, repeated.  The basic idea is to
4293 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4294 ///
4295 /// Trace for v4i16:
4296 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
4297 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4298 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4299 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4300 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
4301 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
4302 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4303 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
4304 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4305   EVT VT = N->getValueType(0);
4306   SDLoc DL(N);
4307
4308   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4309   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4310   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4311   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4312   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4313   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4314 }
4315
4316 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4317 /// bit-count for each 16-bit element from the operand.  We need slightly
4318 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4319 /// 64/128-bit registers.
4320 ///
4321 /// Trace for v4i16:
4322 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
4323 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4324 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
4325 /// v4i16:Extracted = [k0    k1    k2    k3    ]
4326 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4327   EVT VT = N->getValueType(0);
4328   SDLoc DL(N);
4329
4330   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4331   if (VT.is64BitVector()) {
4332     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4333     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4334                        DAG.getIntPtrConstant(0));
4335   } else {
4336     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4337                                     BitCounts, DAG.getIntPtrConstant(0));
4338     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4339   }
4340 }
4341
4342 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4343 /// bit-count for each 32-bit element from the operand.  The idea here is
4344 /// to split the vector into 16-bit elements, leverage the 16-bit count
4345 /// routine, and then combine the results.
4346 ///
4347 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4348 /// input    = [v0    v1    ] (vi: 32-bit elements)
4349 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4350 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4351 /// vrev: N0 = [k1 k0 k3 k2 ]
4352 ///            [k0 k1 k2 k3 ]
4353 ///       N1 =+[k1 k0 k3 k2 ]
4354 ///            [k0 k2 k1 k3 ]
4355 ///       N2 =+[k1 k3 k0 k2 ]
4356 ///            [k0    k2    k1    k3    ]
4357 /// Extended =+[k1    k3    k0    k2    ]
4358 ///            [k0    k2    ]
4359 /// Extracted=+[k1    k3    ]
4360 ///
4361 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4362   EVT VT = N->getValueType(0);
4363   SDLoc DL(N);
4364
4365   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4366
4367   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4368   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4369   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4370   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4371   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4372
4373   if (VT.is64BitVector()) {
4374     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4375     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4376                        DAG.getIntPtrConstant(0));
4377   } else {
4378     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4379                                     DAG.getIntPtrConstant(0));
4380     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4381   }
4382 }
4383
4384 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4385                           const ARMSubtarget *ST) {
4386   EVT VT = N->getValueType(0);
4387
4388   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4389   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4390           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4391          "Unexpected type for custom ctpop lowering");
4392
4393   if (VT.getVectorElementType() == MVT::i32)
4394     return lowerCTPOP32BitElements(N, DAG);
4395   else
4396     return lowerCTPOP16BitElements(N, DAG);
4397 }
4398
4399 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4400                           const ARMSubtarget *ST) {
4401   EVT VT = N->getValueType(0);
4402   SDLoc dl(N);
4403
4404   if (!VT.isVector())
4405     return SDValue();
4406
4407   // Lower vector shifts on NEON to use VSHL.
4408   assert(ST->hasNEON() && "unexpected vector shift");
4409
4410   // Left shifts translate directly to the vshiftu intrinsic.
4411   if (N->getOpcode() == ISD::SHL)
4412     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4413                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4414                        N->getOperand(0), N->getOperand(1));
4415
4416   assert((N->getOpcode() == ISD::SRA ||
4417           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4418
4419   // NEON uses the same intrinsics for both left and right shifts.  For
4420   // right shifts, the shift amounts are negative, so negate the vector of
4421   // shift amounts.
4422   EVT ShiftVT = N->getOperand(1).getValueType();
4423   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4424                                      getZeroVector(ShiftVT, DAG, dl),
4425                                      N->getOperand(1));
4426   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4427                              Intrinsic::arm_neon_vshifts :
4428                              Intrinsic::arm_neon_vshiftu);
4429   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4430                      DAG.getConstant(vshiftInt, MVT::i32),
4431                      N->getOperand(0), NegatedCount);
4432 }
4433
4434 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4435                                 const ARMSubtarget *ST) {
4436   EVT VT = N->getValueType(0);
4437   SDLoc dl(N);
4438
4439   // We can get here for a node like i32 = ISD::SHL i32, i64
4440   if (VT != MVT::i64)
4441     return SDValue();
4442
4443   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4444          "Unknown shift to lower!");
4445
4446   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4447   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4448       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4449     return SDValue();
4450
4451   // If we are in thumb mode, we don't have RRX.
4452   if (ST->isThumb1Only()) return SDValue();
4453
4454   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4455   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4456                            DAG.getConstant(0, MVT::i32));
4457   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4458                            DAG.getConstant(1, MVT::i32));
4459
4460   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4461   // captures the result into a carry flag.
4462   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4463   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4464
4465   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4466   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4467
4468   // Merge the pieces into a single i64 value.
4469  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4470 }
4471
4472 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4473   SDValue TmpOp0, TmpOp1;
4474   bool Invert = false;
4475   bool Swap = false;
4476   unsigned Opc = 0;
4477
4478   SDValue Op0 = Op.getOperand(0);
4479   SDValue Op1 = Op.getOperand(1);
4480   SDValue CC = Op.getOperand(2);
4481   EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
4482   EVT VT = Op.getValueType();
4483   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4484   SDLoc dl(Op);
4485
4486   if (Op1.getValueType().isFloatingPoint()) {
4487     switch (SetCCOpcode) {
4488     default: llvm_unreachable("Illegal FP comparison");
4489     case ISD::SETUNE:
4490     case ISD::SETNE:  Invert = true; // Fallthrough
4491     case ISD::SETOEQ:
4492     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4493     case ISD::SETOLT:
4494     case ISD::SETLT: Swap = true; // Fallthrough
4495     case ISD::SETOGT:
4496     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4497     case ISD::SETOLE:
4498     case ISD::SETLE:  Swap = true; // Fallthrough
4499     case ISD::SETOGE:
4500     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4501     case ISD::SETUGE: Swap = true; // Fallthrough
4502     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4503     case ISD::SETUGT: Swap = true; // Fallthrough
4504     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4505     case ISD::SETUEQ: Invert = true; // Fallthrough
4506     case ISD::SETONE:
4507       // Expand this to (OLT | OGT).
4508       TmpOp0 = Op0;
4509       TmpOp1 = Op1;
4510       Opc = ISD::OR;
4511       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4512       Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
4513       break;
4514     case ISD::SETUO: Invert = true; // Fallthrough
4515     case ISD::SETO:
4516       // Expand this to (OLT | OGE).
4517       TmpOp0 = Op0;
4518       TmpOp1 = Op1;
4519       Opc = ISD::OR;
4520       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4521       Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
4522       break;
4523     }
4524   } else {
4525     // Integer comparisons.
4526     switch (SetCCOpcode) {
4527     default: llvm_unreachable("Illegal integer comparison");
4528     case ISD::SETNE:  Invert = true;
4529     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4530     case ISD::SETLT:  Swap = true;
4531     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4532     case ISD::SETLE:  Swap = true;
4533     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4534     case ISD::SETULT: Swap = true;
4535     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4536     case ISD::SETULE: Swap = true;
4537     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4538     }
4539
4540     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4541     if (Opc == ARMISD::VCEQ) {
4542
4543       SDValue AndOp;
4544       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4545         AndOp = Op0;
4546       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4547         AndOp = Op1;
4548
4549       // Ignore bitconvert.
4550       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4551         AndOp = AndOp.getOperand(0);
4552
4553       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4554         Opc = ARMISD::VTST;
4555         Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
4556         Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
4557         Invert = !Invert;
4558       }
4559     }
4560   }
4561
4562   if (Swap)
4563     std::swap(Op0, Op1);
4564
4565   // If one of the operands is a constant vector zero, attempt to fold the
4566   // comparison to a specialized compare-against-zero form.
4567   SDValue SingleOp;
4568   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4569     SingleOp = Op0;
4570   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4571     if (Opc == ARMISD::VCGE)
4572       Opc = ARMISD::VCLEZ;
4573     else if (Opc == ARMISD::VCGT)
4574       Opc = ARMISD::VCLTZ;
4575     SingleOp = Op1;
4576   }
4577
4578   SDValue Result;
4579   if (SingleOp.getNode()) {
4580     switch (Opc) {
4581     case ARMISD::VCEQ:
4582       Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
4583     case ARMISD::VCGE:
4584       Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
4585     case ARMISD::VCLEZ:
4586       Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
4587     case ARMISD::VCGT:
4588       Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
4589     case ARMISD::VCLTZ:
4590       Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
4591     default:
4592       Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4593     }
4594   } else {
4595      Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4596   }
4597
4598   Result = DAG.getSExtOrTrunc(Result, dl, VT);
4599
4600   if (Invert)
4601     Result = DAG.getNOT(dl, Result, VT);
4602
4603   return Result;
4604 }
4605
4606 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4607 /// valid vector constant for a NEON instruction with a "modified immediate"
4608 /// operand (e.g., VMOV).  If so, return the encoded value.
4609 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4610                                  unsigned SplatBitSize, SelectionDAG &DAG,
4611                                  EVT &VT, bool is128Bits, NEONModImmType type) {
4612   unsigned OpCmode, Imm;
4613
4614   // SplatBitSize is set to the smallest size that splats the vector, so a
4615   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4616   // immediate instructions others than VMOV do not support the 8-bit encoding
4617   // of a zero vector, and the default encoding of zero is supposed to be the
4618   // 32-bit version.
4619   if (SplatBits == 0)
4620     SplatBitSize = 32;
4621
4622   switch (SplatBitSize) {
4623   case 8:
4624     if (type != VMOVModImm)
4625       return SDValue();
4626     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4627     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4628     OpCmode = 0xe;
4629     Imm = SplatBits;
4630     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4631     break;
4632
4633   case 16:
4634     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4635     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4636     if ((SplatBits & ~0xff) == 0) {
4637       // Value = 0x00nn: Op=x, Cmode=100x.
4638       OpCmode = 0x8;
4639       Imm = SplatBits;
4640       break;
4641     }
4642     if ((SplatBits & ~0xff00) == 0) {
4643       // Value = 0xnn00: Op=x, Cmode=101x.
4644       OpCmode = 0xa;
4645       Imm = SplatBits >> 8;
4646       break;
4647     }
4648     return SDValue();
4649
4650   case 32:
4651     // NEON's 32-bit VMOV supports splat values where:
4652     // * only one byte is nonzero, or
4653     // * the least significant byte is 0xff and the second byte is nonzero, or
4654     // * the least significant 2 bytes are 0xff and the third is nonzero.
4655     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4656     if ((SplatBits & ~0xff) == 0) {
4657       // Value = 0x000000nn: Op=x, Cmode=000x.
4658       OpCmode = 0;
4659       Imm = SplatBits;
4660       break;
4661     }
4662     if ((SplatBits & ~0xff00) == 0) {
4663       // Value = 0x0000nn00: Op=x, Cmode=001x.
4664       OpCmode = 0x2;
4665       Imm = SplatBits >> 8;
4666       break;
4667     }
4668     if ((SplatBits & ~0xff0000) == 0) {
4669       // Value = 0x00nn0000: Op=x, Cmode=010x.
4670       OpCmode = 0x4;
4671       Imm = SplatBits >> 16;
4672       break;
4673     }
4674     if ((SplatBits & ~0xff000000) == 0) {
4675       // Value = 0xnn000000: Op=x, Cmode=011x.
4676       OpCmode = 0x6;
4677       Imm = SplatBits >> 24;
4678       break;
4679     }
4680
4681     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4682     if (type == OtherModImm) return SDValue();
4683
4684     if ((SplatBits & ~0xffff) == 0 &&
4685         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4686       // Value = 0x0000nnff: Op=x, Cmode=1100.
4687       OpCmode = 0xc;
4688       Imm = SplatBits >> 8;
4689       break;
4690     }
4691
4692     if ((SplatBits & ~0xffffff) == 0 &&
4693         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4694       // Value = 0x00nnffff: Op=x, Cmode=1101.
4695       OpCmode = 0xd;
4696       Imm = SplatBits >> 16;
4697       break;
4698     }
4699
4700     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4701     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4702     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4703     // and fall through here to test for a valid 64-bit splat.  But, then the
4704     // caller would also need to check and handle the change in size.
4705     return SDValue();
4706
4707   case 64: {
4708     if (type != VMOVModImm)
4709       return SDValue();
4710     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4711     uint64_t BitMask = 0xff;
4712     uint64_t Val = 0;
4713     unsigned ImmMask = 1;
4714     Imm = 0;
4715     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4716       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4717         Val |= BitMask;
4718         Imm |= ImmMask;
4719       } else if ((SplatBits & BitMask) != 0) {
4720         return SDValue();
4721       }
4722       BitMask <<= 8;
4723       ImmMask <<= 1;
4724     }
4725
4726     if (DAG.getTargetLoweringInfo().isBigEndian())
4727       // swap higher and lower 32 bit word
4728       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4729
4730     // Op=1, Cmode=1110.
4731     OpCmode = 0x1e;
4732     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4733     break;
4734   }
4735
4736   default:
4737     llvm_unreachable("unexpected size for isNEONModifiedImm");
4738   }
4739
4740   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4741   return DAG.getTargetConstant(EncodedVal, MVT::i32);
4742 }
4743
4744 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4745                                            const ARMSubtarget *ST) const {
4746   if (!ST->hasVFP3())
4747     return SDValue();
4748
4749   bool IsDouble = Op.getValueType() == MVT::f64;
4750   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4751
4752   // Use the default (constant pool) lowering for double constants when we have
4753   // an SP-only FPU
4754   if (IsDouble && Subtarget->isFPOnlySP())
4755     return SDValue();
4756
4757   // Try splatting with a VMOV.f32...
4758   APFloat FPVal = CFP->getValueAPF();
4759   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4760
4761   if (ImmVal != -1) {
4762     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4763       // We have code in place to select a valid ConstantFP already, no need to
4764       // do any mangling.
4765       return Op;
4766     }
4767
4768     // It's a float and we are trying to use NEON operations where
4769     // possible. Lower it to a splat followed by an extract.
4770     SDLoc DL(Op);
4771     SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4772     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4773                                       NewVal);
4774     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4775                        DAG.getConstant(0, MVT::i32));
4776   }
4777
4778   // The rest of our options are NEON only, make sure that's allowed before
4779   // proceeding..
4780   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4781     return SDValue();
4782
4783   EVT VMovVT;
4784   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4785
4786   // It wouldn't really be worth bothering for doubles except for one very
4787   // important value, which does happen to match: 0.0. So make sure we don't do
4788   // anything stupid.
4789   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4790     return SDValue();
4791
4792   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4793   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4794                                      false, VMOVModImm);
4795   if (NewVal != SDValue()) {
4796     SDLoc DL(Op);
4797     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4798                                       NewVal);
4799     if (IsDouble)
4800       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4801
4802     // It's a float: cast and extract a vector element.
4803     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4804                                        VecConstant);
4805     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4806                        DAG.getConstant(0, MVT::i32));
4807   }
4808
4809   // Finally, try a VMVN.i32
4810   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4811                              false, VMVNModImm);
4812   if (NewVal != SDValue()) {
4813     SDLoc DL(Op);
4814     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4815
4816     if (IsDouble)
4817       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4818
4819     // It's a float: cast and extract a vector element.
4820     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4821                                        VecConstant);
4822     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4823                        DAG.getConstant(0, MVT::i32));
4824   }
4825
4826   return SDValue();
4827 }
4828
4829 // check if an VEXT instruction can handle the shuffle mask when the
4830 // vector sources of the shuffle are the same.
4831 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4832   unsigned NumElts = VT.getVectorNumElements();
4833
4834   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4835   if (M[0] < 0)
4836     return false;
4837
4838   Imm = M[0];
4839
4840   // If this is a VEXT shuffle, the immediate value is the index of the first
4841   // element.  The other shuffle indices must be the successive elements after
4842   // the first one.
4843   unsigned ExpectedElt = Imm;
4844   for (unsigned i = 1; i < NumElts; ++i) {
4845     // Increment the expected index.  If it wraps around, just follow it
4846     // back to index zero and keep going.
4847     ++ExpectedElt;
4848     if (ExpectedElt == NumElts)
4849       ExpectedElt = 0;
4850
4851     if (M[i] < 0) continue; // ignore UNDEF indices
4852     if (ExpectedElt != static_cast<unsigned>(M[i]))
4853       return false;
4854   }
4855
4856   return true;
4857 }
4858
4859
4860 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4861                        bool &ReverseVEXT, unsigned &Imm) {
4862   unsigned NumElts = VT.getVectorNumElements();
4863   ReverseVEXT = false;
4864
4865   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4866   if (M[0] < 0)
4867     return false;
4868
4869   Imm = M[0];
4870
4871   // If this is a VEXT shuffle, the immediate value is the index of the first
4872   // element.  The other shuffle indices must be the successive elements after
4873   // the first one.
4874   unsigned ExpectedElt = Imm;
4875   for (unsigned i = 1; i < NumElts; ++i) {
4876     // Increment the expected index.  If it wraps around, it may still be
4877     // a VEXT but the source vectors must be swapped.
4878     ExpectedElt += 1;
4879     if (ExpectedElt == NumElts * 2) {
4880       ExpectedElt = 0;
4881       ReverseVEXT = true;
4882     }
4883
4884     if (M[i] < 0) continue; // ignore UNDEF indices
4885     if (ExpectedElt != static_cast<unsigned>(M[i]))
4886       return false;
4887   }
4888
4889   // Adjust the index value if the source operands will be swapped.
4890   if (ReverseVEXT)
4891     Imm -= NumElts;
4892
4893   return true;
4894 }
4895
4896 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4897 /// instruction with the specified blocksize.  (The order of the elements
4898 /// within each block of the vector is reversed.)
4899 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4900   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4901          "Only possible block sizes for VREV are: 16, 32, 64");
4902
4903   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4904   if (EltSz == 64)
4905     return false;
4906
4907   unsigned NumElts = VT.getVectorNumElements();
4908   unsigned BlockElts = M[0] + 1;
4909   // If the first shuffle index is UNDEF, be optimistic.
4910   if (M[0] < 0)
4911     BlockElts = BlockSize / EltSz;
4912
4913   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4914     return false;
4915
4916   for (unsigned i = 0; i < NumElts; ++i) {
4917     if (M[i] < 0) continue; // ignore UNDEF indices
4918     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4919       return false;
4920   }
4921
4922   return true;
4923 }
4924
4925 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4926   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4927   // range, then 0 is placed into the resulting vector. So pretty much any mask
4928   // of 8 elements can work here.
4929   return VT == MVT::v8i8 && M.size() == 8;
4930 }
4931
4932 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4933   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4934   if (EltSz == 64)
4935     return false;
4936
4937   unsigned NumElts = VT.getVectorNumElements();
4938   WhichResult = (M[0] == 0 ? 0 : 1);
4939   for (unsigned i = 0; i < NumElts; i += 2) {
4940     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4941         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4942       return false;
4943   }
4944   return true;
4945 }
4946
4947 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4948 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4949 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4950 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4951   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4952   if (EltSz == 64)
4953     return false;
4954
4955   unsigned NumElts = VT.getVectorNumElements();
4956   WhichResult = (M[0] == 0 ? 0 : 1);
4957   for (unsigned i = 0; i < NumElts; i += 2) {
4958     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4959         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4960       return false;
4961   }
4962   return true;
4963 }
4964
4965 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4966   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4967   if (EltSz == 64)
4968     return false;
4969
4970   unsigned NumElts = VT.getVectorNumElements();
4971   WhichResult = (M[0] == 0 ? 0 : 1);
4972   for (unsigned i = 0; i != NumElts; ++i) {
4973     if (M[i] < 0) continue; // ignore UNDEF indices
4974     if ((unsigned) M[i] != 2 * i + WhichResult)
4975       return false;
4976   }
4977
4978   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4979   if (VT.is64BitVector() && EltSz == 32)
4980     return false;
4981
4982   return true;
4983 }
4984
4985 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4986 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4987 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4988 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4989   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4990   if (EltSz == 64)
4991     return false;
4992
4993   unsigned Half = VT.getVectorNumElements() / 2;
4994   WhichResult = (M[0] == 0 ? 0 : 1);
4995   for (unsigned j = 0; j != 2; ++j) {
4996     unsigned Idx = WhichResult;
4997     for (unsigned i = 0; i != Half; ++i) {
4998       int MIdx = M[i + j * Half];
4999       if (MIdx >= 0 && (unsigned) MIdx != Idx)
5000         return false;
5001       Idx += 2;
5002     }
5003   }
5004
5005   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5006   if (VT.is64BitVector() && EltSz == 32)
5007     return false;
5008
5009   return true;
5010 }
5011
5012 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5013   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5014   if (EltSz == 64)
5015     return false;
5016
5017   unsigned NumElts = VT.getVectorNumElements();
5018   WhichResult = (M[0] == 0 ? 0 : 1);
5019   unsigned Idx = WhichResult * NumElts / 2;
5020   for (unsigned i = 0; i != NumElts; i += 2) {
5021     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
5022         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
5023       return false;
5024     Idx += 1;
5025   }
5026
5027   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5028   if (VT.is64BitVector() && EltSz == 32)
5029     return false;
5030
5031   return true;
5032 }
5033
5034 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5035 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5036 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5037 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5038   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5039   if (EltSz == 64)
5040     return false;
5041
5042   unsigned NumElts = VT.getVectorNumElements();
5043   WhichResult = (M[0] == 0 ? 0 : 1);
5044   unsigned Idx = WhichResult * NumElts / 2;
5045   for (unsigned i = 0; i != NumElts; i += 2) {
5046     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
5047         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
5048       return false;
5049     Idx += 1;
5050   }
5051
5052   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5053   if (VT.is64BitVector() && EltSz == 32)
5054     return false;
5055
5056   return true;
5057 }
5058
5059 /// \return true if this is a reverse operation on an vector.
5060 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5061   unsigned NumElts = VT.getVectorNumElements();
5062   // Make sure the mask has the right size.
5063   if (NumElts != M.size())
5064       return false;
5065
5066   // Look for <15, ..., 3, -1, 1, 0>.
5067   for (unsigned i = 0; i != NumElts; ++i)
5068     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5069       return false;
5070
5071   return true;
5072 }
5073
5074 // If N is an integer constant that can be moved into a register in one
5075 // instruction, return an SDValue of such a constant (will become a MOV
5076 // instruction).  Otherwise return null.
5077 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5078                                      const ARMSubtarget *ST, SDLoc dl) {
5079   uint64_t Val;
5080   if (!isa<ConstantSDNode>(N))
5081     return SDValue();
5082   Val = cast<ConstantSDNode>(N)->getZExtValue();
5083
5084   if (ST->isThumb1Only()) {
5085     if (Val <= 255 || ~Val <= 255)
5086       return DAG.getConstant(Val, MVT::i32);
5087   } else {
5088     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5089       return DAG.getConstant(Val, MVT::i32);
5090   }
5091   return SDValue();
5092 }
5093
5094 // If this is a case we can't handle, return null and let the default
5095 // expansion code take care of it.
5096 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5097                                              const ARMSubtarget *ST) const {
5098   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5099   SDLoc dl(Op);
5100   EVT VT = Op.getValueType();
5101
5102   APInt SplatBits, SplatUndef;
5103   unsigned SplatBitSize;
5104   bool HasAnyUndefs;
5105   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5106     if (SplatBitSize <= 64) {
5107       // Check if an immediate VMOV works.
5108       EVT VmovVT;
5109       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5110                                       SplatUndef.getZExtValue(), SplatBitSize,
5111                                       DAG, VmovVT, VT.is128BitVector(),
5112                                       VMOVModImm);
5113       if (Val.getNode()) {
5114         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5115         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5116       }
5117
5118       // Try an immediate VMVN.
5119       uint64_t NegatedImm = (~SplatBits).getZExtValue();
5120       Val = isNEONModifiedImm(NegatedImm,
5121                                       SplatUndef.getZExtValue(), SplatBitSize,
5122                                       DAG, VmovVT, VT.is128BitVector(),
5123                                       VMVNModImm);
5124       if (Val.getNode()) {
5125         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5126         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5127       }
5128
5129       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5130       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5131         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5132         if (ImmVal != -1) {
5133           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
5134           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5135         }
5136       }
5137     }
5138   }
5139
5140   // Scan through the operands to see if only one value is used.
5141   //
5142   // As an optimisation, even if more than one value is used it may be more
5143   // profitable to splat with one value then change some lanes.
5144   //
5145   // Heuristically we decide to do this if the vector has a "dominant" value,
5146   // defined as splatted to more than half of the lanes.
5147   unsigned NumElts = VT.getVectorNumElements();
5148   bool isOnlyLowElement = true;
5149   bool usesOnlyOneValue = true;
5150   bool hasDominantValue = false;
5151   bool isConstant = true;
5152
5153   // Map of the number of times a particular SDValue appears in the
5154   // element list.
5155   DenseMap<SDValue, unsigned> ValueCounts;
5156   SDValue Value;
5157   for (unsigned i = 0; i < NumElts; ++i) {
5158     SDValue V = Op.getOperand(i);
5159     if (V.getOpcode() == ISD::UNDEF)
5160       continue;
5161     if (i > 0)
5162       isOnlyLowElement = false;
5163     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5164       isConstant = false;
5165
5166     ValueCounts.insert(std::make_pair(V, 0));
5167     unsigned &Count = ValueCounts[V];
5168
5169     // Is this value dominant? (takes up more than half of the lanes)
5170     if (++Count > (NumElts / 2)) {
5171       hasDominantValue = true;
5172       Value = V;
5173     }
5174   }
5175   if (ValueCounts.size() != 1)
5176     usesOnlyOneValue = false;
5177   if (!Value.getNode() && ValueCounts.size() > 0)
5178     Value = ValueCounts.begin()->first;
5179
5180   if (ValueCounts.size() == 0)
5181     return DAG.getUNDEF(VT);
5182
5183   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5184   // Keep going if we are hitting this case.
5185   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5186     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5187
5188   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5189
5190   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
5191   // i32 and try again.
5192   if (hasDominantValue && EltSize <= 32) {
5193     if (!isConstant) {
5194       SDValue N;
5195
5196       // If we are VDUPing a value that comes directly from a vector, that will
5197       // cause an unnecessary move to and from a GPR, where instead we could
5198       // just use VDUPLANE. We can only do this if the lane being extracted
5199       // is at a constant index, as the VDUP from lane instructions only have
5200       // constant-index forms.
5201       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5202           isa<ConstantSDNode>(Value->getOperand(1))) {
5203         // We need to create a new undef vector to use for the VDUPLANE if the
5204         // size of the vector from which we get the value is different than the
5205         // size of the vector that we need to create. We will insert the element
5206         // such that the register coalescer will remove unnecessary copies.
5207         if (VT != Value->getOperand(0).getValueType()) {
5208           ConstantSDNode *constIndex;
5209           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5210           assert(constIndex && "The index is not a constant!");
5211           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5212                              VT.getVectorNumElements();
5213           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5214                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5215                         Value, DAG.getConstant(index, MVT::i32)),
5216                            DAG.getConstant(index, MVT::i32));
5217         } else
5218           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5219                         Value->getOperand(0), Value->getOperand(1));
5220       } else
5221         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5222
5223       if (!usesOnlyOneValue) {
5224         // The dominant value was splatted as 'N', but we now have to insert
5225         // all differing elements.
5226         for (unsigned I = 0; I < NumElts; ++I) {
5227           if (Op.getOperand(I) == Value)
5228             continue;
5229           SmallVector<SDValue, 3> Ops;
5230           Ops.push_back(N);
5231           Ops.push_back(Op.getOperand(I));
5232           Ops.push_back(DAG.getConstant(I, MVT::i32));
5233           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5234         }
5235       }
5236       return N;
5237     }
5238     if (VT.getVectorElementType().isFloatingPoint()) {
5239       SmallVector<SDValue, 8> Ops;
5240       for (unsigned i = 0; i < NumElts; ++i)
5241         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5242                                   Op.getOperand(i)));
5243       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5244       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5245       Val = LowerBUILD_VECTOR(Val, DAG, ST);
5246       if (Val.getNode())
5247         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5248     }
5249     if (usesOnlyOneValue) {
5250       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5251       if (isConstant && Val.getNode())
5252         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5253     }
5254   }
5255
5256   // If all elements are constants and the case above didn't get hit, fall back
5257   // to the default expansion, which will generate a load from the constant
5258   // pool.
5259   if (isConstant)
5260     return SDValue();
5261
5262   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5263   if (NumElts >= 4) {
5264     SDValue shuffle = ReconstructShuffle(Op, DAG);
5265     if (shuffle != SDValue())
5266       return shuffle;
5267   }
5268
5269   // Vectors with 32- or 64-bit elements can be built by directly assigning
5270   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
5271   // will be legalized.
5272   if (EltSize >= 32) {
5273     // Do the expansion with floating-point types, since that is what the VFP
5274     // registers are defined to use, and since i64 is not legal.
5275     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5276     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5277     SmallVector<SDValue, 8> Ops;
5278     for (unsigned i = 0; i < NumElts; ++i)
5279       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5280     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5281     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5282   }
5283
5284   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5285   // know the default expansion would otherwise fall back on something even
5286   // worse. For a vector with one or two non-undef values, that's
5287   // scalar_to_vector for the elements followed by a shuffle (provided the
5288   // shuffle is valid for the target) and materialization element by element
5289   // on the stack followed by a load for everything else.
5290   if (!isConstant && !usesOnlyOneValue) {
5291     SDValue Vec = DAG.getUNDEF(VT);
5292     for (unsigned i = 0 ; i < NumElts; ++i) {
5293       SDValue V = Op.getOperand(i);
5294       if (V.getOpcode() == ISD::UNDEF)
5295         continue;
5296       SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
5297       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5298     }
5299     return Vec;
5300   }
5301
5302   return SDValue();
5303 }
5304
5305 // Gather data to see if the operation can be modelled as a
5306 // shuffle in combination with VEXTs.
5307 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5308                                               SelectionDAG &DAG) const {
5309   SDLoc dl(Op);
5310   EVT VT = Op.getValueType();
5311   unsigned NumElts = VT.getVectorNumElements();
5312
5313   SmallVector<SDValue, 2> SourceVecs;
5314   SmallVector<unsigned, 2> MinElts;
5315   SmallVector<unsigned, 2> MaxElts;
5316
5317   for (unsigned i = 0; i < NumElts; ++i) {
5318     SDValue V = Op.getOperand(i);
5319     if (V.getOpcode() == ISD::UNDEF)
5320       continue;
5321     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5322       // A shuffle can only come from building a vector from various
5323       // elements of other vectors.
5324       return SDValue();
5325     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5326                VT.getVectorElementType()) {
5327       // This code doesn't know how to handle shuffles where the vector
5328       // element types do not match (this happens because type legalization
5329       // promotes the return type of EXTRACT_VECTOR_ELT).
5330       // FIXME: It might be appropriate to extend this code to handle
5331       // mismatched types.
5332       return SDValue();
5333     }
5334
5335     // Record this extraction against the appropriate vector if possible...
5336     SDValue SourceVec = V.getOperand(0);
5337     // If the element number isn't a constant, we can't effectively
5338     // analyze what's going on.
5339     if (!isa<ConstantSDNode>(V.getOperand(1)))
5340       return SDValue();
5341     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5342     bool FoundSource = false;
5343     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5344       if (SourceVecs[j] == SourceVec) {
5345         if (MinElts[j] > EltNo)
5346           MinElts[j] = EltNo;
5347         if (MaxElts[j] < EltNo)
5348           MaxElts[j] = EltNo;
5349         FoundSource = true;
5350         break;
5351       }
5352     }
5353
5354     // Or record a new source if not...
5355     if (!FoundSource) {
5356       SourceVecs.push_back(SourceVec);
5357       MinElts.push_back(EltNo);
5358       MaxElts.push_back(EltNo);
5359     }
5360   }
5361
5362   // Currently only do something sane when at most two source vectors
5363   // involved.
5364   if (SourceVecs.size() > 2)
5365     return SDValue();
5366
5367   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5368   int VEXTOffsets[2] = {0, 0};
5369
5370   // This loop extracts the usage patterns of the source vectors
5371   // and prepares appropriate SDValues for a shuffle if possible.
5372   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5373     if (SourceVecs[i].getValueType() == VT) {
5374       // No VEXT necessary
5375       ShuffleSrcs[i] = SourceVecs[i];
5376       VEXTOffsets[i] = 0;
5377       continue;
5378     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5379       // It probably isn't worth padding out a smaller vector just to
5380       // break it down again in a shuffle.
5381       return SDValue();
5382     }
5383
5384     // Since only 64-bit and 128-bit vectors are legal on ARM and
5385     // we've eliminated the other cases...
5386     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5387            "unexpected vector sizes in ReconstructShuffle");
5388
5389     if (MaxElts[i] - MinElts[i] >= NumElts) {
5390       // Span too large for a VEXT to cope
5391       return SDValue();
5392     }
5393
5394     if (MinElts[i] >= NumElts) {
5395       // The extraction can just take the second half
5396       VEXTOffsets[i] = NumElts;
5397       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5398                                    SourceVecs[i],
5399                                    DAG.getIntPtrConstant(NumElts));
5400     } else if (MaxElts[i] < NumElts) {
5401       // The extraction can just take the first half
5402       VEXTOffsets[i] = 0;
5403       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5404                                    SourceVecs[i],
5405                                    DAG.getIntPtrConstant(0));
5406     } else {
5407       // An actual VEXT is needed
5408       VEXTOffsets[i] = MinElts[i];
5409       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5410                                      SourceVecs[i],
5411                                      DAG.getIntPtrConstant(0));
5412       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5413                                      SourceVecs[i],
5414                                      DAG.getIntPtrConstant(NumElts));
5415       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5416                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
5417     }
5418   }
5419
5420   SmallVector<int, 8> Mask;
5421
5422   for (unsigned i = 0; i < NumElts; ++i) {
5423     SDValue Entry = Op.getOperand(i);
5424     if (Entry.getOpcode() == ISD::UNDEF) {
5425       Mask.push_back(-1);
5426       continue;
5427     }
5428
5429     SDValue ExtractVec = Entry.getOperand(0);
5430     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5431                                           .getOperand(1))->getSExtValue();
5432     if (ExtractVec == SourceVecs[0]) {
5433       Mask.push_back(ExtractElt - VEXTOffsets[0]);
5434     } else {
5435       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5436     }
5437   }
5438
5439   // Final check before we try to produce nonsense...
5440   if (isShuffleMaskLegal(Mask, VT))
5441     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5442                                 &Mask[0]);
5443
5444   return SDValue();
5445 }
5446
5447 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5448 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5449 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5450 /// are assumed to be legal.
5451 bool
5452 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5453                                       EVT VT) const {
5454   if (VT.getVectorNumElements() == 4 &&
5455       (VT.is128BitVector() || VT.is64BitVector())) {
5456     unsigned PFIndexes[4];
5457     for (unsigned i = 0; i != 4; ++i) {
5458       if (M[i] < 0)
5459         PFIndexes[i] = 8;
5460       else
5461         PFIndexes[i] = M[i];
5462     }
5463
5464     // Compute the index in the perfect shuffle table.
5465     unsigned PFTableIndex =
5466       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5467     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5468     unsigned Cost = (PFEntry >> 30);
5469
5470     if (Cost <= 4)
5471       return true;
5472   }
5473
5474   bool ReverseVEXT;
5475   unsigned Imm, WhichResult;
5476
5477   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5478   return (EltSize >= 32 ||
5479           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5480           isVREVMask(M, VT, 64) ||
5481           isVREVMask(M, VT, 32) ||
5482           isVREVMask(M, VT, 16) ||
5483           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5484           isVTBLMask(M, VT) ||
5485           isVTRNMask(M, VT, WhichResult) ||
5486           isVUZPMask(M, VT, WhichResult) ||
5487           isVZIPMask(M, VT, WhichResult) ||
5488           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5489           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5490           isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5491           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5492 }
5493
5494 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5495 /// the specified operations to build the shuffle.
5496 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5497                                       SDValue RHS, SelectionDAG &DAG,
5498                                       SDLoc dl) {
5499   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5500   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5501   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5502
5503   enum {
5504     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5505     OP_VREV,
5506     OP_VDUP0,
5507     OP_VDUP1,
5508     OP_VDUP2,
5509     OP_VDUP3,
5510     OP_VEXT1,
5511     OP_VEXT2,
5512     OP_VEXT3,
5513     OP_VUZPL, // VUZP, left result
5514     OP_VUZPR, // VUZP, right result
5515     OP_VZIPL, // VZIP, left result
5516     OP_VZIPR, // VZIP, right result
5517     OP_VTRNL, // VTRN, left result
5518     OP_VTRNR  // VTRN, right result
5519   };
5520
5521   if (OpNum == OP_COPY) {
5522     if (LHSID == (1*9+2)*9+3) return LHS;
5523     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5524     return RHS;
5525   }
5526
5527   SDValue OpLHS, OpRHS;
5528   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5529   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5530   EVT VT = OpLHS.getValueType();
5531
5532   switch (OpNum) {
5533   default: llvm_unreachable("Unknown shuffle opcode!");
5534   case OP_VREV:
5535     // VREV divides the vector in half and swaps within the half.
5536     if (VT.getVectorElementType() == MVT::i32 ||
5537         VT.getVectorElementType() == MVT::f32)
5538       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5539     // vrev <4 x i16> -> VREV32
5540     if (VT.getVectorElementType() == MVT::i16)
5541       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5542     // vrev <4 x i8> -> VREV16
5543     assert(VT.getVectorElementType() == MVT::i8);
5544     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5545   case OP_VDUP0:
5546   case OP_VDUP1:
5547   case OP_VDUP2:
5548   case OP_VDUP3:
5549     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5550                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5551   case OP_VEXT1:
5552   case OP_VEXT2:
5553   case OP_VEXT3:
5554     return DAG.getNode(ARMISD::VEXT, dl, VT,
5555                        OpLHS, OpRHS,
5556                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5557   case OP_VUZPL:
5558   case OP_VUZPR:
5559     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5560                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5561   case OP_VZIPL:
5562   case OP_VZIPR:
5563     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5564                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5565   case OP_VTRNL:
5566   case OP_VTRNR:
5567     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5568                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5569   }
5570 }
5571
5572 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5573                                        ArrayRef<int> ShuffleMask,
5574                                        SelectionDAG &DAG) {
5575   // Check to see if we can use the VTBL instruction.
5576   SDValue V1 = Op.getOperand(0);
5577   SDValue V2 = Op.getOperand(1);
5578   SDLoc DL(Op);
5579
5580   SmallVector<SDValue, 8> VTBLMask;
5581   for (ArrayRef<int>::iterator
5582          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5583     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5584
5585   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5586     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5587                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5588
5589   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5590                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5591 }
5592
5593 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5594                                                       SelectionDAG &DAG) {
5595   SDLoc DL(Op);
5596   SDValue OpLHS = Op.getOperand(0);
5597   EVT VT = OpLHS.getValueType();
5598
5599   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5600          "Expect an v8i16/v16i8 type");
5601   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5602   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5603   // extract the first 8 bytes into the top double word and the last 8 bytes
5604   // into the bottom double word. The v8i16 case is similar.
5605   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5606   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5607                      DAG.getConstant(ExtractNum, MVT::i32));
5608 }
5609
5610 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5611   SDValue V1 = Op.getOperand(0);
5612   SDValue V2 = Op.getOperand(1);
5613   SDLoc dl(Op);
5614   EVT VT = Op.getValueType();
5615   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5616
5617   // Convert shuffles that are directly supported on NEON to target-specific
5618   // DAG nodes, instead of keeping them as shuffles and matching them again
5619   // during code selection.  This is more efficient and avoids the possibility
5620   // of inconsistencies between legalization and selection.
5621   // FIXME: floating-point vectors should be canonicalized to integer vectors
5622   // of the same time so that they get CSEd properly.
5623   ArrayRef<int> ShuffleMask = SVN->getMask();
5624
5625   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5626   if (EltSize <= 32) {
5627     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5628       int Lane = SVN->getSplatIndex();
5629       // If this is undef splat, generate it via "just" vdup, if possible.
5630       if (Lane == -1) Lane = 0;
5631
5632       // Test if V1 is a SCALAR_TO_VECTOR.
5633       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5634         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5635       }
5636       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5637       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5638       // reaches it).
5639       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5640           !isa<ConstantSDNode>(V1.getOperand(0))) {
5641         bool IsScalarToVector = true;
5642         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5643           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5644             IsScalarToVector = false;
5645             break;
5646           }
5647         if (IsScalarToVector)
5648           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5649       }
5650       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5651                          DAG.getConstant(Lane, MVT::i32));
5652     }
5653
5654     bool ReverseVEXT;
5655     unsigned Imm;
5656     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5657       if (ReverseVEXT)
5658         std::swap(V1, V2);
5659       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5660                          DAG.getConstant(Imm, MVT::i32));
5661     }
5662
5663     if (isVREVMask(ShuffleMask, VT, 64))
5664       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5665     if (isVREVMask(ShuffleMask, VT, 32))
5666       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5667     if (isVREVMask(ShuffleMask, VT, 16))
5668       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5669
5670     if (V2->getOpcode() == ISD::UNDEF &&
5671         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5672       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5673                          DAG.getConstant(Imm, MVT::i32));
5674     }
5675
5676     // Check for Neon shuffles that modify both input vectors in place.
5677     // If both results are used, i.e., if there are two shuffles with the same
5678     // source operands and with masks corresponding to both results of one of
5679     // these operations, DAG memoization will ensure that a single node is
5680     // used for both shuffles.
5681     unsigned WhichResult;
5682     if (isVTRNMask(ShuffleMask, VT, WhichResult))
5683       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5684                          V1, V2).getValue(WhichResult);
5685     if (isVUZPMask(ShuffleMask, VT, WhichResult))
5686       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5687                          V1, V2).getValue(WhichResult);
5688     if (isVZIPMask(ShuffleMask, VT, WhichResult))
5689       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5690                          V1, V2).getValue(WhichResult);
5691
5692     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5693       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5694                          V1, V1).getValue(WhichResult);
5695     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5696       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5697                          V1, V1).getValue(WhichResult);
5698     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5699       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5700                          V1, V1).getValue(WhichResult);
5701   }
5702
5703   // If the shuffle is not directly supported and it has 4 elements, use
5704   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5705   unsigned NumElts = VT.getVectorNumElements();
5706   if (NumElts == 4) {
5707     unsigned PFIndexes[4];
5708     for (unsigned i = 0; i != 4; ++i) {
5709       if (ShuffleMask[i] < 0)
5710         PFIndexes[i] = 8;
5711       else
5712         PFIndexes[i] = ShuffleMask[i];
5713     }
5714
5715     // Compute the index in the perfect shuffle table.
5716     unsigned PFTableIndex =
5717       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5718     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5719     unsigned Cost = (PFEntry >> 30);
5720
5721     if (Cost <= 4)
5722       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5723   }
5724
5725   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5726   if (EltSize >= 32) {
5727     // Do the expansion with floating-point types, since that is what the VFP
5728     // registers are defined to use, and since i64 is not legal.
5729     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5730     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5731     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5732     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5733     SmallVector<SDValue, 8> Ops;
5734     for (unsigned i = 0; i < NumElts; ++i) {
5735       if (ShuffleMask[i] < 0)
5736         Ops.push_back(DAG.getUNDEF(EltVT));
5737       else
5738         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5739                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
5740                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5741                                                   MVT::i32)));
5742     }
5743     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5744     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5745   }
5746
5747   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5748     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5749
5750   if (VT == MVT::v8i8) {
5751     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5752     if (NewOp.getNode())
5753       return NewOp;
5754   }
5755
5756   return SDValue();
5757 }
5758
5759 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5760   // INSERT_VECTOR_ELT is legal only for immediate indexes.
5761   SDValue Lane = Op.getOperand(2);
5762   if (!isa<ConstantSDNode>(Lane))
5763     return SDValue();
5764
5765   return Op;
5766 }
5767
5768 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5769   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5770   SDValue Lane = Op.getOperand(1);
5771   if (!isa<ConstantSDNode>(Lane))
5772     return SDValue();
5773
5774   SDValue Vec = Op.getOperand(0);
5775   if (Op.getValueType() == MVT::i32 &&
5776       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5777     SDLoc dl(Op);
5778     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5779   }
5780
5781   return Op;
5782 }
5783
5784 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5785   // The only time a CONCAT_VECTORS operation can have legal types is when
5786   // two 64-bit vectors are concatenated to a 128-bit vector.
5787   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5788          "unexpected CONCAT_VECTORS");
5789   SDLoc dl(Op);
5790   SDValue Val = DAG.getUNDEF(MVT::v2f64);
5791   SDValue Op0 = Op.getOperand(0);
5792   SDValue Op1 = Op.getOperand(1);
5793   if (Op0.getOpcode() != ISD::UNDEF)
5794     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5795                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5796                       DAG.getIntPtrConstant(0));
5797   if (Op1.getOpcode() != ISD::UNDEF)
5798     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5799                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5800                       DAG.getIntPtrConstant(1));
5801   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5802 }
5803
5804 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5805 /// element has been zero/sign-extended, depending on the isSigned parameter,
5806 /// from an integer type half its size.
5807 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5808                                    bool isSigned) {
5809   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5810   EVT VT = N->getValueType(0);
5811   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5812     SDNode *BVN = N->getOperand(0).getNode();
5813     if (BVN->getValueType(0) != MVT::v4i32 ||
5814         BVN->getOpcode() != ISD::BUILD_VECTOR)
5815       return false;
5816     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5817     unsigned HiElt = 1 - LoElt;
5818     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5819     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5820     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5821     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5822     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5823       return false;
5824     if (isSigned) {
5825       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5826           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5827         return true;
5828     } else {
5829       if (Hi0->isNullValue() && Hi1->isNullValue())
5830         return true;
5831     }
5832     return false;
5833   }
5834
5835   if (N->getOpcode() != ISD::BUILD_VECTOR)
5836     return false;
5837
5838   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5839     SDNode *Elt = N->getOperand(i).getNode();
5840     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5841       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5842       unsigned HalfSize = EltSize / 2;
5843       if (isSigned) {
5844         if (!isIntN(HalfSize, C->getSExtValue()))
5845           return false;
5846       } else {
5847         if (!isUIntN(HalfSize, C->getZExtValue()))
5848           return false;
5849       }
5850       continue;
5851     }
5852     return false;
5853   }
5854
5855   return true;
5856 }
5857
5858 /// isSignExtended - Check if a node is a vector value that is sign-extended
5859 /// or a constant BUILD_VECTOR with sign-extended elements.
5860 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5861   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5862     return true;
5863   if (isExtendedBUILD_VECTOR(N, DAG, true))
5864     return true;
5865   return false;
5866 }
5867
5868 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5869 /// or a constant BUILD_VECTOR with zero-extended elements.
5870 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5871   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5872     return true;
5873   if (isExtendedBUILD_VECTOR(N, DAG, false))
5874     return true;
5875   return false;
5876 }
5877
5878 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5879   if (OrigVT.getSizeInBits() >= 64)
5880     return OrigVT;
5881
5882   assert(OrigVT.isSimple() && "Expecting a simple value type");
5883
5884   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5885   switch (OrigSimpleTy) {
5886   default: llvm_unreachable("Unexpected Vector Type");
5887   case MVT::v2i8:
5888   case MVT::v2i16:
5889      return MVT::v2i32;
5890   case MVT::v4i8:
5891     return  MVT::v4i16;
5892   }
5893 }
5894
5895 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5896 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5897 /// We insert the required extension here to get the vector to fill a D register.
5898 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5899                                             const EVT &OrigTy,
5900                                             const EVT &ExtTy,
5901                                             unsigned ExtOpcode) {
5902   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5903   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5904   // 64-bits we need to insert a new extension so that it will be 64-bits.
5905   assert(ExtTy.is128BitVector() && "Unexpected extension size");
5906   if (OrigTy.getSizeInBits() >= 64)
5907     return N;
5908
5909   // Must extend size to at least 64 bits to be used as an operand for VMULL.
5910   EVT NewVT = getExtensionTo64Bits(OrigTy);
5911
5912   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5913 }
5914
5915 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5916 /// does not do any sign/zero extension. If the original vector is less
5917 /// than 64 bits, an appropriate extension will be added after the load to
5918 /// reach a total size of 64 bits. We have to add the extension separately
5919 /// because ARM does not have a sign/zero extending load for vectors.
5920 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5921   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5922
5923   // The load already has the right type.
5924   if (ExtendedTy == LD->getMemoryVT())
5925     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5926                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5927                 LD->isNonTemporal(), LD->isInvariant(),
5928                 LD->getAlignment());
5929
5930   // We need to create a zextload/sextload. We cannot just create a load
5931   // followed by a zext/zext node because LowerMUL is also run during normal
5932   // operation legalization where we can't create illegal types.
5933   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5934                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5935                         LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
5936                         LD->isNonTemporal(), LD->getAlignment());
5937 }
5938
5939 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5940 /// extending load, or BUILD_VECTOR with extended elements, return the
5941 /// unextended value. The unextended vector should be 64 bits so that it can
5942 /// be used as an operand to a VMULL instruction. If the original vector size
5943 /// before extension is less than 64 bits we add a an extension to resize
5944 /// the vector to 64 bits.
5945 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5946   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5947     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5948                                         N->getOperand(0)->getValueType(0),
5949                                         N->getValueType(0),
5950                                         N->getOpcode());
5951
5952   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5953     return SkipLoadExtensionForVMULL(LD, DAG);
5954
5955   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
5956   // have been legalized as a BITCAST from v4i32.
5957   if (N->getOpcode() == ISD::BITCAST) {
5958     SDNode *BVN = N->getOperand(0).getNode();
5959     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5960            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5961     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5962     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5963                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5964   }
5965   // Construct a new BUILD_VECTOR with elements truncated to half the size.
5966   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5967   EVT VT = N->getValueType(0);
5968   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5969   unsigned NumElts = VT.getVectorNumElements();
5970   MVT TruncVT = MVT::getIntegerVT(EltSize);
5971   SmallVector<SDValue, 8> Ops;
5972   for (unsigned i = 0; i != NumElts; ++i) {
5973     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5974     const APInt &CInt = C->getAPIntValue();
5975     // Element types smaller than 32 bits are not legal, so use i32 elements.
5976     // The values are implicitly truncated so sext vs. zext doesn't matter.
5977     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5978   }
5979   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5980                      MVT::getVectorVT(TruncVT, NumElts), Ops);
5981 }
5982
5983 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5984   unsigned Opcode = N->getOpcode();
5985   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5986     SDNode *N0 = N->getOperand(0).getNode();
5987     SDNode *N1 = N->getOperand(1).getNode();
5988     return N0->hasOneUse() && N1->hasOneUse() &&
5989       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5990   }
5991   return false;
5992 }
5993
5994 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5995   unsigned Opcode = N->getOpcode();
5996   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5997     SDNode *N0 = N->getOperand(0).getNode();
5998     SDNode *N1 = N->getOperand(1).getNode();
5999     return N0->hasOneUse() && N1->hasOneUse() &&
6000       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
6001   }
6002   return false;
6003 }
6004
6005 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
6006   // Multiplications are only custom-lowered for 128-bit vectors so that
6007   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
6008   EVT VT = Op.getValueType();
6009   assert(VT.is128BitVector() && VT.isInteger() &&
6010          "unexpected type for custom-lowering ISD::MUL");
6011   SDNode *N0 = Op.getOperand(0).getNode();
6012   SDNode *N1 = Op.getOperand(1).getNode();
6013   unsigned NewOpc = 0;
6014   bool isMLA = false;
6015   bool isN0SExt = isSignExtended(N0, DAG);
6016   bool isN1SExt = isSignExtended(N1, DAG);
6017   if (isN0SExt && isN1SExt)
6018     NewOpc = ARMISD::VMULLs;
6019   else {
6020     bool isN0ZExt = isZeroExtended(N0, DAG);
6021     bool isN1ZExt = isZeroExtended(N1, DAG);
6022     if (isN0ZExt && isN1ZExt)
6023       NewOpc = ARMISD::VMULLu;
6024     else if (isN1SExt || isN1ZExt) {
6025       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
6026       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
6027       if (isN1SExt && isAddSubSExt(N0, DAG)) {
6028         NewOpc = ARMISD::VMULLs;
6029         isMLA = true;
6030       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
6031         NewOpc = ARMISD::VMULLu;
6032         isMLA = true;
6033       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
6034         std::swap(N0, N1);
6035         NewOpc = ARMISD::VMULLu;
6036         isMLA = true;
6037       }
6038     }
6039
6040     if (!NewOpc) {
6041       if (VT == MVT::v2i64)
6042         // Fall through to expand this.  It is not legal.
6043         return SDValue();
6044       else
6045         // Other vector multiplications are legal.
6046         return Op;
6047     }
6048   }
6049
6050   // Legalize to a VMULL instruction.
6051   SDLoc DL(Op);
6052   SDValue Op0;
6053   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
6054   if (!isMLA) {
6055     Op0 = SkipExtensionForVMULL(N0, DAG);
6056     assert(Op0.getValueType().is64BitVector() &&
6057            Op1.getValueType().is64BitVector() &&
6058            "unexpected types for extended operands to VMULL");
6059     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
6060   }
6061
6062   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
6063   // isel lowering to take advantage of no-stall back to back vmul + vmla.
6064   //   vmull q0, d4, d6
6065   //   vmlal q0, d5, d6
6066   // is faster than
6067   //   vaddl q0, d4, d5
6068   //   vmovl q1, d6
6069   //   vmul  q0, q0, q1
6070   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
6071   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
6072   EVT Op1VT = Op1.getValueType();
6073   return DAG.getNode(N0->getOpcode(), DL, VT,
6074                      DAG.getNode(NewOpc, DL, VT,
6075                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
6076                      DAG.getNode(NewOpc, DL, VT,
6077                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
6078 }
6079
6080 static SDValue
6081 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
6082   // Convert to float
6083   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
6084   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
6085   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
6086   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
6087   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
6088   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
6089   // Get reciprocal estimate.
6090   // float4 recip = vrecpeq_f32(yf);
6091   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6092                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
6093   // Because char has a smaller range than uchar, we can actually get away
6094   // without any newton steps.  This requires that we use a weird bias
6095   // of 0xb000, however (again, this has been exhaustively tested).
6096   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
6097   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
6098   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
6099   Y = DAG.getConstant(0xb000, MVT::i32);
6100   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
6101   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6102   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6103   // Convert back to short.
6104   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6105   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6106   return X;
6107 }
6108
6109 static SDValue
6110 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
6111   SDValue N2;
6112   // Convert to float.
6113   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6114   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6115   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6116   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6117   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6118   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6119
6120   // Use reciprocal estimate and one refinement step.
6121   // float4 recip = vrecpeq_f32(yf);
6122   // recip *= vrecpsq_f32(yf, recip);
6123   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6124                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
6125   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6126                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6127                    N1, N2);
6128   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6129   // Because short has a smaller range than ushort, we can actually get away
6130   // with only a single newton step.  This requires that we use a weird bias
6131   // of 89, however (again, this has been exhaustively tested).
6132   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6133   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6134   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6135   N1 = DAG.getConstant(0x89, MVT::i32);
6136   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6137   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6138   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6139   // Convert back to integer and return.
6140   // return vmovn_s32(vcvt_s32_f32(result));
6141   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6142   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6143   return N0;
6144 }
6145
6146 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6147   EVT VT = Op.getValueType();
6148   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6149          "unexpected type for custom-lowering ISD::SDIV");
6150
6151   SDLoc dl(Op);
6152   SDValue N0 = Op.getOperand(0);
6153   SDValue N1 = Op.getOperand(1);
6154   SDValue N2, N3;
6155
6156   if (VT == MVT::v8i8) {
6157     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6158     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6159
6160     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6161                      DAG.getIntPtrConstant(4));
6162     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6163                      DAG.getIntPtrConstant(4));
6164     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6165                      DAG.getIntPtrConstant(0));
6166     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6167                      DAG.getIntPtrConstant(0));
6168
6169     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6170     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6171
6172     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6173     N0 = LowerCONCAT_VECTORS(N0, DAG);
6174
6175     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6176     return N0;
6177   }
6178   return LowerSDIV_v4i16(N0, N1, dl, DAG);
6179 }
6180
6181 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6182   EVT VT = Op.getValueType();
6183   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6184          "unexpected type for custom-lowering ISD::UDIV");
6185
6186   SDLoc dl(Op);
6187   SDValue N0 = Op.getOperand(0);
6188   SDValue N1 = Op.getOperand(1);
6189   SDValue N2, N3;
6190
6191   if (VT == MVT::v8i8) {
6192     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6193     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6194
6195     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6196                      DAG.getIntPtrConstant(4));
6197     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6198                      DAG.getIntPtrConstant(4));
6199     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6200                      DAG.getIntPtrConstant(0));
6201     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6202                      DAG.getIntPtrConstant(0));
6203
6204     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6205     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6206
6207     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6208     N0 = LowerCONCAT_VECTORS(N0, DAG);
6209
6210     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6211                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
6212                      N0);
6213     return N0;
6214   }
6215
6216   // v4i16 sdiv ... Convert to float.
6217   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6218   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6219   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6220   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6221   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6222   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6223
6224   // Use reciprocal estimate and two refinement steps.
6225   // float4 recip = vrecpeq_f32(yf);
6226   // recip *= vrecpsq_f32(yf, recip);
6227   // recip *= vrecpsq_f32(yf, recip);
6228   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6229                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
6230   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6231                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6232                    BN1, N2);
6233   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6234   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6235                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6236                    BN1, N2);
6237   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6238   // Simply multiplying by the reciprocal estimate can leave us a few ulps
6239   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6240   // and that it will never cause us to return an answer too large).
6241   // float4 result = as_float4(as_int4(xf*recip) + 2);
6242   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6243   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6244   N1 = DAG.getConstant(2, MVT::i32);
6245   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6246   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6247   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6248   // Convert back to integer and return.
6249   // return vmovn_u32(vcvt_s32_f32(result));
6250   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6251   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6252   return N0;
6253 }
6254
6255 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6256   EVT VT = Op.getNode()->getValueType(0);
6257   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6258
6259   unsigned Opc;
6260   bool ExtraOp = false;
6261   switch (Op.getOpcode()) {
6262   default: llvm_unreachable("Invalid code");
6263   case ISD::ADDC: Opc = ARMISD::ADDC; break;
6264   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6265   case ISD::SUBC: Opc = ARMISD::SUBC; break;
6266   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6267   }
6268
6269   if (!ExtraOp)
6270     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6271                        Op.getOperand(1));
6272   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6273                      Op.getOperand(1), Op.getOperand(2));
6274 }
6275
6276 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6277   assert(Subtarget->isTargetDarwin());
6278
6279   // For iOS, we want to call an alternative entry point: __sincos_stret,
6280   // return values are passed via sret.
6281   SDLoc dl(Op);
6282   SDValue Arg = Op.getOperand(0);
6283   EVT ArgVT = Arg.getValueType();
6284   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6285
6286   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6287   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6288
6289   // Pair of floats / doubles used to pass the result.
6290   StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
6291
6292   // Create stack object for sret.
6293   const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
6294   const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
6295   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6296   SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
6297
6298   ArgListTy Args;
6299   ArgListEntry Entry;
6300
6301   Entry.Node = SRet;
6302   Entry.Ty = RetTy->getPointerTo();
6303   Entry.isSExt = false;
6304   Entry.isZExt = false;
6305   Entry.isSRet = true;
6306   Args.push_back(Entry);
6307
6308   Entry.Node = Arg;
6309   Entry.Ty = ArgTy;
6310   Entry.isSExt = false;
6311   Entry.isZExt = false;
6312   Args.push_back(Entry);
6313
6314   const char *LibcallName  = (ArgVT == MVT::f64)
6315   ? "__sincos_stret" : "__sincosf_stret";
6316   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
6317
6318   TargetLowering::CallLoweringInfo CLI(DAG);
6319   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6320     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6321                std::move(Args), 0)
6322     .setDiscardResult();
6323
6324   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6325
6326   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6327                                 MachinePointerInfo(), false, false, false, 0);
6328
6329   // Address of cos field.
6330   SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
6331                             DAG.getIntPtrConstant(ArgVT.getStoreSize()));
6332   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6333                                 MachinePointerInfo(), false, false, false, 0);
6334
6335   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6336   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6337                      LoadSin.getValue(0), LoadCos.getValue(0));
6338 }
6339
6340 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6341   // Monotonic load/store is legal for all targets
6342   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6343     return Op;
6344
6345   // Acquire/Release load/store is not legal for targets without a
6346   // dmb or equivalent available.
6347   return SDValue();
6348 }
6349
6350 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6351                                     SmallVectorImpl<SDValue> &Results,
6352                                     SelectionDAG &DAG,
6353                                     const ARMSubtarget *Subtarget) {
6354   SDLoc DL(N);
6355   SDValue Cycles32, OutChain;
6356
6357   if (Subtarget->hasPerfMon()) {
6358     // Under Power Management extensions, the cycle-count is:
6359     //    mrc p15, #0, <Rt>, c9, c13, #0
6360     SDValue Ops[] = { N->getOperand(0), // Chain
6361                       DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
6362                       DAG.getConstant(15, MVT::i32),
6363                       DAG.getConstant(0, MVT::i32),
6364                       DAG.getConstant(9, MVT::i32),
6365                       DAG.getConstant(13, MVT::i32),
6366                       DAG.getConstant(0, MVT::i32)
6367     };
6368
6369     Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6370                            DAG.getVTList(MVT::i32, MVT::Other), Ops);
6371     OutChain = Cycles32.getValue(1);
6372   } else {
6373     // Intrinsic is defined to return 0 on unsupported platforms. Technically
6374     // there are older ARM CPUs that have implementation-specific ways of
6375     // obtaining this information (FIXME!).
6376     Cycles32 = DAG.getConstant(0, MVT::i32);
6377     OutChain = DAG.getEntryNode();
6378   }
6379
6380
6381   SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6382                                  Cycles32, DAG.getConstant(0, MVT::i32));
6383   Results.push_back(Cycles64);
6384   Results.push_back(OutChain);
6385 }
6386
6387 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6388   switch (Op.getOpcode()) {
6389   default: llvm_unreachable("Don't know how to custom lower this!");
6390   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6391   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6392   case ISD::GlobalAddress:
6393     switch (Subtarget->getTargetTriple().getObjectFormat()) {
6394     default: llvm_unreachable("unknown object format");
6395     case Triple::COFF:
6396       return LowerGlobalAddressWindows(Op, DAG);
6397     case Triple::ELF:
6398       return LowerGlobalAddressELF(Op, DAG);
6399     case Triple::MachO:
6400       return LowerGlobalAddressDarwin(Op, DAG);
6401     }
6402   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6403   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6404   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6405   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6406   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6407   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6408   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6409   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6410   case ISD::SINT_TO_FP:
6411   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6412   case ISD::FP_TO_SINT:
6413   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6414   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6415   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6416   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6417   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6418   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6419   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6420   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6421                                                                Subtarget);
6422   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6423   case ISD::SHL:
6424   case ISD::SRL:
6425   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6426   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6427   case ISD::SRL_PARTS:
6428   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6429   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6430   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6431   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6432   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6433   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6434   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6435   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6436   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6437   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6438   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6439   case ISD::MUL:           return LowerMUL(Op, DAG);
6440   case ISD::SDIV:          return LowerSDIV(Op, DAG);
6441   case ISD::UDIV:          return LowerUDIV(Op, DAG);
6442   case ISD::ADDC:
6443   case ISD::ADDE:
6444   case ISD::SUBC:
6445   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6446   case ISD::SADDO:
6447   case ISD::UADDO:
6448   case ISD::SSUBO:
6449   case ISD::USUBO:
6450     return LowerXALUO(Op, DAG);
6451   case ISD::ATOMIC_LOAD:
6452   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6453   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6454   case ISD::SDIVREM:
6455   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6456   case ISD::DYNAMIC_STACKALLOC:
6457     if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6458       return LowerDYNAMIC_STACKALLOC(Op, DAG);
6459     llvm_unreachable("Don't know how to custom lower this!");
6460   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6461   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6462   }
6463 }
6464
6465 /// ReplaceNodeResults - Replace the results of node with an illegal result
6466 /// type with new values built out of custom code.
6467 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6468                                            SmallVectorImpl<SDValue>&Results,
6469                                            SelectionDAG &DAG) const {
6470   SDValue Res;
6471   switch (N->getOpcode()) {
6472   default:
6473     llvm_unreachable("Don't know how to custom expand this!");
6474   case ISD::BITCAST:
6475     Res = ExpandBITCAST(N, DAG);
6476     break;
6477   case ISD::SRL:
6478   case ISD::SRA:
6479     Res = Expand64BitShift(N, DAG, Subtarget);
6480     break;
6481   case ISD::READCYCLECOUNTER:
6482     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6483     return;
6484   }
6485   if (Res.getNode())
6486     Results.push_back(Res);
6487 }
6488
6489 //===----------------------------------------------------------------------===//
6490 //                           ARM Scheduler Hooks
6491 //===----------------------------------------------------------------------===//
6492
6493 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6494 /// registers the function context.
6495 void ARMTargetLowering::
6496 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6497                        MachineBasicBlock *DispatchBB, int FI) const {
6498   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6499   DebugLoc dl = MI->getDebugLoc();
6500   MachineFunction *MF = MBB->getParent();
6501   MachineRegisterInfo *MRI = &MF->getRegInfo();
6502   MachineConstantPool *MCP = MF->getConstantPool();
6503   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6504   const Function *F = MF->getFunction();
6505
6506   bool isThumb = Subtarget->isThumb();
6507   bool isThumb2 = Subtarget->isThumb2();
6508
6509   unsigned PCLabelId = AFI->createPICLabelUId();
6510   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6511   ARMConstantPoolValue *CPV =
6512     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6513   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6514
6515   const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
6516                                            : &ARM::GPRRegClass;
6517
6518   // Grab constant pool and fixed stack memory operands.
6519   MachineMemOperand *CPMMO =
6520     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6521                              MachineMemOperand::MOLoad, 4, 4);
6522
6523   MachineMemOperand *FIMMOSt =
6524     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6525                              MachineMemOperand::MOStore, 4, 4);
6526
6527   // Load the address of the dispatch MBB into the jump buffer.
6528   if (isThumb2) {
6529     // Incoming value: jbuf
6530     //   ldr.n  r5, LCPI1_1
6531     //   orr    r5, r5, #1
6532     //   add    r5, pc
6533     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6534     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6535     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6536                    .addConstantPoolIndex(CPI)
6537                    .addMemOperand(CPMMO));
6538     // Set the low bit because of thumb mode.
6539     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6540     AddDefaultCC(
6541       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6542                      .addReg(NewVReg1, RegState::Kill)
6543                      .addImm(0x01)));
6544     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6545     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6546       .addReg(NewVReg2, RegState::Kill)
6547       .addImm(PCLabelId);
6548     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6549                    .addReg(NewVReg3, RegState::Kill)
6550                    .addFrameIndex(FI)
6551                    .addImm(36)  // &jbuf[1] :: pc
6552                    .addMemOperand(FIMMOSt));
6553   } else if (isThumb) {
6554     // Incoming value: jbuf
6555     //   ldr.n  r1, LCPI1_4
6556     //   add    r1, pc
6557     //   mov    r2, #1
6558     //   orrs   r1, r2
6559     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6560     //   str    r1, [r2]
6561     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6562     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6563                    .addConstantPoolIndex(CPI)
6564                    .addMemOperand(CPMMO));
6565     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6566     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6567       .addReg(NewVReg1, RegState::Kill)
6568       .addImm(PCLabelId);
6569     // Set the low bit because of thumb mode.
6570     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6571     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6572                    .addReg(ARM::CPSR, RegState::Define)
6573                    .addImm(1));
6574     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6575     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6576                    .addReg(ARM::CPSR, RegState::Define)
6577                    .addReg(NewVReg2, RegState::Kill)
6578                    .addReg(NewVReg3, RegState::Kill));
6579     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6580     BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
6581             .addFrameIndex(FI)
6582             .addImm(36); // &jbuf[1] :: pc
6583     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6584                    .addReg(NewVReg4, RegState::Kill)
6585                    .addReg(NewVReg5, RegState::Kill)
6586                    .addImm(0)
6587                    .addMemOperand(FIMMOSt));
6588   } else {
6589     // Incoming value: jbuf
6590     //   ldr  r1, LCPI1_1
6591     //   add  r1, pc, r1
6592     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6593     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6594     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6595                    .addConstantPoolIndex(CPI)
6596                    .addImm(0)
6597                    .addMemOperand(CPMMO));
6598     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6599     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6600                    .addReg(NewVReg1, RegState::Kill)
6601                    .addImm(PCLabelId));
6602     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6603                    .addReg(NewVReg2, RegState::Kill)
6604                    .addFrameIndex(FI)
6605                    .addImm(36)  // &jbuf[1] :: pc
6606                    .addMemOperand(FIMMOSt));
6607   }
6608 }
6609
6610 MachineBasicBlock *ARMTargetLowering::
6611 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6612   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6613   DebugLoc dl = MI->getDebugLoc();
6614   MachineFunction *MF = MBB->getParent();
6615   MachineRegisterInfo *MRI = &MF->getRegInfo();
6616   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6617   MachineFrameInfo *MFI = MF->getFrameInfo();
6618   int FI = MFI->getFunctionContextIndex();
6619
6620   const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
6621                                                         : &ARM::GPRnopcRegClass;
6622
6623   // Get a mapping of the call site numbers to all of the landing pads they're
6624   // associated with.
6625   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6626   unsigned MaxCSNum = 0;
6627   MachineModuleInfo &MMI = MF->getMMI();
6628   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6629        ++BB) {
6630     if (!BB->isLandingPad()) continue;
6631
6632     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6633     // pad.
6634     for (MachineBasicBlock::iterator
6635            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6636       if (!II->isEHLabel()) continue;
6637
6638       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6639       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6640
6641       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6642       for (SmallVectorImpl<unsigned>::iterator
6643              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6644            CSI != CSE; ++CSI) {
6645         CallSiteNumToLPad[*CSI].push_back(BB);
6646         MaxCSNum = std::max(MaxCSNum, *CSI);
6647       }
6648       break;
6649     }
6650   }
6651
6652   // Get an ordered list of the machine basic blocks for the jump table.
6653   std::vector<MachineBasicBlock*> LPadList;
6654   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6655   LPadList.reserve(CallSiteNumToLPad.size());
6656   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6657     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6658     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6659            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6660       LPadList.push_back(*II);
6661       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6662     }
6663   }
6664
6665   assert(!LPadList.empty() &&
6666          "No landing pad destinations for the dispatch jump table!");
6667
6668   // Create the jump table and associated information.
6669   MachineJumpTableInfo *JTI =
6670     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6671   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6672   unsigned UId = AFI->createJumpTableUId();
6673   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6674
6675   // Create the MBBs for the dispatch code.
6676
6677   // Shove the dispatch's address into the return slot in the function context.
6678   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6679   DispatchBB->setIsLandingPad();
6680
6681   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6682   unsigned trap_opcode;
6683   if (Subtarget->isThumb())
6684     trap_opcode = ARM::tTRAP;
6685   else
6686     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6687
6688   BuildMI(TrapBB, dl, TII->get(trap_opcode));
6689   DispatchBB->addSuccessor(TrapBB);
6690
6691   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6692   DispatchBB->addSuccessor(DispContBB);
6693
6694   // Insert and MBBs.
6695   MF->insert(MF->end(), DispatchBB);
6696   MF->insert(MF->end(), DispContBB);
6697   MF->insert(MF->end(), TrapBB);
6698
6699   // Insert code into the entry block that creates and registers the function
6700   // context.
6701   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6702
6703   MachineMemOperand *FIMMOLd =
6704     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6705                              MachineMemOperand::MOLoad |
6706                              MachineMemOperand::MOVolatile, 4, 4);
6707
6708   MachineInstrBuilder MIB;
6709   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6710
6711   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6712   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6713
6714   // Add a register mask with no preserved registers.  This results in all
6715   // registers being marked as clobbered.
6716   MIB.addRegMask(RI.getNoPreservedMask());
6717
6718   unsigned NumLPads = LPadList.size();
6719   if (Subtarget->isThumb2()) {
6720     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6721     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6722                    .addFrameIndex(FI)
6723                    .addImm(4)
6724                    .addMemOperand(FIMMOLd));
6725
6726     if (NumLPads < 256) {
6727       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6728                      .addReg(NewVReg1)
6729                      .addImm(LPadList.size()));
6730     } else {
6731       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6732       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6733                      .addImm(NumLPads & 0xFFFF));
6734
6735       unsigned VReg2 = VReg1;
6736       if ((NumLPads & 0xFFFF0000) != 0) {
6737         VReg2 = MRI->createVirtualRegister(TRC);
6738         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6739                        .addReg(VReg1)
6740                        .addImm(NumLPads >> 16));
6741       }
6742
6743       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6744                      .addReg(NewVReg1)
6745                      .addReg(VReg2));
6746     }
6747
6748     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6749       .addMBB(TrapBB)
6750       .addImm(ARMCC::HI)
6751       .addReg(ARM::CPSR);
6752
6753     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6754     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6755                    .addJumpTableIndex(MJTI)
6756                    .addImm(UId));
6757
6758     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6759     AddDefaultCC(
6760       AddDefaultPred(
6761         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6762         .addReg(NewVReg3, RegState::Kill)
6763         .addReg(NewVReg1)
6764         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6765
6766     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6767       .addReg(NewVReg4, RegState::Kill)
6768       .addReg(NewVReg1)
6769       .addJumpTableIndex(MJTI)
6770       .addImm(UId);
6771   } else if (Subtarget->isThumb()) {
6772     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6773     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6774                    .addFrameIndex(FI)
6775                    .addImm(1)
6776                    .addMemOperand(FIMMOLd));
6777
6778     if (NumLPads < 256) {
6779       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6780                      .addReg(NewVReg1)
6781                      .addImm(NumLPads));
6782     } else {
6783       MachineConstantPool *ConstantPool = MF->getConstantPool();
6784       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6785       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6786
6787       // MachineConstantPool wants an explicit alignment.
6788       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6789       if (Align == 0)
6790         Align = getDataLayout()->getTypeAllocSize(C->getType());
6791       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6792
6793       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6794       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6795                      .addReg(VReg1, RegState::Define)
6796                      .addConstantPoolIndex(Idx));
6797       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6798                      .addReg(NewVReg1)
6799                      .addReg(VReg1));
6800     }
6801
6802     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6803       .addMBB(TrapBB)
6804       .addImm(ARMCC::HI)
6805       .addReg(ARM::CPSR);
6806
6807     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6808     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6809                    .addReg(ARM::CPSR, RegState::Define)
6810                    .addReg(NewVReg1)
6811                    .addImm(2));
6812
6813     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6814     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6815                    .addJumpTableIndex(MJTI)
6816                    .addImm(UId));
6817
6818     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6819     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6820                    .addReg(ARM::CPSR, RegState::Define)
6821                    .addReg(NewVReg2, RegState::Kill)
6822                    .addReg(NewVReg3));
6823
6824     MachineMemOperand *JTMMOLd =
6825       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6826                                MachineMemOperand::MOLoad, 4, 4);
6827
6828     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6829     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6830                    .addReg(NewVReg4, RegState::Kill)
6831                    .addImm(0)
6832                    .addMemOperand(JTMMOLd));
6833
6834     unsigned NewVReg6 = NewVReg5;
6835     if (RelocM == Reloc::PIC_) {
6836       NewVReg6 = MRI->createVirtualRegister(TRC);
6837       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6838                      .addReg(ARM::CPSR, RegState::Define)
6839                      .addReg(NewVReg5, RegState::Kill)
6840                      .addReg(NewVReg3));
6841     }
6842
6843     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6844       .addReg(NewVReg6, RegState::Kill)
6845       .addJumpTableIndex(MJTI)
6846       .addImm(UId);
6847   } else {
6848     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6849     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6850                    .addFrameIndex(FI)
6851                    .addImm(4)
6852                    .addMemOperand(FIMMOLd));
6853
6854     if (NumLPads < 256) {
6855       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6856                      .addReg(NewVReg1)
6857                      .addImm(NumLPads));
6858     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6859       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6860       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6861                      .addImm(NumLPads & 0xFFFF));
6862
6863       unsigned VReg2 = VReg1;
6864       if ((NumLPads & 0xFFFF0000) != 0) {
6865         VReg2 = MRI->createVirtualRegister(TRC);
6866         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6867                        .addReg(VReg1)
6868                        .addImm(NumLPads >> 16));
6869       }
6870
6871       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6872                      .addReg(NewVReg1)
6873                      .addReg(VReg2));
6874     } else {
6875       MachineConstantPool *ConstantPool = MF->getConstantPool();
6876       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6877       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6878
6879       // MachineConstantPool wants an explicit alignment.
6880       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6881       if (Align == 0)
6882         Align = getDataLayout()->getTypeAllocSize(C->getType());
6883       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6884
6885       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6886       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6887                      .addReg(VReg1, RegState::Define)
6888                      .addConstantPoolIndex(Idx)
6889                      .addImm(0));
6890       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6891                      .addReg(NewVReg1)
6892                      .addReg(VReg1, RegState::Kill));
6893     }
6894
6895     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6896       .addMBB(TrapBB)
6897       .addImm(ARMCC::HI)
6898       .addReg(ARM::CPSR);
6899
6900     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6901     AddDefaultCC(
6902       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6903                      .addReg(NewVReg1)
6904                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6905     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6906     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6907                    .addJumpTableIndex(MJTI)
6908                    .addImm(UId));
6909
6910     MachineMemOperand *JTMMOLd =
6911       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6912                                MachineMemOperand::MOLoad, 4, 4);
6913     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6914     AddDefaultPred(
6915       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6916       .addReg(NewVReg3, RegState::Kill)
6917       .addReg(NewVReg4)
6918       .addImm(0)
6919       .addMemOperand(JTMMOLd));
6920
6921     if (RelocM == Reloc::PIC_) {
6922       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6923         .addReg(NewVReg5, RegState::Kill)
6924         .addReg(NewVReg4)
6925         .addJumpTableIndex(MJTI)
6926         .addImm(UId);
6927     } else {
6928       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6929         .addReg(NewVReg5, RegState::Kill)
6930         .addJumpTableIndex(MJTI)
6931         .addImm(UId);
6932     }
6933   }
6934
6935   // Add the jump table entries as successors to the MBB.
6936   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6937   for (std::vector<MachineBasicBlock*>::iterator
6938          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6939     MachineBasicBlock *CurMBB = *I;
6940     if (SeenMBBs.insert(CurMBB).second)
6941       DispContBB->addSuccessor(CurMBB);
6942   }
6943
6944   // N.B. the order the invoke BBs are processed in doesn't matter here.
6945   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
6946   SmallVector<MachineBasicBlock*, 64> MBBLPads;
6947   for (MachineBasicBlock *BB : InvokeBBs) {
6948
6949     // Remove the landing pad successor from the invoke block and replace it
6950     // with the new dispatch block.
6951     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6952                                                   BB->succ_end());
6953     while (!Successors.empty()) {
6954       MachineBasicBlock *SMBB = Successors.pop_back_val();
6955       if (SMBB->isLandingPad()) {
6956         BB->removeSuccessor(SMBB);
6957         MBBLPads.push_back(SMBB);
6958       }
6959     }
6960
6961     BB->addSuccessor(DispatchBB);
6962
6963     // Find the invoke call and mark all of the callee-saved registers as
6964     // 'implicit defined' so that they're spilled. This prevents code from
6965     // moving instructions to before the EH block, where they will never be
6966     // executed.
6967     for (MachineBasicBlock::reverse_iterator
6968            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6969       if (!II->isCall()) continue;
6970
6971       DenseMap<unsigned, bool> DefRegs;
6972       for (MachineInstr::mop_iterator
6973              OI = II->operands_begin(), OE = II->operands_end();
6974            OI != OE; ++OI) {
6975         if (!OI->isReg()) continue;
6976         DefRegs[OI->getReg()] = true;
6977       }
6978
6979       MachineInstrBuilder MIB(*MF, &*II);
6980
6981       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6982         unsigned Reg = SavedRegs[i];
6983         if (Subtarget->isThumb2() &&
6984             !ARM::tGPRRegClass.contains(Reg) &&
6985             !ARM::hGPRRegClass.contains(Reg))
6986           continue;
6987         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6988           continue;
6989         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6990           continue;
6991         if (!DefRegs[Reg])
6992           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6993       }
6994
6995       break;
6996     }
6997   }
6998
6999   // Mark all former landing pads as non-landing pads. The dispatch is the only
7000   // landing pad now.
7001   for (SmallVectorImpl<MachineBasicBlock*>::iterator
7002          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7003     (*I)->setIsLandingPad(false);
7004
7005   // The instruction is gone now.
7006   MI->eraseFromParent();
7007
7008   return MBB;
7009 }
7010
7011 static
7012 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7013   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7014        E = MBB->succ_end(); I != E; ++I)
7015     if (*I != Succ)
7016       return *I;
7017   llvm_unreachable("Expecting a BB with two successors!");
7018 }
7019
7020 /// Return the load opcode for a given load size. If load size >= 8,
7021 /// neon opcode will be returned.
7022 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7023   if (LdSize >= 8)
7024     return LdSize == 16 ? ARM::VLD1q32wb_fixed
7025                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7026   if (IsThumb1)
7027     return LdSize == 4 ? ARM::tLDRi
7028                        : LdSize == 2 ? ARM::tLDRHi
7029                                      : LdSize == 1 ? ARM::tLDRBi : 0;
7030   if (IsThumb2)
7031     return LdSize == 4 ? ARM::t2LDR_POST
7032                        : LdSize == 2 ? ARM::t2LDRH_POST
7033                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7034   return LdSize == 4 ? ARM::LDR_POST_IMM
7035                      : LdSize == 2 ? ARM::LDRH_POST
7036                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7037 }
7038
7039 /// Return the store opcode for a given store size. If store size >= 8,
7040 /// neon opcode will be returned.
7041 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7042   if (StSize >= 8)
7043     return StSize == 16 ? ARM::VST1q32wb_fixed
7044                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7045   if (IsThumb1)
7046     return StSize == 4 ? ARM::tSTRi
7047                        : StSize == 2 ? ARM::tSTRHi
7048                                      : StSize == 1 ? ARM::tSTRBi : 0;
7049   if (IsThumb2)
7050     return StSize == 4 ? ARM::t2STR_POST
7051                        : StSize == 2 ? ARM::t2STRH_POST
7052                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
7053   return StSize == 4 ? ARM::STR_POST_IMM
7054                      : StSize == 2 ? ARM::STRH_POST
7055                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7056 }
7057
7058 /// Emit a post-increment load operation with given size. The instructions
7059 /// will be added to BB at Pos.
7060 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7061                        const TargetInstrInfo *TII, DebugLoc dl,
7062                        unsigned LdSize, unsigned Data, unsigned AddrIn,
7063                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7064   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7065   assert(LdOpc != 0 && "Should have a load opcode");
7066   if (LdSize >= 8) {
7067     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7068                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7069                        .addImm(0));
7070   } else if (IsThumb1) {
7071     // load + update AddrIn
7072     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7073                        .addReg(AddrIn).addImm(0));
7074     MachineInstrBuilder MIB =
7075         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7076     MIB = AddDefaultT1CC(MIB);
7077     MIB.addReg(AddrIn).addImm(LdSize);
7078     AddDefaultPred(MIB);
7079   } else if (IsThumb2) {
7080     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7081                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7082                        .addImm(LdSize));
7083   } else { // arm
7084     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7085                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7086                        .addReg(0).addImm(LdSize));
7087   }
7088 }
7089
7090 /// Emit a post-increment store operation with given size. The instructions
7091 /// will be added to BB at Pos.
7092 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7093                        const TargetInstrInfo *TII, DebugLoc dl,
7094                        unsigned StSize, unsigned Data, unsigned AddrIn,
7095                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7096   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7097   assert(StOpc != 0 && "Should have a store opcode");
7098   if (StSize >= 8) {
7099     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7100                        .addReg(AddrIn).addImm(0).addReg(Data));
7101   } else if (IsThumb1) {
7102     // store + update AddrIn
7103     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7104                        .addReg(AddrIn).addImm(0));
7105     MachineInstrBuilder MIB =
7106         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7107     MIB = AddDefaultT1CC(MIB);
7108     MIB.addReg(AddrIn).addImm(StSize);
7109     AddDefaultPred(MIB);
7110   } else if (IsThumb2) {
7111     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7112                        .addReg(Data).addReg(AddrIn).addImm(StSize));
7113   } else { // arm
7114     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7115                        .addReg(Data).addReg(AddrIn).addReg(0)
7116                        .addImm(StSize));
7117   }
7118 }
7119
7120 MachineBasicBlock *
7121 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7122                                    MachineBasicBlock *BB) const {
7123   // This pseudo instruction has 3 operands: dst, src, size
7124   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7125   // Otherwise, we will generate unrolled scalar copies.
7126   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7127   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7128   MachineFunction::iterator It = BB;
7129   ++It;
7130
7131   unsigned dest = MI->getOperand(0).getReg();
7132   unsigned src = MI->getOperand(1).getReg();
7133   unsigned SizeVal = MI->getOperand(2).getImm();
7134   unsigned Align = MI->getOperand(3).getImm();
7135   DebugLoc dl = MI->getDebugLoc();
7136
7137   MachineFunction *MF = BB->getParent();
7138   MachineRegisterInfo &MRI = MF->getRegInfo();
7139   unsigned UnitSize = 0;
7140   const TargetRegisterClass *TRC = nullptr;
7141   const TargetRegisterClass *VecTRC = nullptr;
7142
7143   bool IsThumb1 = Subtarget->isThumb1Only();
7144   bool IsThumb2 = Subtarget->isThumb2();
7145
7146   if (Align & 1) {
7147     UnitSize = 1;
7148   } else if (Align & 2) {
7149     UnitSize = 2;
7150   } else {
7151     // Check whether we can use NEON instructions.
7152     if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
7153         Subtarget->hasNEON()) {
7154       if ((Align % 16 == 0) && SizeVal >= 16)
7155         UnitSize = 16;
7156       else if ((Align % 8 == 0) && SizeVal >= 8)
7157         UnitSize = 8;
7158     }
7159     // Can't use NEON instructions.
7160     if (UnitSize == 0)
7161       UnitSize = 4;
7162   }
7163
7164   // Select the correct opcode and register class for unit size load/store
7165   bool IsNeon = UnitSize >= 8;
7166   TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
7167   if (IsNeon)
7168     VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
7169                             : UnitSize == 8 ? &ARM::DPRRegClass
7170                                             : nullptr;
7171
7172   unsigned BytesLeft = SizeVal % UnitSize;
7173   unsigned LoopSize = SizeVal - BytesLeft;
7174
7175   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7176     // Use LDR and STR to copy.
7177     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7178     // [destOut] = STR_POST(scratch, destIn, UnitSize)
7179     unsigned srcIn = src;
7180     unsigned destIn = dest;
7181     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7182       unsigned srcOut = MRI.createVirtualRegister(TRC);
7183       unsigned destOut = MRI.createVirtualRegister(TRC);
7184       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7185       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7186                  IsThumb1, IsThumb2);
7187       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7188                  IsThumb1, IsThumb2);
7189       srcIn = srcOut;
7190       destIn = destOut;
7191     }
7192
7193     // Handle the leftover bytes with LDRB and STRB.
7194     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7195     // [destOut] = STRB_POST(scratch, destIn, 1)
7196     for (unsigned i = 0; i < BytesLeft; i++) {
7197       unsigned srcOut = MRI.createVirtualRegister(TRC);
7198       unsigned destOut = MRI.createVirtualRegister(TRC);
7199       unsigned scratch = MRI.createVirtualRegister(TRC);
7200       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7201                  IsThumb1, IsThumb2);
7202       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7203                  IsThumb1, IsThumb2);
7204       srcIn = srcOut;
7205       destIn = destOut;
7206     }
7207     MI->eraseFromParent();   // The instruction is gone now.
7208     return BB;
7209   }
7210
7211   // Expand the pseudo op to a loop.
7212   // thisMBB:
7213   //   ...
7214   //   movw varEnd, # --> with thumb2
7215   //   movt varEnd, #
7216   //   ldrcp varEnd, idx --> without thumb2
7217   //   fallthrough --> loopMBB
7218   // loopMBB:
7219   //   PHI varPhi, varEnd, varLoop
7220   //   PHI srcPhi, src, srcLoop
7221   //   PHI destPhi, dst, destLoop
7222   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7223   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7224   //   subs varLoop, varPhi, #UnitSize
7225   //   bne loopMBB
7226   //   fallthrough --> exitMBB
7227   // exitMBB:
7228   //   epilogue to handle left-over bytes
7229   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7230   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7231   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7232   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7233   MF->insert(It, loopMBB);
7234   MF->insert(It, exitMBB);
7235
7236   // Transfer the remainder of BB and its successor edges to exitMBB.
7237   exitMBB->splice(exitMBB->begin(), BB,
7238                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7239   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7240
7241   // Load an immediate to varEnd.
7242   unsigned varEnd = MRI.createVirtualRegister(TRC);
7243   if (IsThumb2) {
7244     unsigned Vtmp = varEnd;
7245     if ((LoopSize & 0xFFFF0000) != 0)
7246       Vtmp = MRI.createVirtualRegister(TRC);
7247     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp)
7248                        .addImm(LoopSize & 0xFFFF));
7249
7250     if ((LoopSize & 0xFFFF0000) != 0)
7251       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7252                          .addReg(Vtmp).addImm(LoopSize >> 16));
7253   } else {
7254     MachineConstantPool *ConstantPool = MF->getConstantPool();
7255     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7256     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7257
7258     // MachineConstantPool wants an explicit alignment.
7259     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7260     if (Align == 0)
7261       Align = getDataLayout()->getTypeAllocSize(C->getType());
7262     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7263
7264     if (IsThumb1)
7265       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7266           varEnd, RegState::Define).addConstantPoolIndex(Idx));
7267     else
7268       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7269           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7270   }
7271   BB->addSuccessor(loopMBB);
7272
7273   // Generate the loop body:
7274   //   varPhi = PHI(varLoop, varEnd)
7275   //   srcPhi = PHI(srcLoop, src)
7276   //   destPhi = PHI(destLoop, dst)
7277   MachineBasicBlock *entryBB = BB;
7278   BB = loopMBB;
7279   unsigned varLoop = MRI.createVirtualRegister(TRC);
7280   unsigned varPhi = MRI.createVirtualRegister(TRC);
7281   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7282   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7283   unsigned destLoop = MRI.createVirtualRegister(TRC);
7284   unsigned destPhi = MRI.createVirtualRegister(TRC);
7285
7286   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7287     .addReg(varLoop).addMBB(loopMBB)
7288     .addReg(varEnd).addMBB(entryBB);
7289   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7290     .addReg(srcLoop).addMBB(loopMBB)
7291     .addReg(src).addMBB(entryBB);
7292   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7293     .addReg(destLoop).addMBB(loopMBB)
7294     .addReg(dest).addMBB(entryBB);
7295
7296   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7297   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7298   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7299   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7300              IsThumb1, IsThumb2);
7301   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7302              IsThumb1, IsThumb2);
7303
7304   // Decrement loop variable by UnitSize.
7305   if (IsThumb1) {
7306     MachineInstrBuilder MIB =
7307         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7308     MIB = AddDefaultT1CC(MIB);
7309     MIB.addReg(varPhi).addImm(UnitSize);
7310     AddDefaultPred(MIB);
7311   } else {
7312     MachineInstrBuilder MIB =
7313         BuildMI(*BB, BB->end(), dl,
7314                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7315     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7316     MIB->getOperand(5).setReg(ARM::CPSR);
7317     MIB->getOperand(5).setIsDef(true);
7318   }
7319   BuildMI(*BB, BB->end(), dl,
7320           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7321       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7322
7323   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7324   BB->addSuccessor(loopMBB);
7325   BB->addSuccessor(exitMBB);
7326
7327   // Add epilogue to handle BytesLeft.
7328   BB = exitMBB;
7329   MachineInstr *StartOfExit = exitMBB->begin();
7330
7331   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7332   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7333   unsigned srcIn = srcLoop;
7334   unsigned destIn = destLoop;
7335   for (unsigned i = 0; i < BytesLeft; i++) {
7336     unsigned srcOut = MRI.createVirtualRegister(TRC);
7337     unsigned destOut = MRI.createVirtualRegister(TRC);
7338     unsigned scratch = MRI.createVirtualRegister(TRC);
7339     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7340                IsThumb1, IsThumb2);
7341     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7342                IsThumb1, IsThumb2);
7343     srcIn = srcOut;
7344     destIn = destOut;
7345   }
7346
7347   MI->eraseFromParent();   // The instruction is gone now.
7348   return BB;
7349 }
7350
7351 MachineBasicBlock *
7352 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7353                                        MachineBasicBlock *MBB) const {
7354   const TargetMachine &TM = getTargetMachine();
7355   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
7356   DebugLoc DL = MI->getDebugLoc();
7357
7358   assert(Subtarget->isTargetWindows() &&
7359          "__chkstk is only supported on Windows");
7360   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7361
7362   // __chkstk takes the number of words to allocate on the stack in R4, and
7363   // returns the stack adjustment in number of bytes in R4.  This will not
7364   // clober any other registers (other than the obvious lr).
7365   //
7366   // Although, technically, IP should be considered a register which may be
7367   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
7368   // thumb-2 environment, so there is no interworking required.  As a result, we
7369   // do not expect a veneer to be emitted by the linker, clobbering IP.
7370   //
7371   // Each module receives its own copy of __chkstk, so no import thunk is
7372   // required, again, ensuring that IP is not clobbered.
7373   //
7374   // Finally, although some linkers may theoretically provide a trampoline for
7375   // out of range calls (which is quite common due to a 32M range limitation of
7376   // branches for Thumb), we can generate the long-call version via
7377   // -mcmodel=large, alleviating the need for the trampoline which may clobber
7378   // IP.
7379
7380   switch (TM.getCodeModel()) {
7381   case CodeModel::Small:
7382   case CodeModel::Medium:
7383   case CodeModel::Default:
7384   case CodeModel::Kernel:
7385     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7386       .addImm((unsigned)ARMCC::AL).addReg(0)
7387       .addExternalSymbol("__chkstk")
7388       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7389       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7390       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7391     break;
7392   case CodeModel::Large:
7393   case CodeModel::JITDefault: {
7394     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7395     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7396
7397     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7398       .addExternalSymbol("__chkstk");
7399     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7400       .addImm((unsigned)ARMCC::AL).addReg(0)
7401       .addReg(Reg, RegState::Kill)
7402       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7403       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7404       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7405     break;
7406   }
7407   }
7408
7409   AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7410                                       ARM::SP)
7411                               .addReg(ARM::SP).addReg(ARM::R4)));
7412
7413   MI->eraseFromParent();
7414   return MBB;
7415 }
7416
7417 MachineBasicBlock *
7418 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7419                                                MachineBasicBlock *BB) const {
7420   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7421   DebugLoc dl = MI->getDebugLoc();
7422   bool isThumb2 = Subtarget->isThumb2();
7423   switch (MI->getOpcode()) {
7424   default: {
7425     MI->dump();
7426     llvm_unreachable("Unexpected instr type to insert");
7427   }
7428   // The Thumb2 pre-indexed stores have the same MI operands, they just
7429   // define them differently in the .td files from the isel patterns, so
7430   // they need pseudos.
7431   case ARM::t2STR_preidx:
7432     MI->setDesc(TII->get(ARM::t2STR_PRE));
7433     return BB;
7434   case ARM::t2STRB_preidx:
7435     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7436     return BB;
7437   case ARM::t2STRH_preidx:
7438     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7439     return BB;
7440
7441   case ARM::STRi_preidx:
7442   case ARM::STRBi_preidx: {
7443     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7444       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7445     // Decode the offset.
7446     unsigned Offset = MI->getOperand(4).getImm();
7447     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7448     Offset = ARM_AM::getAM2Offset(Offset);
7449     if (isSub)
7450       Offset = -Offset;
7451
7452     MachineMemOperand *MMO = *MI->memoperands_begin();
7453     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7454       .addOperand(MI->getOperand(0))  // Rn_wb
7455       .addOperand(MI->getOperand(1))  // Rt
7456       .addOperand(MI->getOperand(2))  // Rn
7457       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7458       .addOperand(MI->getOperand(5))  // pred
7459       .addOperand(MI->getOperand(6))
7460       .addMemOperand(MMO);
7461     MI->eraseFromParent();
7462     return BB;
7463   }
7464   case ARM::STRr_preidx:
7465   case ARM::STRBr_preidx:
7466   case ARM::STRH_preidx: {
7467     unsigned NewOpc;
7468     switch (MI->getOpcode()) {
7469     default: llvm_unreachable("unexpected opcode!");
7470     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7471     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7472     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7473     }
7474     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7475     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7476       MIB.addOperand(MI->getOperand(i));
7477     MI->eraseFromParent();
7478     return BB;
7479   }
7480
7481   case ARM::tMOVCCr_pseudo: {
7482     // To "insert" a SELECT_CC instruction, we actually have to insert the
7483     // diamond control-flow pattern.  The incoming instruction knows the
7484     // destination vreg to set, the condition code register to branch on, the
7485     // true/false values to select between, and a branch opcode to use.
7486     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7487     MachineFunction::iterator It = BB;
7488     ++It;
7489
7490     //  thisMBB:
7491     //  ...
7492     //   TrueVal = ...
7493     //   cmpTY ccX, r1, r2
7494     //   bCC copy1MBB
7495     //   fallthrough --> copy0MBB
7496     MachineBasicBlock *thisMBB  = BB;
7497     MachineFunction *F = BB->getParent();
7498     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7499     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7500     F->insert(It, copy0MBB);
7501     F->insert(It, sinkMBB);
7502
7503     // Transfer the remainder of BB and its successor edges to sinkMBB.
7504     sinkMBB->splice(sinkMBB->begin(), BB,
7505                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7506     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7507
7508     BB->addSuccessor(copy0MBB);
7509     BB->addSuccessor(sinkMBB);
7510
7511     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7512       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7513
7514     //  copy0MBB:
7515     //   %FalseValue = ...
7516     //   # fallthrough to sinkMBB
7517     BB = copy0MBB;
7518
7519     // Update machine-CFG edges
7520     BB->addSuccessor(sinkMBB);
7521
7522     //  sinkMBB:
7523     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7524     //  ...
7525     BB = sinkMBB;
7526     BuildMI(*BB, BB->begin(), dl,
7527             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7528       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7529       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7530
7531     MI->eraseFromParent();   // The pseudo instruction is gone now.
7532     return BB;
7533   }
7534
7535   case ARM::BCCi64:
7536   case ARM::BCCZi64: {
7537     // If there is an unconditional branch to the other successor, remove it.
7538     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7539
7540     // Compare both parts that make up the double comparison separately for
7541     // equality.
7542     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7543
7544     unsigned LHS1 = MI->getOperand(1).getReg();
7545     unsigned LHS2 = MI->getOperand(2).getReg();
7546     if (RHSisZero) {
7547       AddDefaultPred(BuildMI(BB, dl,
7548                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7549                      .addReg(LHS1).addImm(0));
7550       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7551         .addReg(LHS2).addImm(0)
7552         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7553     } else {
7554       unsigned RHS1 = MI->getOperand(3).getReg();
7555       unsigned RHS2 = MI->getOperand(4).getReg();
7556       AddDefaultPred(BuildMI(BB, dl,
7557                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7558                      .addReg(LHS1).addReg(RHS1));
7559       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7560         .addReg(LHS2).addReg(RHS2)
7561         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7562     }
7563
7564     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7565     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7566     if (MI->getOperand(0).getImm() == ARMCC::NE)
7567       std::swap(destMBB, exitMBB);
7568
7569     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7570       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7571     if (isThumb2)
7572       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7573     else
7574       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7575
7576     MI->eraseFromParent();   // The pseudo instruction is gone now.
7577     return BB;
7578   }
7579
7580   case ARM::Int_eh_sjlj_setjmp:
7581   case ARM::Int_eh_sjlj_setjmp_nofp:
7582   case ARM::tInt_eh_sjlj_setjmp:
7583   case ARM::t2Int_eh_sjlj_setjmp:
7584   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7585     EmitSjLjDispatchBlock(MI, BB);
7586     return BB;
7587
7588   case ARM::ABS:
7589   case ARM::t2ABS: {
7590     // To insert an ABS instruction, we have to insert the
7591     // diamond control-flow pattern.  The incoming instruction knows the
7592     // source vreg to test against 0, the destination vreg to set,
7593     // the condition code register to branch on, the
7594     // true/false values to select between, and a branch opcode to use.
7595     // It transforms
7596     //     V1 = ABS V0
7597     // into
7598     //     V2 = MOVS V0
7599     //     BCC                      (branch to SinkBB if V0 >= 0)
7600     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7601     //     SinkBB: V1 = PHI(V2, V3)
7602     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7603     MachineFunction::iterator BBI = BB;
7604     ++BBI;
7605     MachineFunction *Fn = BB->getParent();
7606     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7607     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7608     Fn->insert(BBI, RSBBB);
7609     Fn->insert(BBI, SinkBB);
7610
7611     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7612     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7613     bool isThumb2 = Subtarget->isThumb2();
7614     MachineRegisterInfo &MRI = Fn->getRegInfo();
7615     // In Thumb mode S must not be specified if source register is the SP or
7616     // PC and if destination register is the SP, so restrict register class
7617     unsigned NewRsbDstReg =
7618       MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
7619
7620     // Transfer the remainder of BB and its successor edges to sinkMBB.
7621     SinkBB->splice(SinkBB->begin(), BB,
7622                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
7623     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7624
7625     BB->addSuccessor(RSBBB);
7626     BB->addSuccessor(SinkBB);
7627
7628     // fall through to SinkMBB
7629     RSBBB->addSuccessor(SinkBB);
7630
7631     // insert a cmp at the end of BB
7632     AddDefaultPred(BuildMI(BB, dl,
7633                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7634                    .addReg(ABSSrcReg).addImm(0));
7635
7636     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7637     BuildMI(BB, dl,
7638       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7639       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7640
7641     // insert rsbri in RSBBB
7642     // Note: BCC and rsbri will be converted into predicated rsbmi
7643     // by if-conversion pass
7644     BuildMI(*RSBBB, RSBBB->begin(), dl,
7645       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7646       .addReg(ABSSrcReg, RegState::Kill)
7647       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7648
7649     // insert PHI in SinkBB,
7650     // reuse ABSDstReg to not change uses of ABS instruction
7651     BuildMI(*SinkBB, SinkBB->begin(), dl,
7652       TII->get(ARM::PHI), ABSDstReg)
7653       .addReg(NewRsbDstReg).addMBB(RSBBB)
7654       .addReg(ABSSrcReg).addMBB(BB);
7655
7656     // remove ABS instruction
7657     MI->eraseFromParent();
7658
7659     // return last added BB
7660     return SinkBB;
7661   }
7662   case ARM::COPY_STRUCT_BYVAL_I32:
7663     ++NumLoopByVals;
7664     return EmitStructByval(MI, BB);
7665   case ARM::WIN__CHKSTK:
7666     return EmitLowered__chkstk(MI, BB);
7667   }
7668 }
7669
7670 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7671                                                       SDNode *Node) const {
7672   const MCInstrDesc *MCID = &MI->getDesc();
7673   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7674   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7675   // operand is still set to noreg. If needed, set the optional operand's
7676   // register to CPSR, and remove the redundant implicit def.
7677   //
7678   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7679
7680   // Rename pseudo opcodes.
7681   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7682   if (NewOpc) {
7683     const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
7684     MCID = &TII->get(NewOpc);
7685
7686     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7687            "converted opcode should be the same except for cc_out");
7688
7689     MI->setDesc(*MCID);
7690
7691     // Add the optional cc_out operand
7692     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7693   }
7694   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7695
7696   // Any ARM instruction that sets the 's' bit should specify an optional
7697   // "cc_out" operand in the last operand position.
7698   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7699     assert(!NewOpc && "Optional cc_out operand required");
7700     return;
7701   }
7702   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7703   // since we already have an optional CPSR def.
7704   bool definesCPSR = false;
7705   bool deadCPSR = false;
7706   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7707        i != e; ++i) {
7708     const MachineOperand &MO = MI->getOperand(i);
7709     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7710       definesCPSR = true;
7711       if (MO.isDead())
7712         deadCPSR = true;
7713       MI->RemoveOperand(i);
7714       break;
7715     }
7716   }
7717   if (!definesCPSR) {
7718     assert(!NewOpc && "Optional cc_out operand required");
7719     return;
7720   }
7721   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7722   if (deadCPSR) {
7723     assert(!MI->getOperand(ccOutIdx).getReg() &&
7724            "expect uninitialized optional cc_out operand");
7725     return;
7726   }
7727
7728   // If this instruction was defined with an optional CPSR def and its dag node
7729   // had a live implicit CPSR def, then activate the optional CPSR def.
7730   MachineOperand &MO = MI->getOperand(ccOutIdx);
7731   MO.setReg(ARM::CPSR);
7732   MO.setIsDef(true);
7733 }
7734
7735 //===----------------------------------------------------------------------===//
7736 //                           ARM Optimization Hooks
7737 //===----------------------------------------------------------------------===//
7738
7739 // Helper function that checks if N is a null or all ones constant.
7740 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7741   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7742   if (!C)
7743     return false;
7744   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7745 }
7746
7747 // Return true if N is conditionally 0 or all ones.
7748 // Detects these expressions where cc is an i1 value:
7749 //
7750 //   (select cc 0, y)   [AllOnes=0]
7751 //   (select cc y, 0)   [AllOnes=0]
7752 //   (zext cc)          [AllOnes=0]
7753 //   (sext cc)          [AllOnes=0/1]
7754 //   (select cc -1, y)  [AllOnes=1]
7755 //   (select cc y, -1)  [AllOnes=1]
7756 //
7757 // Invert is set when N is the null/all ones constant when CC is false.
7758 // OtherOp is set to the alternative value of N.
7759 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7760                                        SDValue &CC, bool &Invert,
7761                                        SDValue &OtherOp,
7762                                        SelectionDAG &DAG) {
7763   switch (N->getOpcode()) {
7764   default: return false;
7765   case ISD::SELECT: {
7766     CC = N->getOperand(0);
7767     SDValue N1 = N->getOperand(1);
7768     SDValue N2 = N->getOperand(2);
7769     if (isZeroOrAllOnes(N1, AllOnes)) {
7770       Invert = false;
7771       OtherOp = N2;
7772       return true;
7773     }
7774     if (isZeroOrAllOnes(N2, AllOnes)) {
7775       Invert = true;
7776       OtherOp = N1;
7777       return true;
7778     }
7779     return false;
7780   }
7781   case ISD::ZERO_EXTEND:
7782     // (zext cc) can never be the all ones value.
7783     if (AllOnes)
7784       return false;
7785     // Fall through.
7786   case ISD::SIGN_EXTEND: {
7787     EVT VT = N->getValueType(0);
7788     CC = N->getOperand(0);
7789     if (CC.getValueType() != MVT::i1)
7790       return false;
7791     Invert = !AllOnes;
7792     if (AllOnes)
7793       // When looking for an AllOnes constant, N is an sext, and the 'other'
7794       // value is 0.
7795       OtherOp = DAG.getConstant(0, VT);
7796     else if (N->getOpcode() == ISD::ZERO_EXTEND)
7797       // When looking for a 0 constant, N can be zext or sext.
7798       OtherOp = DAG.getConstant(1, VT);
7799     else
7800       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7801     return true;
7802   }
7803   }
7804 }
7805
7806 // Combine a constant select operand into its use:
7807 //
7808 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
7809 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
7810 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
7811 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
7812 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
7813 //
7814 // The transform is rejected if the select doesn't have a constant operand that
7815 // is null, or all ones when AllOnes is set.
7816 //
7817 // Also recognize sext/zext from i1:
7818 //
7819 //   (add (zext cc), x) -> (select cc (add x, 1), x)
7820 //   (add (sext cc), x) -> (select cc (add x, -1), x)
7821 //
7822 // These transformations eventually create predicated instructions.
7823 //
7824 // @param N       The node to transform.
7825 // @param Slct    The N operand that is a select.
7826 // @param OtherOp The other N operand (x above).
7827 // @param DCI     Context.
7828 // @param AllOnes Require the select constant to be all ones instead of null.
7829 // @returns The new node, or SDValue() on failure.
7830 static
7831 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7832                             TargetLowering::DAGCombinerInfo &DCI,
7833                             bool AllOnes = false) {
7834   SelectionDAG &DAG = DCI.DAG;
7835   EVT VT = N->getValueType(0);
7836   SDValue NonConstantVal;
7837   SDValue CCOp;
7838   bool SwapSelectOps;
7839   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7840                                   NonConstantVal, DAG))
7841     return SDValue();
7842
7843   // Slct is now know to be the desired identity constant when CC is true.
7844   SDValue TrueVal = OtherOp;
7845   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7846                                  OtherOp, NonConstantVal);
7847   // Unless SwapSelectOps says CC should be false.
7848   if (SwapSelectOps)
7849     std::swap(TrueVal, FalseVal);
7850
7851   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7852                      CCOp, TrueVal, FalseVal);
7853 }
7854
7855 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7856 static
7857 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7858                                        TargetLowering::DAGCombinerInfo &DCI) {
7859   SDValue N0 = N->getOperand(0);
7860   SDValue N1 = N->getOperand(1);
7861   if (N0.getNode()->hasOneUse()) {
7862     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7863     if (Result.getNode())
7864       return Result;
7865   }
7866   if (N1.getNode()->hasOneUse()) {
7867     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7868     if (Result.getNode())
7869       return Result;
7870   }
7871   return SDValue();
7872 }
7873
7874 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7875 // (only after legalization).
7876 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7877                                  TargetLowering::DAGCombinerInfo &DCI,
7878                                  const ARMSubtarget *Subtarget) {
7879
7880   // Only perform optimization if after legalize, and if NEON is available. We
7881   // also expected both operands to be BUILD_VECTORs.
7882   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7883       || N0.getOpcode() != ISD::BUILD_VECTOR
7884       || N1.getOpcode() != ISD::BUILD_VECTOR)
7885     return SDValue();
7886
7887   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7888   EVT VT = N->getValueType(0);
7889   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7890     return SDValue();
7891
7892   // Check that the vector operands are of the right form.
7893   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7894   // operands, where N is the size of the formed vector.
7895   // Each EXTRACT_VECTOR should have the same input vector and odd or even
7896   // index such that we have a pair wise add pattern.
7897
7898   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7899   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7900     return SDValue();
7901   SDValue Vec = N0->getOperand(0)->getOperand(0);
7902   SDNode *V = Vec.getNode();
7903   unsigned nextIndex = 0;
7904
7905   // For each operands to the ADD which are BUILD_VECTORs,
7906   // check to see if each of their operands are an EXTRACT_VECTOR with
7907   // the same vector and appropriate index.
7908   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7909     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7910         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7911
7912       SDValue ExtVec0 = N0->getOperand(i);
7913       SDValue ExtVec1 = N1->getOperand(i);
7914
7915       // First operand is the vector, verify its the same.
7916       if (V != ExtVec0->getOperand(0).getNode() ||
7917           V != ExtVec1->getOperand(0).getNode())
7918         return SDValue();
7919
7920       // Second is the constant, verify its correct.
7921       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7922       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7923
7924       // For the constant, we want to see all the even or all the odd.
7925       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7926           || C1->getZExtValue() != nextIndex+1)
7927         return SDValue();
7928
7929       // Increment index.
7930       nextIndex+=2;
7931     } else
7932       return SDValue();
7933   }
7934
7935   // Create VPADDL node.
7936   SelectionDAG &DAG = DCI.DAG;
7937   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7938
7939   // Build operand list.
7940   SmallVector<SDValue, 8> Ops;
7941   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7942                                 TLI.getPointerTy()));
7943
7944   // Input is the vector.
7945   Ops.push_back(Vec);
7946
7947   // Get widened type and narrowed type.
7948   MVT widenType;
7949   unsigned numElem = VT.getVectorNumElements();
7950   
7951   EVT inputLaneType = Vec.getValueType().getVectorElementType();
7952   switch (inputLaneType.getSimpleVT().SimpleTy) {
7953     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7954     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7955     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7956     default:
7957       llvm_unreachable("Invalid vector element type for padd optimization.");
7958   }
7959
7960   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), widenType, Ops);
7961   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
7962   return DAG.getNode(ExtOp, SDLoc(N), VT, tmp);
7963 }
7964
7965 static SDValue findMUL_LOHI(SDValue V) {
7966   if (V->getOpcode() == ISD::UMUL_LOHI ||
7967       V->getOpcode() == ISD::SMUL_LOHI)
7968     return V;
7969   return SDValue();
7970 }
7971
7972 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7973                                      TargetLowering::DAGCombinerInfo &DCI,
7974                                      const ARMSubtarget *Subtarget) {
7975
7976   if (Subtarget->isThumb1Only()) return SDValue();
7977
7978   // Only perform the checks after legalize when the pattern is available.
7979   if (DCI.isBeforeLegalize()) return SDValue();
7980
7981   // Look for multiply add opportunities.
7982   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7983   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7984   // a glue link from the first add to the second add.
7985   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7986   // a S/UMLAL instruction.
7987   //          loAdd   UMUL_LOHI
7988   //            \    / :lo    \ :hi
7989   //             \  /          \          [no multiline comment]
7990   //              ADDC         |  hiAdd
7991   //                 \ :glue  /  /
7992   //                  \      /  /
7993   //                    ADDE
7994   //
7995   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7996   SDValue AddcOp0 = AddcNode->getOperand(0);
7997   SDValue AddcOp1 = AddcNode->getOperand(1);
7998
7999   // Check if the two operands are from the same mul_lohi node.
8000   if (AddcOp0.getNode() == AddcOp1.getNode())
8001     return SDValue();
8002
8003   assert(AddcNode->getNumValues() == 2 &&
8004          AddcNode->getValueType(0) == MVT::i32 &&
8005          "Expect ADDC with two result values. First: i32");
8006
8007   // Check that we have a glued ADDC node.
8008   if (AddcNode->getValueType(1) != MVT::Glue)
8009     return SDValue();
8010
8011   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8012   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8013       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8014       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8015       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8016     return SDValue();
8017
8018   // Look for the glued ADDE.
8019   SDNode* AddeNode = AddcNode->getGluedUser();
8020   if (!AddeNode)
8021     return SDValue();
8022
8023   // Make sure it is really an ADDE.
8024   if (AddeNode->getOpcode() != ISD::ADDE)
8025     return SDValue();
8026
8027   assert(AddeNode->getNumOperands() == 3 &&
8028          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8029          "ADDE node has the wrong inputs");
8030
8031   // Check for the triangle shape.
8032   SDValue AddeOp0 = AddeNode->getOperand(0);
8033   SDValue AddeOp1 = AddeNode->getOperand(1);
8034
8035   // Make sure that the ADDE operands are not coming from the same node.
8036   if (AddeOp0.getNode() == AddeOp1.getNode())
8037     return SDValue();
8038
8039   // Find the MUL_LOHI node walking up ADDE's operands.
8040   bool IsLeftOperandMUL = false;
8041   SDValue MULOp = findMUL_LOHI(AddeOp0);
8042   if (MULOp == SDValue())
8043    MULOp = findMUL_LOHI(AddeOp1);
8044   else
8045     IsLeftOperandMUL = true;
8046   if (MULOp == SDValue())
8047     return SDValue();
8048
8049   // Figure out the right opcode.
8050   unsigned Opc = MULOp->getOpcode();
8051   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8052
8053   // Figure out the high and low input values to the MLAL node.
8054   SDValue* HiAdd = nullptr;
8055   SDValue* LoMul = nullptr;
8056   SDValue* LowAdd = nullptr;
8057
8058   // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
8059   if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
8060     return SDValue();
8061
8062   if (IsLeftOperandMUL)
8063     HiAdd = &AddeOp1;
8064   else
8065     HiAdd = &AddeOp0;
8066
8067
8068   // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
8069   // whose low result is fed to the ADDC we are checking.
8070
8071   if (AddcOp0 == MULOp.getValue(0)) {
8072     LoMul = &AddcOp0;
8073     LowAdd = &AddcOp1;
8074   }
8075   if (AddcOp1 == MULOp.getValue(0)) {
8076     LoMul = &AddcOp1;
8077     LowAdd = &AddcOp0;
8078   }
8079
8080   if (!LoMul)
8081     return SDValue();
8082
8083   // Create the merged node.
8084   SelectionDAG &DAG = DCI.DAG;
8085
8086   // Build operand list.
8087   SmallVector<SDValue, 8> Ops;
8088   Ops.push_back(LoMul->getOperand(0));
8089   Ops.push_back(LoMul->getOperand(1));
8090   Ops.push_back(*LowAdd);
8091   Ops.push_back(*HiAdd);
8092
8093   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
8094                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
8095
8096   // Replace the ADDs' nodes uses by the MLA node's values.
8097   SDValue HiMLALResult(MLALNode.getNode(), 1);
8098   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8099
8100   SDValue LoMLALResult(MLALNode.getNode(), 0);
8101   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8102
8103   // Return original node to notify the driver to stop replacing.
8104   SDValue resNode(AddcNode, 0);
8105   return resNode;
8106 }
8107
8108 /// PerformADDCCombine - Target-specific dag combine transform from
8109 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8110 static SDValue PerformADDCCombine(SDNode *N,
8111                                  TargetLowering::DAGCombinerInfo &DCI,
8112                                  const ARMSubtarget *Subtarget) {
8113
8114   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8115
8116 }
8117
8118 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8119 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
8120 /// called with the default operands, and if that fails, with commuted
8121 /// operands.
8122 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8123                                           TargetLowering::DAGCombinerInfo &DCI,
8124                                           const ARMSubtarget *Subtarget){
8125
8126   // Attempt to create vpaddl for this add.
8127   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8128   if (Result.getNode())
8129     return Result;
8130
8131   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8132   if (N0.getNode()->hasOneUse()) {
8133     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8134     if (Result.getNode()) return Result;
8135   }
8136   return SDValue();
8137 }
8138
8139 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8140 ///
8141 static SDValue PerformADDCombine(SDNode *N,
8142                                  TargetLowering::DAGCombinerInfo &DCI,
8143                                  const ARMSubtarget *Subtarget) {
8144   SDValue N0 = N->getOperand(0);
8145   SDValue N1 = N->getOperand(1);
8146
8147   // First try with the default operand order.
8148   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8149   if (Result.getNode())
8150     return Result;
8151
8152   // If that didn't work, try again with the operands commuted.
8153   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8154 }
8155
8156 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8157 ///
8158 static SDValue PerformSUBCombine(SDNode *N,
8159                                  TargetLowering::DAGCombinerInfo &DCI) {
8160   SDValue N0 = N->getOperand(0);
8161   SDValue N1 = N->getOperand(1);
8162
8163   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8164   if (N1.getNode()->hasOneUse()) {
8165     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8166     if (Result.getNode()) return Result;
8167   }
8168
8169   return SDValue();
8170 }
8171
8172 /// PerformVMULCombine
8173 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8174 /// special multiplier accumulator forwarding.
8175 ///   vmul d3, d0, d2
8176 ///   vmla d3, d1, d2
8177 /// is faster than
8178 ///   vadd d3, d0, d1
8179 ///   vmul d3, d3, d2
8180 //  However, for (A + B) * (A + B),
8181 //    vadd d2, d0, d1
8182 //    vmul d3, d0, d2
8183 //    vmla d3, d1, d2
8184 //  is slower than
8185 //    vadd d2, d0, d1
8186 //    vmul d3, d2, d2
8187 static SDValue PerformVMULCombine(SDNode *N,
8188                                   TargetLowering::DAGCombinerInfo &DCI,
8189                                   const ARMSubtarget *Subtarget) {
8190   if (!Subtarget->hasVMLxForwarding())
8191     return SDValue();
8192
8193   SelectionDAG &DAG = DCI.DAG;
8194   SDValue N0 = N->getOperand(0);
8195   SDValue N1 = N->getOperand(1);
8196   unsigned Opcode = N0.getOpcode();
8197   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8198       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8199     Opcode = N1.getOpcode();
8200     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8201         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8202       return SDValue();
8203     std::swap(N0, N1);
8204   }
8205
8206   if (N0 == N1)
8207     return SDValue();
8208
8209   EVT VT = N->getValueType(0);
8210   SDLoc DL(N);
8211   SDValue N00 = N0->getOperand(0);
8212   SDValue N01 = N0->getOperand(1);
8213   return DAG.getNode(Opcode, DL, VT,
8214                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8215                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8216 }
8217
8218 static SDValue PerformMULCombine(SDNode *N,
8219                                  TargetLowering::DAGCombinerInfo &DCI,
8220                                  const ARMSubtarget *Subtarget) {
8221   SelectionDAG &DAG = DCI.DAG;
8222
8223   if (Subtarget->isThumb1Only())
8224     return SDValue();
8225
8226   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8227     return SDValue();
8228
8229   EVT VT = N->getValueType(0);
8230   if (VT.is64BitVector() || VT.is128BitVector())
8231     return PerformVMULCombine(N, DCI, Subtarget);
8232   if (VT != MVT::i32)
8233     return SDValue();
8234
8235   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8236   if (!C)
8237     return SDValue();
8238
8239   int64_t MulAmt = C->getSExtValue();
8240   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8241
8242   ShiftAmt = ShiftAmt & (32 - 1);
8243   SDValue V = N->getOperand(0);
8244   SDLoc DL(N);
8245
8246   SDValue Res;
8247   MulAmt >>= ShiftAmt;
8248
8249   if (MulAmt >= 0) {
8250     if (isPowerOf2_32(MulAmt - 1)) {
8251       // (mul x, 2^N + 1) => (add (shl x, N), x)
8252       Res = DAG.getNode(ISD::ADD, DL, VT,
8253                         V,
8254                         DAG.getNode(ISD::SHL, DL, VT,
8255                                     V,
8256                                     DAG.getConstant(Log2_32(MulAmt - 1),
8257                                                     MVT::i32)));
8258     } else if (isPowerOf2_32(MulAmt + 1)) {
8259       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8260       Res = DAG.getNode(ISD::SUB, DL, VT,
8261                         DAG.getNode(ISD::SHL, DL, VT,
8262                                     V,
8263                                     DAG.getConstant(Log2_32(MulAmt + 1),
8264                                                     MVT::i32)),
8265                         V);
8266     } else
8267       return SDValue();
8268   } else {
8269     uint64_t MulAmtAbs = -MulAmt;
8270     if (isPowerOf2_32(MulAmtAbs + 1)) {
8271       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8272       Res = DAG.getNode(ISD::SUB, DL, VT,
8273                         V,
8274                         DAG.getNode(ISD::SHL, DL, VT,
8275                                     V,
8276                                     DAG.getConstant(Log2_32(MulAmtAbs + 1),
8277                                                     MVT::i32)));
8278     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8279       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8280       Res = DAG.getNode(ISD::ADD, DL, VT,
8281                         V,
8282                         DAG.getNode(ISD::SHL, DL, VT,
8283                                     V,
8284                                     DAG.getConstant(Log2_32(MulAmtAbs-1),
8285                                                     MVT::i32)));
8286       Res = DAG.getNode(ISD::SUB, DL, VT,
8287                         DAG.getConstant(0, MVT::i32),Res);
8288
8289     } else
8290       return SDValue();
8291   }
8292
8293   if (ShiftAmt != 0)
8294     Res = DAG.getNode(ISD::SHL, DL, VT,
8295                       Res, DAG.getConstant(ShiftAmt, MVT::i32));
8296
8297   // Do not add new nodes to DAG combiner worklist.
8298   DCI.CombineTo(N, Res, false);
8299   return SDValue();
8300 }
8301
8302 static SDValue PerformANDCombine(SDNode *N,
8303                                  TargetLowering::DAGCombinerInfo &DCI,
8304                                  const ARMSubtarget *Subtarget) {
8305
8306   // Attempt to use immediate-form VBIC
8307   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8308   SDLoc dl(N);
8309   EVT VT = N->getValueType(0);
8310   SelectionDAG &DAG = DCI.DAG;
8311
8312   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8313     return SDValue();
8314
8315   APInt SplatBits, SplatUndef;
8316   unsigned SplatBitSize;
8317   bool HasAnyUndefs;
8318   if (BVN &&
8319       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8320     if (SplatBitSize <= 64) {
8321       EVT VbicVT;
8322       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8323                                       SplatUndef.getZExtValue(), SplatBitSize,
8324                                       DAG, VbicVT, VT.is128BitVector(),
8325                                       OtherModImm);
8326       if (Val.getNode()) {
8327         SDValue Input =
8328           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8329         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8330         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8331       }
8332     }
8333   }
8334
8335   if (!Subtarget->isThumb1Only()) {
8336     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8337     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8338     if (Result.getNode())
8339       return Result;
8340   }
8341
8342   return SDValue();
8343 }
8344
8345 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8346 static SDValue PerformORCombine(SDNode *N,
8347                                 TargetLowering::DAGCombinerInfo &DCI,
8348                                 const ARMSubtarget *Subtarget) {
8349   // Attempt to use immediate-form VORR
8350   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8351   SDLoc dl(N);
8352   EVT VT = N->getValueType(0);
8353   SelectionDAG &DAG = DCI.DAG;
8354
8355   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8356     return SDValue();
8357
8358   APInt SplatBits, SplatUndef;
8359   unsigned SplatBitSize;
8360   bool HasAnyUndefs;
8361   if (BVN && Subtarget->hasNEON() &&
8362       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8363     if (SplatBitSize <= 64) {
8364       EVT VorrVT;
8365       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8366                                       SplatUndef.getZExtValue(), SplatBitSize,
8367                                       DAG, VorrVT, VT.is128BitVector(),
8368                                       OtherModImm);
8369       if (Val.getNode()) {
8370         SDValue Input =
8371           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8372         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8373         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8374       }
8375     }
8376   }
8377
8378   if (!Subtarget->isThumb1Only()) {
8379     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8380     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8381     if (Result.getNode())
8382       return Result;
8383   }
8384
8385   // The code below optimizes (or (and X, Y), Z).
8386   // The AND operand needs to have a single user to make these optimizations
8387   // profitable.
8388   SDValue N0 = N->getOperand(0);
8389   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8390     return SDValue();
8391   SDValue N1 = N->getOperand(1);
8392
8393   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8394   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8395       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8396     APInt SplatUndef;
8397     unsigned SplatBitSize;
8398     bool HasAnyUndefs;
8399
8400     APInt SplatBits0, SplatBits1;
8401     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8402     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8403     // Ensure that the second operand of both ands are constants
8404     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8405                                       HasAnyUndefs) && !HasAnyUndefs) {
8406         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8407                                           HasAnyUndefs) && !HasAnyUndefs) {
8408             // Ensure that the bit width of the constants are the same and that
8409             // the splat arguments are logical inverses as per the pattern we
8410             // are trying to simplify.
8411             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8412                 SplatBits0 == ~SplatBits1) {
8413                 // Canonicalize the vector type to make instruction selection
8414                 // simpler.
8415                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8416                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8417                                              N0->getOperand(1),
8418                                              N0->getOperand(0),
8419                                              N1->getOperand(0));
8420                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8421             }
8422         }
8423     }
8424   }
8425
8426   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8427   // reasonable.
8428
8429   // BFI is only available on V6T2+
8430   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8431     return SDValue();
8432
8433   SDLoc DL(N);
8434   // 1) or (and A, mask), val => ARMbfi A, val, mask
8435   //      iff (val & mask) == val
8436   //
8437   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8438   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8439   //          && mask == ~mask2
8440   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8441   //          && ~mask == mask2
8442   //  (i.e., copy a bitfield value into another bitfield of the same width)
8443
8444   if (VT != MVT::i32)
8445     return SDValue();
8446
8447   SDValue N00 = N0.getOperand(0);
8448
8449   // The value and the mask need to be constants so we can verify this is
8450   // actually a bitfield set. If the mask is 0xffff, we can do better
8451   // via a movt instruction, so don't use BFI in that case.
8452   SDValue MaskOp = N0.getOperand(1);
8453   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8454   if (!MaskC)
8455     return SDValue();
8456   unsigned Mask = MaskC->getZExtValue();
8457   if (Mask == 0xffff)
8458     return SDValue();
8459   SDValue Res;
8460   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8461   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8462   if (N1C) {
8463     unsigned Val = N1C->getZExtValue();
8464     if ((Val & ~Mask) != Val)
8465       return SDValue();
8466
8467     if (ARM::isBitFieldInvertedMask(Mask)) {
8468       Val >>= countTrailingZeros(~Mask);
8469
8470       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8471                         DAG.getConstant(Val, MVT::i32),
8472                         DAG.getConstant(Mask, MVT::i32));
8473
8474       // Do not add new nodes to DAG combiner worklist.
8475       DCI.CombineTo(N, Res, false);
8476       return SDValue();
8477     }
8478   } else if (N1.getOpcode() == ISD::AND) {
8479     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8480     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8481     if (!N11C)
8482       return SDValue();
8483     unsigned Mask2 = N11C->getZExtValue();
8484
8485     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8486     // as is to match.
8487     if (ARM::isBitFieldInvertedMask(Mask) &&
8488         (Mask == ~Mask2)) {
8489       // The pack halfword instruction works better for masks that fit it,
8490       // so use that when it's available.
8491       if (Subtarget->hasT2ExtractPack() &&
8492           (Mask == 0xffff || Mask == 0xffff0000))
8493         return SDValue();
8494       // 2a
8495       unsigned amt = countTrailingZeros(Mask2);
8496       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8497                         DAG.getConstant(amt, MVT::i32));
8498       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8499                         DAG.getConstant(Mask, MVT::i32));
8500       // Do not add new nodes to DAG combiner worklist.
8501       DCI.CombineTo(N, Res, false);
8502       return SDValue();
8503     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8504                (~Mask == Mask2)) {
8505       // The pack halfword instruction works better for masks that fit it,
8506       // so use that when it's available.
8507       if (Subtarget->hasT2ExtractPack() &&
8508           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8509         return SDValue();
8510       // 2b
8511       unsigned lsb = countTrailingZeros(Mask);
8512       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8513                         DAG.getConstant(lsb, MVT::i32));
8514       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8515                         DAG.getConstant(Mask2, MVT::i32));
8516       // Do not add new nodes to DAG combiner worklist.
8517       DCI.CombineTo(N, Res, false);
8518       return SDValue();
8519     }
8520   }
8521
8522   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8523       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8524       ARM::isBitFieldInvertedMask(~Mask)) {
8525     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8526     // where lsb(mask) == #shamt and masked bits of B are known zero.
8527     SDValue ShAmt = N00.getOperand(1);
8528     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8529     unsigned LSB = countTrailingZeros(Mask);
8530     if (ShAmtC != LSB)
8531       return SDValue();
8532
8533     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8534                       DAG.getConstant(~Mask, MVT::i32));
8535
8536     // Do not add new nodes to DAG combiner worklist.
8537     DCI.CombineTo(N, Res, false);
8538   }
8539
8540   return SDValue();
8541 }
8542
8543 static SDValue PerformXORCombine(SDNode *N,
8544                                  TargetLowering::DAGCombinerInfo &DCI,
8545                                  const ARMSubtarget *Subtarget) {
8546   EVT VT = N->getValueType(0);
8547   SelectionDAG &DAG = DCI.DAG;
8548
8549   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8550     return SDValue();
8551
8552   if (!Subtarget->isThumb1Only()) {
8553     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8554     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8555     if (Result.getNode())
8556       return Result;
8557   }
8558
8559   return SDValue();
8560 }
8561
8562 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8563 /// the bits being cleared by the AND are not demanded by the BFI.
8564 static SDValue PerformBFICombine(SDNode *N,
8565                                  TargetLowering::DAGCombinerInfo &DCI) {
8566   SDValue N1 = N->getOperand(1);
8567   if (N1.getOpcode() == ISD::AND) {
8568     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8569     if (!N11C)
8570       return SDValue();
8571     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8572     unsigned LSB = countTrailingZeros(~InvMask);
8573     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8574     assert(Width <
8575                static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
8576            "undefined behavior");
8577     unsigned Mask = (1u << Width) - 1;
8578     unsigned Mask2 = N11C->getZExtValue();
8579     if ((Mask & (~Mask2)) == 0)
8580       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8581                              N->getOperand(0), N1.getOperand(0),
8582                              N->getOperand(2));
8583   }
8584   return SDValue();
8585 }
8586
8587 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8588 /// ARMISD::VMOVRRD.
8589 static SDValue PerformVMOVRRDCombine(SDNode *N,
8590                                      TargetLowering::DAGCombinerInfo &DCI,
8591                                      const ARMSubtarget *Subtarget) {
8592   // vmovrrd(vmovdrr x, y) -> x,y
8593   SDValue InDouble = N->getOperand(0);
8594   if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
8595     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8596
8597   // vmovrrd(load f64) -> (load i32), (load i32)
8598   SDNode *InNode = InDouble.getNode();
8599   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8600       InNode->getValueType(0) == MVT::f64 &&
8601       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8602       !cast<LoadSDNode>(InNode)->isVolatile()) {
8603     // TODO: Should this be done for non-FrameIndex operands?
8604     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8605
8606     SelectionDAG &DAG = DCI.DAG;
8607     SDLoc DL(LD);
8608     SDValue BasePtr = LD->getBasePtr();
8609     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8610                                  LD->getPointerInfo(), LD->isVolatile(),
8611                                  LD->isNonTemporal(), LD->isInvariant(),
8612                                  LD->getAlignment());
8613
8614     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8615                                     DAG.getConstant(4, MVT::i32));
8616     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8617                                  LD->getPointerInfo(), LD->isVolatile(),
8618                                  LD->isNonTemporal(), LD->isInvariant(),
8619                                  std::min(4U, LD->getAlignment() / 2));
8620
8621     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8622     if (DCI.DAG.getTargetLoweringInfo().isBigEndian())
8623       std::swap (NewLD1, NewLD2);
8624     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8625     return Result;
8626   }
8627
8628   return SDValue();
8629 }
8630
8631 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8632 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8633 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8634   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8635   SDValue Op0 = N->getOperand(0);
8636   SDValue Op1 = N->getOperand(1);
8637   if (Op0.getOpcode() == ISD::BITCAST)
8638     Op0 = Op0.getOperand(0);
8639   if (Op1.getOpcode() == ISD::BITCAST)
8640     Op1 = Op1.getOperand(0);
8641   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8642       Op0.getNode() == Op1.getNode() &&
8643       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8644     return DAG.getNode(ISD::BITCAST, SDLoc(N),
8645                        N->getValueType(0), Op0.getOperand(0));
8646   return SDValue();
8647 }
8648
8649 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8650 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8651 /// i64 vector to have f64 elements, since the value can then be loaded
8652 /// directly into a VFP register.
8653 static bool hasNormalLoadOperand(SDNode *N) {
8654   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8655   for (unsigned i = 0; i < NumElts; ++i) {
8656     SDNode *Elt = N->getOperand(i).getNode();
8657     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8658       return true;
8659   }
8660   return false;
8661 }
8662
8663 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8664 /// ISD::BUILD_VECTOR.
8665 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8666                                           TargetLowering::DAGCombinerInfo &DCI,
8667                                           const ARMSubtarget *Subtarget) {
8668   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8669   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
8670   // into a pair of GPRs, which is fine when the value is used as a scalar,
8671   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8672   SelectionDAG &DAG = DCI.DAG;
8673   if (N->getNumOperands() == 2) {
8674     SDValue RV = PerformVMOVDRRCombine(N, DAG);
8675     if (RV.getNode())
8676       return RV;
8677   }
8678
8679   // Load i64 elements as f64 values so that type legalization does not split
8680   // them up into i32 values.
8681   EVT VT = N->getValueType(0);
8682   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8683     return SDValue();
8684   SDLoc dl(N);
8685   SmallVector<SDValue, 8> Ops;
8686   unsigned NumElts = VT.getVectorNumElements();
8687   for (unsigned i = 0; i < NumElts; ++i) {
8688     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8689     Ops.push_back(V);
8690     // Make the DAGCombiner fold the bitcast.
8691     DCI.AddToWorklist(V.getNode());
8692   }
8693   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8694   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8695   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8696 }
8697
8698 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8699 static SDValue
8700 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8701   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8702   // At that time, we may have inserted bitcasts from integer to float.
8703   // If these bitcasts have survived DAGCombine, change the lowering of this
8704   // BUILD_VECTOR in something more vector friendly, i.e., that does not
8705   // force to use floating point types.
8706
8707   // Make sure we can change the type of the vector.
8708   // This is possible iff:
8709   // 1. The vector is only used in a bitcast to a integer type. I.e.,
8710   //    1.1. Vector is used only once.
8711   //    1.2. Use is a bit convert to an integer type.
8712   // 2. The size of its operands are 32-bits (64-bits are not legal).
8713   EVT VT = N->getValueType(0);
8714   EVT EltVT = VT.getVectorElementType();
8715
8716   // Check 1.1. and 2.
8717   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8718     return SDValue();
8719
8720   // By construction, the input type must be float.
8721   assert(EltVT == MVT::f32 && "Unexpected type!");
8722
8723   // Check 1.2.
8724   SDNode *Use = *N->use_begin();
8725   if (Use->getOpcode() != ISD::BITCAST ||
8726       Use->getValueType(0).isFloatingPoint())
8727     return SDValue();
8728
8729   // Check profitability.
8730   // Model is, if more than half of the relevant operands are bitcast from
8731   // i32, turn the build_vector into a sequence of insert_vector_elt.
8732   // Relevant operands are everything that is not statically
8733   // (i.e., at compile time) bitcasted.
8734   unsigned NumOfBitCastedElts = 0;
8735   unsigned NumElts = VT.getVectorNumElements();
8736   unsigned NumOfRelevantElts = NumElts;
8737   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8738     SDValue Elt = N->getOperand(Idx);
8739     if (Elt->getOpcode() == ISD::BITCAST) {
8740       // Assume only bit cast to i32 will go away.
8741       if (Elt->getOperand(0).getValueType() == MVT::i32)
8742         ++NumOfBitCastedElts;
8743     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8744       // Constants are statically casted, thus do not count them as
8745       // relevant operands.
8746       --NumOfRelevantElts;
8747   }
8748
8749   // Check if more than half of the elements require a non-free bitcast.
8750   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8751     return SDValue();
8752
8753   SelectionDAG &DAG = DCI.DAG;
8754   // Create the new vector type.
8755   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8756   // Check if the type is legal.
8757   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8758   if (!TLI.isTypeLegal(VecVT))
8759     return SDValue();
8760
8761   // Combine:
8762   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8763   // => BITCAST INSERT_VECTOR_ELT
8764   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8765   //                      (BITCAST EN), N.
8766   SDValue Vec = DAG.getUNDEF(VecVT);
8767   SDLoc dl(N);
8768   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8769     SDValue V = N->getOperand(Idx);
8770     if (V.getOpcode() == ISD::UNDEF)
8771       continue;
8772     if (V.getOpcode() == ISD::BITCAST &&
8773         V->getOperand(0).getValueType() == MVT::i32)
8774       // Fold obvious case.
8775       V = V.getOperand(0);
8776     else {
8777       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
8778       // Make the DAGCombiner fold the bitcasts.
8779       DCI.AddToWorklist(V.getNode());
8780     }
8781     SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
8782     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8783   }
8784   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8785   // Make the DAGCombiner fold the bitcasts.
8786   DCI.AddToWorklist(Vec.getNode());
8787   return Vec;
8788 }
8789
8790 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8791 /// ISD::INSERT_VECTOR_ELT.
8792 static SDValue PerformInsertEltCombine(SDNode *N,
8793                                        TargetLowering::DAGCombinerInfo &DCI) {
8794   // Bitcast an i64 load inserted into a vector to f64.
8795   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8796   EVT VT = N->getValueType(0);
8797   SDNode *Elt = N->getOperand(1).getNode();
8798   if (VT.getVectorElementType() != MVT::i64 ||
8799       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8800     return SDValue();
8801
8802   SelectionDAG &DAG = DCI.DAG;
8803   SDLoc dl(N);
8804   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8805                                  VT.getVectorNumElements());
8806   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8807   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8808   // Make the DAGCombiner fold the bitcasts.
8809   DCI.AddToWorklist(Vec.getNode());
8810   DCI.AddToWorklist(V.getNode());
8811   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8812                                Vec, V, N->getOperand(2));
8813   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8814 }
8815
8816 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8817 /// ISD::VECTOR_SHUFFLE.
8818 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8819   // The LLVM shufflevector instruction does not require the shuffle mask
8820   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8821   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
8822   // operands do not match the mask length, they are extended by concatenating
8823   // them with undef vectors.  That is probably the right thing for other
8824   // targets, but for NEON it is better to concatenate two double-register
8825   // size vector operands into a single quad-register size vector.  Do that
8826   // transformation here:
8827   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
8828   //   shuffle(concat(v1, v2), undef)
8829   SDValue Op0 = N->getOperand(0);
8830   SDValue Op1 = N->getOperand(1);
8831   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8832       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8833       Op0.getNumOperands() != 2 ||
8834       Op1.getNumOperands() != 2)
8835     return SDValue();
8836   SDValue Concat0Op1 = Op0.getOperand(1);
8837   SDValue Concat1Op1 = Op1.getOperand(1);
8838   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8839       Concat1Op1.getOpcode() != ISD::UNDEF)
8840     return SDValue();
8841   // Skip the transformation if any of the types are illegal.
8842   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8843   EVT VT = N->getValueType(0);
8844   if (!TLI.isTypeLegal(VT) ||
8845       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8846       !TLI.isTypeLegal(Concat1Op1.getValueType()))
8847     return SDValue();
8848
8849   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
8850                                   Op0.getOperand(0), Op1.getOperand(0));
8851   // Translate the shuffle mask.
8852   SmallVector<int, 16> NewMask;
8853   unsigned NumElts = VT.getVectorNumElements();
8854   unsigned HalfElts = NumElts/2;
8855   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8856   for (unsigned n = 0; n < NumElts; ++n) {
8857     int MaskElt = SVN->getMaskElt(n);
8858     int NewElt = -1;
8859     if (MaskElt < (int)HalfElts)
8860       NewElt = MaskElt;
8861     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8862       NewElt = HalfElts + MaskElt - NumElts;
8863     NewMask.push_back(NewElt);
8864   }
8865   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
8866                               DAG.getUNDEF(VT), NewMask.data());
8867 }
8868
8869 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
8870 /// NEON load/store intrinsics, and generic vector load/stores, to merge
8871 /// base address updates.
8872 /// For generic load/stores, the memory type is assumed to be a vector.
8873 /// The caller is assumed to have checked legality.
8874 static SDValue CombineBaseUpdate(SDNode *N,
8875                                  TargetLowering::DAGCombinerInfo &DCI) {
8876   SelectionDAG &DAG = DCI.DAG;
8877   const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8878                             N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8879   const bool isStore = N->getOpcode() == ISD::STORE;
8880   const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
8881   SDValue Addr = N->getOperand(AddrOpIdx);
8882   MemSDNode *MemN = cast<MemSDNode>(N);
8883
8884   // Search for a use of the address operand that is an increment.
8885   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8886          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8887     SDNode *User = *UI;
8888     if (User->getOpcode() != ISD::ADD ||
8889         UI.getUse().getResNo() != Addr.getResNo())
8890       continue;
8891
8892     // Check that the add is independent of the load/store.  Otherwise, folding
8893     // it would create a cycle.
8894     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8895       continue;
8896
8897     // Find the new opcode for the updating load/store.
8898     bool isLoadOp = true;
8899     bool isLaneOp = false;
8900     unsigned NewOpc = 0;
8901     unsigned NumVecs = 0;
8902     if (isIntrinsic) {
8903       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8904       switch (IntNo) {
8905       default: llvm_unreachable("unexpected intrinsic for Neon base update");
8906       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
8907         NumVecs = 1; break;
8908       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
8909         NumVecs = 2; break;
8910       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
8911         NumVecs = 3; break;
8912       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
8913         NumVecs = 4; break;
8914       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8915         NumVecs = 2; isLaneOp = true; break;
8916       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8917         NumVecs = 3; isLaneOp = true; break;
8918       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8919         NumVecs = 4; isLaneOp = true; break;
8920       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
8921         NumVecs = 1; isLoadOp = false; break;
8922       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
8923         NumVecs = 2; isLoadOp = false; break;
8924       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
8925         NumVecs = 3; isLoadOp = false; break;
8926       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
8927         NumVecs = 4; isLoadOp = false; break;
8928       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8929         NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
8930       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8931         NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
8932       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8933         NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
8934       }
8935     } else {
8936       isLaneOp = true;
8937       switch (N->getOpcode()) {
8938       default: llvm_unreachable("unexpected opcode for Neon base update");
8939       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8940       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8941       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8942       case ISD::LOAD:       NewOpc = ARMISD::VLD1_UPD;
8943         NumVecs = 1; isLaneOp = false; break;
8944       case ISD::STORE:      NewOpc = ARMISD::VST1_UPD;
8945         NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
8946       }
8947     }
8948
8949     // Find the size of memory referenced by the load/store.
8950     EVT VecTy;
8951     if (isLoadOp) {
8952       VecTy = N->getValueType(0);
8953     } else if (isIntrinsic) {
8954       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8955     } else {
8956       assert(isStore && "Node has to be a load, a store, or an intrinsic!");
8957       VecTy = N->getOperand(1).getValueType();
8958     }
8959
8960     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8961     if (isLaneOp)
8962       NumBytes /= VecTy.getVectorNumElements();
8963
8964     // If the increment is a constant, it must match the memory ref size.
8965     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8966     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8967       uint64_t IncVal = CInc->getZExtValue();
8968       if (IncVal != NumBytes)
8969         continue;
8970     } else if (NumBytes >= 3 * 16) {
8971       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8972       // separate instructions that make it harder to use a non-constant update.
8973       continue;
8974     }
8975
8976     // OK, we found an ADD we can fold into the base update.
8977     // Now, create a _UPD node, taking care of not breaking alignment.
8978
8979     EVT AlignedVecTy = VecTy;
8980     unsigned Alignment = MemN->getAlignment();
8981
8982     // If this is a less-than-standard-aligned load/store, change the type to
8983     // match the standard alignment.
8984     // The alignment is overlooked when selecting _UPD variants; and it's
8985     // easier to introduce bitcasts here than fix that.
8986     // There are 3 ways to get to this base-update combine:
8987     // - intrinsics: they are assumed to be properly aligned (to the standard
8988     //   alignment of the memory type), so we don't need to do anything.
8989     // - ARMISD::VLDx nodes: they are only generated from the aforementioned
8990     //   intrinsics, so, likewise, there's nothing to do.
8991     // - generic load/store instructions: the alignment is specified as an
8992     //   explicit operand, rather than implicitly as the standard alignment
8993     //   of the memory type (like the intrisics).  We need to change the
8994     //   memory type to match the explicit alignment.  That way, we don't
8995     //   generate non-standard-aligned ARMISD::VLDx nodes.
8996     if (isa<LSBaseSDNode>(N)) {
8997       if (Alignment == 0)
8998         Alignment = 1;
8999       if (Alignment < VecTy.getScalarSizeInBits() / 8) {
9000         MVT EltTy = MVT::getIntegerVT(Alignment * 8);
9001         assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
9002         assert(!isLaneOp && "Unexpected generic load/store lane.");
9003         unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
9004         AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
9005       }
9006       // Don't set an explicit alignment on regular load/stores that we want
9007       // to transform to VLD/VST 1_UPD nodes.
9008       // This matches the behavior of regular load/stores, which only get an
9009       // explicit alignment if the MMO alignment is larger than the standard
9010       // alignment of the memory type.
9011       // Intrinsics, however, always get an explicit alignment, set to the
9012       // alignment of the MMO.
9013       Alignment = 1;
9014     }
9015
9016     // Create the new updating load/store node.
9017     // First, create an SDVTList for the new updating node's results.
9018     EVT Tys[6];
9019     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
9020     unsigned n;
9021     for (n = 0; n < NumResultVecs; ++n)
9022       Tys[n] = AlignedVecTy;
9023     Tys[n++] = MVT::i32;
9024     Tys[n] = MVT::Other;
9025     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
9026
9027     // Then, gather the new node's operands.
9028     SmallVector<SDValue, 8> Ops;
9029     Ops.push_back(N->getOperand(0)); // incoming chain
9030     Ops.push_back(N->getOperand(AddrOpIdx));
9031     Ops.push_back(Inc);
9032
9033     if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
9034       // Try to match the intrinsic's signature
9035       Ops.push_back(StN->getValue());
9036     } else {
9037       // Loads (and of course intrinsics) match the intrinsics' signature,
9038       // so just add all but the alignment operand.
9039       for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
9040         Ops.push_back(N->getOperand(i));
9041     }
9042
9043     // For all node types, the alignment operand is always the last one.
9044     Ops.push_back(DAG.getConstant(Alignment, MVT::i32));
9045
9046     // If this is a non-standard-aligned STORE, the penultimate operand is the
9047     // stored value.  Bitcast it to the aligned type.
9048     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
9049       SDValue &StVal = Ops[Ops.size()-2];
9050       StVal = DAG.getNode(ISD::BITCAST, SDLoc(N), AlignedVecTy, StVal);
9051     }
9052
9053     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
9054                                            Ops, AlignedVecTy,
9055                                            MemN->getMemOperand());
9056
9057     // Update the uses.
9058     SmallVector<SDValue, 5> NewResults;
9059     for (unsigned i = 0; i < NumResultVecs; ++i)
9060       NewResults.push_back(SDValue(UpdN.getNode(), i));
9061
9062     // If this is an non-standard-aligned LOAD, the first result is the loaded
9063     // value.  Bitcast it to the expected result type.
9064     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
9065       SDValue &LdVal = NewResults[0];
9066       LdVal = DAG.getNode(ISD::BITCAST, SDLoc(N), VecTy, LdVal);
9067     }
9068
9069     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9070     DCI.CombineTo(N, NewResults);
9071     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9072
9073     break;
9074   }
9075   return SDValue();
9076 }
9077
9078 static SDValue PerformVLDCombine(SDNode *N,
9079                                  TargetLowering::DAGCombinerInfo &DCI) {
9080   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9081     return SDValue();
9082
9083   return CombineBaseUpdate(N, DCI);
9084 }
9085
9086 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9087 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9088 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
9089 /// return true.
9090 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9091   SelectionDAG &DAG = DCI.DAG;
9092   EVT VT = N->getValueType(0);
9093   // vldN-dup instructions only support 64-bit vectors for N > 1.
9094   if (!VT.is64BitVector())
9095     return false;
9096
9097   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9098   SDNode *VLD = N->getOperand(0).getNode();
9099   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9100     return false;
9101   unsigned NumVecs = 0;
9102   unsigned NewOpc = 0;
9103   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9104   if (IntNo == Intrinsic::arm_neon_vld2lane) {
9105     NumVecs = 2;
9106     NewOpc = ARMISD::VLD2DUP;
9107   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9108     NumVecs = 3;
9109     NewOpc = ARMISD::VLD3DUP;
9110   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9111     NumVecs = 4;
9112     NewOpc = ARMISD::VLD4DUP;
9113   } else {
9114     return false;
9115   }
9116
9117   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9118   // numbers match the load.
9119   unsigned VLDLaneNo =
9120     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9121   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9122        UI != UE; ++UI) {
9123     // Ignore uses of the chain result.
9124     if (UI.getUse().getResNo() == NumVecs)
9125       continue;
9126     SDNode *User = *UI;
9127     if (User->getOpcode() != ARMISD::VDUPLANE ||
9128         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9129       return false;
9130   }
9131
9132   // Create the vldN-dup node.
9133   EVT Tys[5];
9134   unsigned n;
9135   for (n = 0; n < NumVecs; ++n)
9136     Tys[n] = VT;
9137   Tys[n] = MVT::Other;
9138   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9139   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9140   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9141   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9142                                            Ops, VLDMemInt->getMemoryVT(),
9143                                            VLDMemInt->getMemOperand());
9144
9145   // Update the uses.
9146   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9147        UI != UE; ++UI) {
9148     unsigned ResNo = UI.getUse().getResNo();
9149     // Ignore uses of the chain result.
9150     if (ResNo == NumVecs)
9151       continue;
9152     SDNode *User = *UI;
9153     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9154   }
9155
9156   // Now the vldN-lane intrinsic is dead except for its chain result.
9157   // Update uses of the chain.
9158   std::vector<SDValue> VLDDupResults;
9159   for (unsigned n = 0; n < NumVecs; ++n)
9160     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9161   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9162   DCI.CombineTo(VLD, VLDDupResults);
9163
9164   return true;
9165 }
9166
9167 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9168 /// ARMISD::VDUPLANE.
9169 static SDValue PerformVDUPLANECombine(SDNode *N,
9170                                       TargetLowering::DAGCombinerInfo &DCI) {
9171   SDValue Op = N->getOperand(0);
9172
9173   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9174   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9175   if (CombineVLDDUP(N, DCI))
9176     return SDValue(N, 0);
9177
9178   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9179   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9180   while (Op.getOpcode() == ISD::BITCAST)
9181     Op = Op.getOperand(0);
9182   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9183     return SDValue();
9184
9185   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9186   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9187   // The canonical VMOV for a zero vector uses a 32-bit element size.
9188   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9189   unsigned EltBits;
9190   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9191     EltSize = 8;
9192   EVT VT = N->getValueType(0);
9193   if (EltSize > VT.getVectorElementType().getSizeInBits())
9194     return SDValue();
9195
9196   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9197 }
9198
9199 static SDValue PerformLOADCombine(SDNode *N,
9200                                   TargetLowering::DAGCombinerInfo &DCI) {
9201   EVT VT = N->getValueType(0);
9202
9203   // If this is a legal vector load, try to combine it into a VLD1_UPD.
9204   if (ISD::isNormalLoad(N) && VT.isVector() &&
9205       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9206     return CombineBaseUpdate(N, DCI);
9207
9208   return SDValue();
9209 }
9210
9211 /// PerformSTORECombine - Target-specific dag combine xforms for
9212 /// ISD::STORE.
9213 static SDValue PerformSTORECombine(SDNode *N,
9214                                    TargetLowering::DAGCombinerInfo &DCI) {
9215   StoreSDNode *St = cast<StoreSDNode>(N);
9216   if (St->isVolatile())
9217     return SDValue();
9218
9219   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
9220   // pack all of the elements in one place.  Next, store to memory in fewer
9221   // chunks.
9222   SDValue StVal = St->getValue();
9223   EVT VT = StVal.getValueType();
9224   if (St->isTruncatingStore() && VT.isVector()) {
9225     SelectionDAG &DAG = DCI.DAG;
9226     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9227     EVT StVT = St->getMemoryVT();
9228     unsigned NumElems = VT.getVectorNumElements();
9229     assert(StVT != VT && "Cannot truncate to the same type");
9230     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
9231     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
9232
9233     // From, To sizes and ElemCount must be pow of two
9234     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
9235
9236     // We are going to use the original vector elt for storing.
9237     // Accumulated smaller vector elements must be a multiple of the store size.
9238     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
9239
9240     unsigned SizeRatio  = FromEltSz / ToEltSz;
9241     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
9242
9243     // Create a type on which we perform the shuffle.
9244     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9245                                      NumElems*SizeRatio);
9246     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9247
9248     SDLoc DL(St);
9249     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9250     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9251     for (unsigned i = 0; i < NumElems; ++i)
9252       ShuffleVec[i] = TLI.isBigEndian() ? (i+1) * SizeRatio - 1 : i * SizeRatio;
9253
9254     // Can't shuffle using an illegal type.
9255     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9256
9257     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9258                                 DAG.getUNDEF(WideVec.getValueType()),
9259                                 ShuffleVec.data());
9260     // At this point all of the data is stored at the bottom of the
9261     // register. We now need to save it to mem.
9262
9263     // Find the largest store unit
9264     MVT StoreType = MVT::i8;
9265     for (MVT Tp : MVT::integer_valuetypes()) {
9266       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9267         StoreType = Tp;
9268     }
9269     // Didn't find a legal store type.
9270     if (!TLI.isTypeLegal(StoreType))
9271       return SDValue();
9272
9273     // Bitcast the original vector into a vector of store-size units
9274     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9275             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9276     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9277     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9278     SmallVector<SDValue, 8> Chains;
9279     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
9280                                         TLI.getPointerTy());
9281     SDValue BasePtr = St->getBasePtr();
9282
9283     // Perform one or more big stores into memory.
9284     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9285     for (unsigned I = 0; I < E; I++) {
9286       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9287                                    StoreType, ShuffWide,
9288                                    DAG.getIntPtrConstant(I));
9289       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9290                                 St->getPointerInfo(), St->isVolatile(),
9291                                 St->isNonTemporal(), St->getAlignment());
9292       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9293                             Increment);
9294       Chains.push_back(Ch);
9295     }
9296     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
9297   }
9298
9299   if (!ISD::isNormalStore(St))
9300     return SDValue();
9301
9302   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9303   // ARM stores of arguments in the same cache line.
9304   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9305       StVal.getNode()->hasOneUse()) {
9306     SelectionDAG  &DAG = DCI.DAG;
9307     bool isBigEndian = DAG.getTargetLoweringInfo().isBigEndian();
9308     SDLoc DL(St);
9309     SDValue BasePtr = St->getBasePtr();
9310     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9311                                   StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
9312                                   BasePtr, St->getPointerInfo(), St->isVolatile(),
9313                                   St->isNonTemporal(), St->getAlignment());
9314
9315     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9316                                     DAG.getConstant(4, MVT::i32));
9317     return DAG.getStore(NewST1.getValue(0), DL,
9318                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
9319                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9320                         St->isNonTemporal(),
9321                         std::min(4U, St->getAlignment() / 2));
9322   }
9323
9324   if (StVal.getValueType() == MVT::i64 &&
9325       StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9326
9327     // Bitcast an i64 store extracted from a vector to f64.
9328     // Otherwise, the i64 value will be legalized to a pair of i32 values.
9329     SelectionDAG &DAG = DCI.DAG;
9330     SDLoc dl(StVal);
9331     SDValue IntVec = StVal.getOperand(0);
9332     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9333                                    IntVec.getValueType().getVectorNumElements());
9334     SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9335     SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9336                                  Vec, StVal.getOperand(1));
9337     dl = SDLoc(N);
9338     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9339     // Make the DAGCombiner fold the bitcasts.
9340     DCI.AddToWorklist(Vec.getNode());
9341     DCI.AddToWorklist(ExtElt.getNode());
9342     DCI.AddToWorklist(V.getNode());
9343     return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9344                         St->getPointerInfo(), St->isVolatile(),
9345                         St->isNonTemporal(), St->getAlignment(),
9346                         St->getAAInfo());
9347   }
9348
9349   // If this is a legal vector store, try to combine it into a VST1_UPD.
9350   if (ISD::isNormalStore(N) && VT.isVector() &&
9351       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9352     return CombineBaseUpdate(N, DCI);
9353
9354   return SDValue();
9355 }
9356
9357 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9358 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9359 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9360 {
9361   integerPart cN;
9362   integerPart c0 = 0;
9363   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9364        I != E; I++) {
9365     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9366     if (!C)
9367       return false;
9368
9369     bool isExact;
9370     APFloat APF = C->getValueAPF();
9371     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9372         != APFloat::opOK || !isExact)
9373       return false;
9374
9375     c0 = (I == 0) ? cN : c0;
9376     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9377       return false;
9378   }
9379   C = c0;
9380   return true;
9381 }
9382
9383 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9384 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9385 /// when the VMUL has a constant operand that is a power of 2.
9386 ///
9387 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9388 ///  vmul.f32        d16, d17, d16
9389 ///  vcvt.s32.f32    d16, d16
9390 /// becomes:
9391 ///  vcvt.s32.f32    d16, d16, #3
9392 static SDValue PerformVCVTCombine(SDNode *N,
9393                                   TargetLowering::DAGCombinerInfo &DCI,
9394                                   const ARMSubtarget *Subtarget) {
9395   SelectionDAG &DAG = DCI.DAG;
9396   SDValue Op = N->getOperand(0);
9397
9398   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9399       Op.getOpcode() != ISD::FMUL)
9400     return SDValue();
9401
9402   uint64_t C;
9403   SDValue N0 = Op->getOperand(0);
9404   SDValue ConstVec = Op->getOperand(1);
9405   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9406
9407   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9408       !isConstVecPow2(ConstVec, isSigned, C))
9409     return SDValue();
9410
9411   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9412   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9413   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9414   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32 ||
9415       NumLanes > 4) {
9416     // These instructions only exist converting from f32 to i32. We can handle
9417     // smaller integers by generating an extra truncate, but larger ones would
9418     // be lossy. We also can't handle more then 4 lanes, since these intructions
9419     // only support v2i32/v4i32 types.
9420     return SDValue();
9421   }
9422
9423   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9424     Intrinsic::arm_neon_vcvtfp2fxu;
9425   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9426                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9427                                  DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9428                                  DAG.getConstant(Log2_64(C), MVT::i32));
9429
9430   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9431     FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9432
9433   return FixConv;
9434 }
9435
9436 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9437 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9438 /// when the VDIV has a constant operand that is a power of 2.
9439 ///
9440 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9441 ///  vcvt.f32.s32    d16, d16
9442 ///  vdiv.f32        d16, d17, d16
9443 /// becomes:
9444 ///  vcvt.f32.s32    d16, d16, #3
9445 static SDValue PerformVDIVCombine(SDNode *N,
9446                                   TargetLowering::DAGCombinerInfo &DCI,
9447                                   const ARMSubtarget *Subtarget) {
9448   SelectionDAG &DAG = DCI.DAG;
9449   SDValue Op = N->getOperand(0);
9450   unsigned OpOpcode = Op.getNode()->getOpcode();
9451
9452   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9453       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9454     return SDValue();
9455
9456   uint64_t C;
9457   SDValue ConstVec = N->getOperand(1);
9458   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9459
9460   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9461       !isConstVecPow2(ConstVec, isSigned, C))
9462     return SDValue();
9463
9464   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9465   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9466   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9467     // These instructions only exist converting from i32 to f32. We can handle
9468     // smaller integers by generating an extra extend, but larger ones would
9469     // be lossy.
9470     return SDValue();
9471   }
9472
9473   SDValue ConvInput = Op.getOperand(0);
9474   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9475   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9476     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9477                             SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9478                             ConvInput);
9479
9480   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9481     Intrinsic::arm_neon_vcvtfxu2fp;
9482   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9483                      Op.getValueType(),
9484                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
9485                      ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9486 }
9487
9488 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9489 /// operand of a vector shift operation, where all the elements of the
9490 /// build_vector must have the same constant integer value.
9491 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9492   // Ignore bit_converts.
9493   while (Op.getOpcode() == ISD::BITCAST)
9494     Op = Op.getOperand(0);
9495   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9496   APInt SplatBits, SplatUndef;
9497   unsigned SplatBitSize;
9498   bool HasAnyUndefs;
9499   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9500                                       HasAnyUndefs, ElementBits) ||
9501       SplatBitSize > ElementBits)
9502     return false;
9503   Cnt = SplatBits.getSExtValue();
9504   return true;
9505 }
9506
9507 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9508 /// operand of a vector shift left operation.  That value must be in the range:
9509 ///   0 <= Value < ElementBits for a left shift; or
9510 ///   0 <= Value <= ElementBits for a long left shift.
9511 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9512   assert(VT.isVector() && "vector shift count is not a vector type");
9513   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9514   if (! getVShiftImm(Op, ElementBits, Cnt))
9515     return false;
9516   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9517 }
9518
9519 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9520 /// operand of a vector shift right operation.  For a shift opcode, the value
9521 /// is positive, but for an intrinsic the value count must be negative. The
9522 /// absolute value must be in the range:
9523 ///   1 <= |Value| <= ElementBits for a right shift; or
9524 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9525 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9526                          int64_t &Cnt) {
9527   assert(VT.isVector() && "vector shift count is not a vector type");
9528   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9529   if (! getVShiftImm(Op, ElementBits, Cnt))
9530     return false;
9531   if (isIntrinsic)
9532     Cnt = -Cnt;
9533   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9534 }
9535
9536 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9537 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9538   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9539   switch (IntNo) {
9540   default:
9541     // Don't do anything for most intrinsics.
9542     break;
9543
9544   // Vector shifts: check for immediate versions and lower them.
9545   // Note: This is done during DAG combining instead of DAG legalizing because
9546   // the build_vectors for 64-bit vector element shift counts are generally
9547   // not legal, and it is hard to see their values after they get legalized to
9548   // loads from a constant pool.
9549   case Intrinsic::arm_neon_vshifts:
9550   case Intrinsic::arm_neon_vshiftu:
9551   case Intrinsic::arm_neon_vrshifts:
9552   case Intrinsic::arm_neon_vrshiftu:
9553   case Intrinsic::arm_neon_vrshiftn:
9554   case Intrinsic::arm_neon_vqshifts:
9555   case Intrinsic::arm_neon_vqshiftu:
9556   case Intrinsic::arm_neon_vqshiftsu:
9557   case Intrinsic::arm_neon_vqshiftns:
9558   case Intrinsic::arm_neon_vqshiftnu:
9559   case Intrinsic::arm_neon_vqshiftnsu:
9560   case Intrinsic::arm_neon_vqrshiftns:
9561   case Intrinsic::arm_neon_vqrshiftnu:
9562   case Intrinsic::arm_neon_vqrshiftnsu: {
9563     EVT VT = N->getOperand(1).getValueType();
9564     int64_t Cnt;
9565     unsigned VShiftOpc = 0;
9566
9567     switch (IntNo) {
9568     case Intrinsic::arm_neon_vshifts:
9569     case Intrinsic::arm_neon_vshiftu:
9570       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9571         VShiftOpc = ARMISD::VSHL;
9572         break;
9573       }
9574       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9575         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9576                      ARMISD::VSHRs : ARMISD::VSHRu);
9577         break;
9578       }
9579       return SDValue();
9580
9581     case Intrinsic::arm_neon_vrshifts:
9582     case Intrinsic::arm_neon_vrshiftu:
9583       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9584         break;
9585       return SDValue();
9586
9587     case Intrinsic::arm_neon_vqshifts:
9588     case Intrinsic::arm_neon_vqshiftu:
9589       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9590         break;
9591       return SDValue();
9592
9593     case Intrinsic::arm_neon_vqshiftsu:
9594       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9595         break;
9596       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9597
9598     case Intrinsic::arm_neon_vrshiftn:
9599     case Intrinsic::arm_neon_vqshiftns:
9600     case Intrinsic::arm_neon_vqshiftnu:
9601     case Intrinsic::arm_neon_vqshiftnsu:
9602     case Intrinsic::arm_neon_vqrshiftns:
9603     case Intrinsic::arm_neon_vqrshiftnu:
9604     case Intrinsic::arm_neon_vqrshiftnsu:
9605       // Narrowing shifts require an immediate right shift.
9606       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9607         break;
9608       llvm_unreachable("invalid shift count for narrowing vector shift "
9609                        "intrinsic");
9610
9611     default:
9612       llvm_unreachable("unhandled vector shift");
9613     }
9614
9615     switch (IntNo) {
9616     case Intrinsic::arm_neon_vshifts:
9617     case Intrinsic::arm_neon_vshiftu:
9618       // Opcode already set above.
9619       break;
9620     case Intrinsic::arm_neon_vrshifts:
9621       VShiftOpc = ARMISD::VRSHRs; break;
9622     case Intrinsic::arm_neon_vrshiftu:
9623       VShiftOpc = ARMISD::VRSHRu; break;
9624     case Intrinsic::arm_neon_vrshiftn:
9625       VShiftOpc = ARMISD::VRSHRN; break;
9626     case Intrinsic::arm_neon_vqshifts:
9627       VShiftOpc = ARMISD::VQSHLs; break;
9628     case Intrinsic::arm_neon_vqshiftu:
9629       VShiftOpc = ARMISD::VQSHLu; break;
9630     case Intrinsic::arm_neon_vqshiftsu:
9631       VShiftOpc = ARMISD::VQSHLsu; break;
9632     case Intrinsic::arm_neon_vqshiftns:
9633       VShiftOpc = ARMISD::VQSHRNs; break;
9634     case Intrinsic::arm_neon_vqshiftnu:
9635       VShiftOpc = ARMISD::VQSHRNu; break;
9636     case Intrinsic::arm_neon_vqshiftnsu:
9637       VShiftOpc = ARMISD::VQSHRNsu; break;
9638     case Intrinsic::arm_neon_vqrshiftns:
9639       VShiftOpc = ARMISD::VQRSHRNs; break;
9640     case Intrinsic::arm_neon_vqrshiftnu:
9641       VShiftOpc = ARMISD::VQRSHRNu; break;
9642     case Intrinsic::arm_neon_vqrshiftnsu:
9643       VShiftOpc = ARMISD::VQRSHRNsu; break;
9644     }
9645
9646     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9647                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9648   }
9649
9650   case Intrinsic::arm_neon_vshiftins: {
9651     EVT VT = N->getOperand(1).getValueType();
9652     int64_t Cnt;
9653     unsigned VShiftOpc = 0;
9654
9655     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9656       VShiftOpc = ARMISD::VSLI;
9657     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9658       VShiftOpc = ARMISD::VSRI;
9659     else {
9660       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9661     }
9662
9663     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9664                        N->getOperand(1), N->getOperand(2),
9665                        DAG.getConstant(Cnt, MVT::i32));
9666   }
9667
9668   case Intrinsic::arm_neon_vqrshifts:
9669   case Intrinsic::arm_neon_vqrshiftu:
9670     // No immediate versions of these to check for.
9671     break;
9672   }
9673
9674   return SDValue();
9675 }
9676
9677 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9678 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9679 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9680 /// vector element shift counts are generally not legal, and it is hard to see
9681 /// their values after they get legalized to loads from a constant pool.
9682 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9683                                    const ARMSubtarget *ST) {
9684   EVT VT = N->getValueType(0);
9685   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9686     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9687     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9688     SDValue N1 = N->getOperand(1);
9689     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9690       SDValue N0 = N->getOperand(0);
9691       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9692           DAG.MaskedValueIsZero(N0.getOperand(0),
9693                                 APInt::getHighBitsSet(32, 16)))
9694         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9695     }
9696   }
9697
9698   // Nothing to be done for scalar shifts.
9699   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9700   if (!VT.isVector() || !TLI.isTypeLegal(VT))
9701     return SDValue();
9702
9703   assert(ST->hasNEON() && "unexpected vector shift");
9704   int64_t Cnt;
9705
9706   switch (N->getOpcode()) {
9707   default: llvm_unreachable("unexpected shift opcode");
9708
9709   case ISD::SHL:
9710     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9711       return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9712                          DAG.getConstant(Cnt, MVT::i32));
9713     break;
9714
9715   case ISD::SRA:
9716   case ISD::SRL:
9717     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9718       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9719                             ARMISD::VSHRs : ARMISD::VSHRu);
9720       return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9721                          DAG.getConstant(Cnt, MVT::i32));
9722     }
9723   }
9724   return SDValue();
9725 }
9726
9727 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9728 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9729 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9730                                     const ARMSubtarget *ST) {
9731   SDValue N0 = N->getOperand(0);
9732
9733   // Check for sign- and zero-extensions of vector extract operations of 8-
9734   // and 16-bit vector elements.  NEON supports these directly.  They are
9735   // handled during DAG combining because type legalization will promote them
9736   // to 32-bit types and it is messy to recognize the operations after that.
9737   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9738     SDValue Vec = N0.getOperand(0);
9739     SDValue Lane = N0.getOperand(1);
9740     EVT VT = N->getValueType(0);
9741     EVT EltVT = N0.getValueType();
9742     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9743
9744     if (VT == MVT::i32 &&
9745         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9746         TLI.isTypeLegal(Vec.getValueType()) &&
9747         isa<ConstantSDNode>(Lane)) {
9748
9749       unsigned Opc = 0;
9750       switch (N->getOpcode()) {
9751       default: llvm_unreachable("unexpected opcode");
9752       case ISD::SIGN_EXTEND:
9753         Opc = ARMISD::VGETLANEs;
9754         break;
9755       case ISD::ZERO_EXTEND:
9756       case ISD::ANY_EXTEND:
9757         Opc = ARMISD::VGETLANEu;
9758         break;
9759       }
9760       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9761     }
9762   }
9763
9764   return SDValue();
9765 }
9766
9767 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9768 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9769 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9770                                        const ARMSubtarget *ST) {
9771   // If the target supports NEON, try to use vmax/vmin instructions for f32
9772   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
9773   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
9774   // a NaN; only do the transformation when it matches that behavior.
9775
9776   // For now only do this when using NEON for FP operations; if using VFP, it
9777   // is not obvious that the benefit outweighs the cost of switching to the
9778   // NEON pipeline.
9779   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9780       N->getValueType(0) != MVT::f32)
9781     return SDValue();
9782
9783   SDValue CondLHS = N->getOperand(0);
9784   SDValue CondRHS = N->getOperand(1);
9785   SDValue LHS = N->getOperand(2);
9786   SDValue RHS = N->getOperand(3);
9787   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9788
9789   unsigned Opcode = 0;
9790   bool IsReversed;
9791   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9792     IsReversed = false; // x CC y ? x : y
9793   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9794     IsReversed = true ; // x CC y ? y : x
9795   } else {
9796     return SDValue();
9797   }
9798
9799   bool IsUnordered;
9800   switch (CC) {
9801   default: break;
9802   case ISD::SETOLT:
9803   case ISD::SETOLE:
9804   case ISD::SETLT:
9805   case ISD::SETLE:
9806   case ISD::SETULT:
9807   case ISD::SETULE:
9808     // If LHS is NaN, an ordered comparison will be false and the result will
9809     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
9810     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9811     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9812     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9813       break;
9814     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9815     // will return -0, so vmin can only be used for unsafe math or if one of
9816     // the operands is known to be nonzero.
9817     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9818         !DAG.getTarget().Options.UnsafeFPMath &&
9819         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9820       break;
9821     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9822     break;
9823
9824   case ISD::SETOGT:
9825   case ISD::SETOGE:
9826   case ISD::SETGT:
9827   case ISD::SETGE:
9828   case ISD::SETUGT:
9829   case ISD::SETUGE:
9830     // If LHS is NaN, an ordered comparison will be false and the result will
9831     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
9832     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9833     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9834     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9835       break;
9836     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9837     // will return +0, so vmax can only be used for unsafe math or if one of
9838     // the operands is known to be nonzero.
9839     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9840         !DAG.getTarget().Options.UnsafeFPMath &&
9841         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9842       break;
9843     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9844     break;
9845   }
9846
9847   if (!Opcode)
9848     return SDValue();
9849   return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9850 }
9851
9852 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9853 SDValue
9854 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9855   SDValue Cmp = N->getOperand(4);
9856   if (Cmp.getOpcode() != ARMISD::CMPZ)
9857     // Only looking at EQ and NE cases.
9858     return SDValue();
9859
9860   EVT VT = N->getValueType(0);
9861   SDLoc dl(N);
9862   SDValue LHS = Cmp.getOperand(0);
9863   SDValue RHS = Cmp.getOperand(1);
9864   SDValue FalseVal = N->getOperand(0);
9865   SDValue TrueVal = N->getOperand(1);
9866   SDValue ARMcc = N->getOperand(2);
9867   ARMCC::CondCodes CC =
9868     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9869
9870   // Simplify
9871   //   mov     r1, r0
9872   //   cmp     r1, x
9873   //   mov     r0, y
9874   //   moveq   r0, x
9875   // to
9876   //   cmp     r0, x
9877   //   movne   r0, y
9878   //
9879   //   mov     r1, r0
9880   //   cmp     r1, x
9881   //   mov     r0, x
9882   //   movne   r0, y
9883   // to
9884   //   cmp     r0, x
9885   //   movne   r0, y
9886   /// FIXME: Turn this into a target neutral optimization?
9887   SDValue Res;
9888   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9889     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9890                       N->getOperand(3), Cmp);
9891   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9892     SDValue ARMcc;
9893     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9894     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9895                       N->getOperand(3), NewCmp);
9896   }
9897
9898   if (Res.getNode()) {
9899     APInt KnownZero, KnownOne;
9900     DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
9901     // Capture demanded bits information that would be otherwise lost.
9902     if (KnownZero == 0xfffffffe)
9903       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9904                         DAG.getValueType(MVT::i1));
9905     else if (KnownZero == 0xffffff00)
9906       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9907                         DAG.getValueType(MVT::i8));
9908     else if (KnownZero == 0xffff0000)
9909       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9910                         DAG.getValueType(MVT::i16));
9911   }
9912
9913   return Res;
9914 }
9915
9916 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9917                                              DAGCombinerInfo &DCI) const {
9918   switch (N->getOpcode()) {
9919   default: break;
9920   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
9921   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
9922   case ISD::SUB:        return PerformSUBCombine(N, DCI);
9923   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
9924   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
9925   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
9926   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
9927   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
9928   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
9929   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9930   case ISD::STORE:      return PerformSTORECombine(N, DCI);
9931   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
9932   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9933   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9934   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9935   case ISD::FP_TO_SINT:
9936   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9937   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
9938   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9939   case ISD::SHL:
9940   case ISD::SRA:
9941   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
9942   case ISD::SIGN_EXTEND:
9943   case ISD::ZERO_EXTEND:
9944   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9945   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9946   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9947   case ISD::LOAD:       return PerformLOADCombine(N, DCI);
9948   case ARMISD::VLD2DUP:
9949   case ARMISD::VLD3DUP:
9950   case ARMISD::VLD4DUP:
9951     return PerformVLDCombine(N, DCI);
9952   case ARMISD::BUILD_VECTOR:
9953     return PerformARMBUILD_VECTORCombine(N, DCI);
9954   case ISD::INTRINSIC_VOID:
9955   case ISD::INTRINSIC_W_CHAIN:
9956     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9957     case Intrinsic::arm_neon_vld1:
9958     case Intrinsic::arm_neon_vld2:
9959     case Intrinsic::arm_neon_vld3:
9960     case Intrinsic::arm_neon_vld4:
9961     case Intrinsic::arm_neon_vld2lane:
9962     case Intrinsic::arm_neon_vld3lane:
9963     case Intrinsic::arm_neon_vld4lane:
9964     case Intrinsic::arm_neon_vst1:
9965     case Intrinsic::arm_neon_vst2:
9966     case Intrinsic::arm_neon_vst3:
9967     case Intrinsic::arm_neon_vst4:
9968     case Intrinsic::arm_neon_vst2lane:
9969     case Intrinsic::arm_neon_vst3lane:
9970     case Intrinsic::arm_neon_vst4lane:
9971       return PerformVLDCombine(N, DCI);
9972     default: break;
9973     }
9974     break;
9975   }
9976   return SDValue();
9977 }
9978
9979 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9980                                                           EVT VT) const {
9981   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9982 }
9983
9984 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
9985                                                        unsigned,
9986                                                        unsigned,
9987                                                        bool *Fast) const {
9988   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9989   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9990
9991   switch (VT.getSimpleVT().SimpleTy) {
9992   default:
9993     return false;
9994   case MVT::i8:
9995   case MVT::i16:
9996   case MVT::i32: {
9997     // Unaligned access can use (for example) LRDB, LRDH, LDR
9998     if (AllowsUnaligned) {
9999       if (Fast)
10000         *Fast = Subtarget->hasV7Ops();
10001       return true;
10002     }
10003     return false;
10004   }
10005   case MVT::f64:
10006   case MVT::v2f64: {
10007     // For any little-endian targets with neon, we can support unaligned ld/st
10008     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10009     // A big-endian target may also explicitly support unaligned accesses
10010     if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
10011       if (Fast)
10012         *Fast = true;
10013       return true;
10014     }
10015     return false;
10016   }
10017   }
10018 }
10019
10020 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10021                        unsigned AlignCheck) {
10022   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10023           (DstAlign == 0 || DstAlign % AlignCheck == 0));
10024 }
10025
10026 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10027                                            unsigned DstAlign, unsigned SrcAlign,
10028                                            bool IsMemset, bool ZeroMemset,
10029                                            bool MemcpyStrSrc,
10030                                            MachineFunction &MF) const {
10031   const Function *F = MF.getFunction();
10032
10033   // See if we can use NEON instructions for this...
10034   if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
10035       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10036     bool Fast;
10037     if (Size >= 16 &&
10038         (memOpAlign(SrcAlign, DstAlign, 16) ||
10039          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
10040       return MVT::v2f64;
10041     } else if (Size >= 8 &&
10042                (memOpAlign(SrcAlign, DstAlign, 8) ||
10043                 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
10044                  Fast))) {
10045       return MVT::f64;
10046     }
10047   }
10048
10049   // Lowering to i32/i16 if the size permits.
10050   if (Size >= 4)
10051     return MVT::i32;
10052   else if (Size >= 2)
10053     return MVT::i16;
10054
10055   // Let the target-independent logic figure it out.
10056   return MVT::Other;
10057 }
10058
10059 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10060   if (Val.getOpcode() != ISD::LOAD)
10061     return false;
10062
10063   EVT VT1 = Val.getValueType();
10064   if (!VT1.isSimple() || !VT1.isInteger() ||
10065       !VT2.isSimple() || !VT2.isInteger())
10066     return false;
10067
10068   switch (VT1.getSimpleVT().SimpleTy) {
10069   default: break;
10070   case MVT::i1:
10071   case MVT::i8:
10072   case MVT::i16:
10073     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10074     return true;
10075   }
10076
10077   return false;
10078 }
10079
10080 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
10081   EVT VT = ExtVal.getValueType();
10082
10083   if (!isTypeLegal(VT))
10084     return false;
10085
10086   // Don't create a loadext if we can fold the extension into a wide/long
10087   // instruction.
10088   // If there's more than one user instruction, the loadext is desirable no
10089   // matter what.  There can be two uses by the same instruction.
10090   if (ExtVal->use_empty() ||
10091       !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
10092     return true;
10093
10094   SDNode *U = *ExtVal->use_begin();
10095   if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
10096        U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
10097     return false;
10098
10099   return true;
10100 }
10101
10102 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10103   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10104     return false;
10105
10106   if (!isTypeLegal(EVT::getEVT(Ty1)))
10107     return false;
10108
10109   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10110
10111   // Assuming the caller doesn't have a zeroext or signext return parameter,
10112   // truncation all the way down to i1 is valid.
10113   return true;
10114 }
10115
10116
10117 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10118   if (V < 0)
10119     return false;
10120
10121   unsigned Scale = 1;
10122   switch (VT.getSimpleVT().SimpleTy) {
10123   default: return false;
10124   case MVT::i1:
10125   case MVT::i8:
10126     // Scale == 1;
10127     break;
10128   case MVT::i16:
10129     // Scale == 2;
10130     Scale = 2;
10131     break;
10132   case MVT::i32:
10133     // Scale == 4;
10134     Scale = 4;
10135     break;
10136   }
10137
10138   if ((V & (Scale - 1)) != 0)
10139     return false;
10140   V /= Scale;
10141   return V == (V & ((1LL << 5) - 1));
10142 }
10143
10144 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10145                                       const ARMSubtarget *Subtarget) {
10146   bool isNeg = false;
10147   if (V < 0) {
10148     isNeg = true;
10149     V = - V;
10150   }
10151
10152   switch (VT.getSimpleVT().SimpleTy) {
10153   default: return false;
10154   case MVT::i1:
10155   case MVT::i8:
10156   case MVT::i16:
10157   case MVT::i32:
10158     // + imm12 or - imm8
10159     if (isNeg)
10160       return V == (V & ((1LL << 8) - 1));
10161     return V == (V & ((1LL << 12) - 1));
10162   case MVT::f32:
10163   case MVT::f64:
10164     // Same as ARM mode. FIXME: NEON?
10165     if (!Subtarget->hasVFP2())
10166       return false;
10167     if ((V & 3) != 0)
10168       return false;
10169     V >>= 2;
10170     return V == (V & ((1LL << 8) - 1));
10171   }
10172 }
10173
10174 /// isLegalAddressImmediate - Return true if the integer value can be used
10175 /// as the offset of the target addressing mode for load / store of the
10176 /// given type.
10177 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10178                                     const ARMSubtarget *Subtarget) {
10179   if (V == 0)
10180     return true;
10181
10182   if (!VT.isSimple())
10183     return false;
10184
10185   if (Subtarget->isThumb1Only())
10186     return isLegalT1AddressImmediate(V, VT);
10187   else if (Subtarget->isThumb2())
10188     return isLegalT2AddressImmediate(V, VT, Subtarget);
10189
10190   // ARM mode.
10191   if (V < 0)
10192     V = - V;
10193   switch (VT.getSimpleVT().SimpleTy) {
10194   default: return false;
10195   case MVT::i1:
10196   case MVT::i8:
10197   case MVT::i32:
10198     // +- imm12
10199     return V == (V & ((1LL << 12) - 1));
10200   case MVT::i16:
10201     // +- imm8
10202     return V == (V & ((1LL << 8) - 1));
10203   case MVT::f32:
10204   case MVT::f64:
10205     if (!Subtarget->hasVFP2()) // FIXME: NEON?
10206       return false;
10207     if ((V & 3) != 0)
10208       return false;
10209     V >>= 2;
10210     return V == (V & ((1LL << 8) - 1));
10211   }
10212 }
10213
10214 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10215                                                       EVT VT) const {
10216   int Scale = AM.Scale;
10217   if (Scale < 0)
10218     return false;
10219
10220   switch (VT.getSimpleVT().SimpleTy) {
10221   default: return false;
10222   case MVT::i1:
10223   case MVT::i8:
10224   case MVT::i16:
10225   case MVT::i32:
10226     if (Scale == 1)
10227       return true;
10228     // r + r << imm
10229     Scale = Scale & ~1;
10230     return Scale == 2 || Scale == 4 || Scale == 8;
10231   case MVT::i64:
10232     // r + r
10233     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10234       return true;
10235     return false;
10236   case MVT::isVoid:
10237     // Note, we allow "void" uses (basically, uses that aren't loads or
10238     // stores), because arm allows folding a scale into many arithmetic
10239     // operations.  This should be made more precise and revisited later.
10240
10241     // Allow r << imm, but the imm has to be a multiple of two.
10242     if (Scale & 1) return false;
10243     return isPowerOf2_32(Scale);
10244   }
10245 }
10246
10247 /// isLegalAddressingMode - Return true if the addressing mode represented
10248 /// by AM is legal for this target, for a load/store of the specified type.
10249 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10250                                               Type *Ty) const {
10251   EVT VT = getValueType(Ty, true);
10252   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10253     return false;
10254
10255   // Can never fold addr of global into load/store.
10256   if (AM.BaseGV)
10257     return false;
10258
10259   switch (AM.Scale) {
10260   case 0:  // no scale reg, must be "r+i" or "r", or "i".
10261     break;
10262   case 1:
10263     if (Subtarget->isThumb1Only())
10264       return false;
10265     // FALL THROUGH.
10266   default:
10267     // ARM doesn't support any R+R*scale+imm addr modes.
10268     if (AM.BaseOffs)
10269       return false;
10270
10271     if (!VT.isSimple())
10272       return false;
10273
10274     if (Subtarget->isThumb2())
10275       return isLegalT2ScaledAddressingMode(AM, VT);
10276
10277     int Scale = AM.Scale;
10278     switch (VT.getSimpleVT().SimpleTy) {
10279     default: return false;
10280     case MVT::i1:
10281     case MVT::i8:
10282     case MVT::i32:
10283       if (Scale < 0) Scale = -Scale;
10284       if (Scale == 1)
10285         return true;
10286       // r + r << imm
10287       return isPowerOf2_32(Scale & ~1);
10288     case MVT::i16:
10289     case MVT::i64:
10290       // r + r
10291       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10292         return true;
10293       return false;
10294
10295     case MVT::isVoid:
10296       // Note, we allow "void" uses (basically, uses that aren't loads or
10297       // stores), because arm allows folding a scale into many arithmetic
10298       // operations.  This should be made more precise and revisited later.
10299
10300       // Allow r << imm, but the imm has to be a multiple of two.
10301       if (Scale & 1) return false;
10302       return isPowerOf2_32(Scale);
10303     }
10304   }
10305   return true;
10306 }
10307
10308 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10309 /// icmp immediate, that is the target has icmp instructions which can compare
10310 /// a register against the immediate without having to materialize the
10311 /// immediate into a register.
10312 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10313   // Thumb2 and ARM modes can use cmn for negative immediates.
10314   if (!Subtarget->isThumb())
10315     return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
10316   if (Subtarget->isThumb2())
10317     return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
10318   // Thumb1 doesn't have cmn, and only 8-bit immediates.
10319   return Imm >= 0 && Imm <= 255;
10320 }
10321
10322 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10323 /// *or sub* immediate, that is the target has add or sub instructions which can
10324 /// add a register with the immediate without having to materialize the
10325 /// immediate into a register.
10326 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10327   // Same encoding for add/sub, just flip the sign.
10328   int64_t AbsImm = llvm::abs64(Imm);
10329   if (!Subtarget->isThumb())
10330     return ARM_AM::getSOImmVal(AbsImm) != -1;
10331   if (Subtarget->isThumb2())
10332     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10333   // Thumb1 only has 8-bit unsigned immediate.
10334   return AbsImm >= 0 && AbsImm <= 255;
10335 }
10336
10337 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10338                                       bool isSEXTLoad, SDValue &Base,
10339                                       SDValue &Offset, bool &isInc,
10340                                       SelectionDAG &DAG) {
10341   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10342     return false;
10343
10344   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10345     // AddressingMode 3
10346     Base = Ptr->getOperand(0);
10347     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10348       int RHSC = (int)RHS->getZExtValue();
10349       if (RHSC < 0 && RHSC > -256) {
10350         assert(Ptr->getOpcode() == ISD::ADD);
10351         isInc = false;
10352         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10353         return true;
10354       }
10355     }
10356     isInc = (Ptr->getOpcode() == ISD::ADD);
10357     Offset = Ptr->getOperand(1);
10358     return true;
10359   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10360     // AddressingMode 2
10361     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10362       int RHSC = (int)RHS->getZExtValue();
10363       if (RHSC < 0 && RHSC > -0x1000) {
10364         assert(Ptr->getOpcode() == ISD::ADD);
10365         isInc = false;
10366         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10367         Base = Ptr->getOperand(0);
10368         return true;
10369       }
10370     }
10371
10372     if (Ptr->getOpcode() == ISD::ADD) {
10373       isInc = true;
10374       ARM_AM::ShiftOpc ShOpcVal=
10375         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10376       if (ShOpcVal != ARM_AM::no_shift) {
10377         Base = Ptr->getOperand(1);
10378         Offset = Ptr->getOperand(0);
10379       } else {
10380         Base = Ptr->getOperand(0);
10381         Offset = Ptr->getOperand(1);
10382       }
10383       return true;
10384     }
10385
10386     isInc = (Ptr->getOpcode() == ISD::ADD);
10387     Base = Ptr->getOperand(0);
10388     Offset = Ptr->getOperand(1);
10389     return true;
10390   }
10391
10392   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10393   return false;
10394 }
10395
10396 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10397                                      bool isSEXTLoad, SDValue &Base,
10398                                      SDValue &Offset, bool &isInc,
10399                                      SelectionDAG &DAG) {
10400   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10401     return false;
10402
10403   Base = Ptr->getOperand(0);
10404   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10405     int RHSC = (int)RHS->getZExtValue();
10406     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10407       assert(Ptr->getOpcode() == ISD::ADD);
10408       isInc = false;
10409       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10410       return true;
10411     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10412       isInc = Ptr->getOpcode() == ISD::ADD;
10413       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10414       return true;
10415     }
10416   }
10417
10418   return false;
10419 }
10420
10421 /// getPreIndexedAddressParts - returns true by value, base pointer and
10422 /// offset pointer and addressing mode by reference if the node's address
10423 /// can be legally represented as pre-indexed load / store address.
10424 bool
10425 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10426                                              SDValue &Offset,
10427                                              ISD::MemIndexedMode &AM,
10428                                              SelectionDAG &DAG) const {
10429   if (Subtarget->isThumb1Only())
10430     return false;
10431
10432   EVT VT;
10433   SDValue Ptr;
10434   bool isSEXTLoad = false;
10435   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10436     Ptr = LD->getBasePtr();
10437     VT  = LD->getMemoryVT();
10438     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10439   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10440     Ptr = ST->getBasePtr();
10441     VT  = ST->getMemoryVT();
10442   } else
10443     return false;
10444
10445   bool isInc;
10446   bool isLegal = false;
10447   if (Subtarget->isThumb2())
10448     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10449                                        Offset, isInc, DAG);
10450   else
10451     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10452                                         Offset, isInc, DAG);
10453   if (!isLegal)
10454     return false;
10455
10456   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10457   return true;
10458 }
10459
10460 /// getPostIndexedAddressParts - returns true by value, base pointer and
10461 /// offset pointer and addressing mode by reference if this node can be
10462 /// combined with a load / store to form a post-indexed load / store.
10463 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10464                                                    SDValue &Base,
10465                                                    SDValue &Offset,
10466                                                    ISD::MemIndexedMode &AM,
10467                                                    SelectionDAG &DAG) const {
10468   if (Subtarget->isThumb1Only())
10469     return false;
10470
10471   EVT VT;
10472   SDValue Ptr;
10473   bool isSEXTLoad = false;
10474   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10475     VT  = LD->getMemoryVT();
10476     Ptr = LD->getBasePtr();
10477     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10478   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10479     VT  = ST->getMemoryVT();
10480     Ptr = ST->getBasePtr();
10481   } else
10482     return false;
10483
10484   bool isInc;
10485   bool isLegal = false;
10486   if (Subtarget->isThumb2())
10487     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10488                                        isInc, DAG);
10489   else
10490     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10491                                         isInc, DAG);
10492   if (!isLegal)
10493     return false;
10494
10495   if (Ptr != Base) {
10496     // Swap base ptr and offset to catch more post-index load / store when
10497     // it's legal. In Thumb2 mode, offset must be an immediate.
10498     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10499         !Subtarget->isThumb2())
10500       std::swap(Base, Offset);
10501
10502     // Post-indexed load / store update the base pointer.
10503     if (Ptr != Base)
10504       return false;
10505   }
10506
10507   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10508   return true;
10509 }
10510
10511 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10512                                                       APInt &KnownZero,
10513                                                       APInt &KnownOne,
10514                                                       const SelectionDAG &DAG,
10515                                                       unsigned Depth) const {
10516   unsigned BitWidth = KnownOne.getBitWidth();
10517   KnownZero = KnownOne = APInt(BitWidth, 0);
10518   switch (Op.getOpcode()) {
10519   default: break;
10520   case ARMISD::ADDC:
10521   case ARMISD::ADDE:
10522   case ARMISD::SUBC:
10523   case ARMISD::SUBE:
10524     // These nodes' second result is a boolean
10525     if (Op.getResNo() == 0)
10526       break;
10527     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10528     break;
10529   case ARMISD::CMOV: {
10530     // Bits are known zero/one if known on the LHS and RHS.
10531     DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10532     if (KnownZero == 0 && KnownOne == 0) return;
10533
10534     APInt KnownZeroRHS, KnownOneRHS;
10535     DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10536     KnownZero &= KnownZeroRHS;
10537     KnownOne  &= KnownOneRHS;
10538     return;
10539   }
10540   case ISD::INTRINSIC_W_CHAIN: {
10541     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10542     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10543     switch (IntID) {
10544     default: return;
10545     case Intrinsic::arm_ldaex:
10546     case Intrinsic::arm_ldrex: {
10547       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10548       unsigned MemBits = VT.getScalarType().getSizeInBits();
10549       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10550       return;
10551     }
10552     }
10553   }
10554   }
10555 }
10556
10557 //===----------------------------------------------------------------------===//
10558 //                           ARM Inline Assembly Support
10559 //===----------------------------------------------------------------------===//
10560
10561 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10562   // Looking for "rev" which is V6+.
10563   if (!Subtarget->hasV6Ops())
10564     return false;
10565
10566   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10567   std::string AsmStr = IA->getAsmString();
10568   SmallVector<StringRef, 4> AsmPieces;
10569   SplitString(AsmStr, AsmPieces, ";\n");
10570
10571   switch (AsmPieces.size()) {
10572   default: return false;
10573   case 1:
10574     AsmStr = AsmPieces[0];
10575     AsmPieces.clear();
10576     SplitString(AsmStr, AsmPieces, " \t,");
10577
10578     // rev $0, $1
10579     if (AsmPieces.size() == 3 &&
10580         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10581         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10582       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10583       if (Ty && Ty->getBitWidth() == 32)
10584         return IntrinsicLowering::LowerToByteSwap(CI);
10585     }
10586     break;
10587   }
10588
10589   return false;
10590 }
10591
10592 /// getConstraintType - Given a constraint letter, return the type of
10593 /// constraint it is for this target.
10594 ARMTargetLowering::ConstraintType
10595 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10596   if (Constraint.size() == 1) {
10597     switch (Constraint[0]) {
10598     default:  break;
10599     case 'l': return C_RegisterClass;
10600     case 'w': return C_RegisterClass;
10601     case 'h': return C_RegisterClass;
10602     case 'x': return C_RegisterClass;
10603     case 't': return C_RegisterClass;
10604     case 'j': return C_Other; // Constant for movw.
10605       // An address with a single base register. Due to the way we
10606       // currently handle addresses it is the same as an 'r' memory constraint.
10607     case 'Q': return C_Memory;
10608     }
10609   } else if (Constraint.size() == 2) {
10610     switch (Constraint[0]) {
10611     default: break;
10612     // All 'U+' constraints are addresses.
10613     case 'U': return C_Memory;
10614     }
10615   }
10616   return TargetLowering::getConstraintType(Constraint);
10617 }
10618
10619 /// Examine constraint type and operand type and determine a weight value.
10620 /// This object must already have been set up with the operand type
10621 /// and the current alternative constraint selected.
10622 TargetLowering::ConstraintWeight
10623 ARMTargetLowering::getSingleConstraintMatchWeight(
10624     AsmOperandInfo &info, const char *constraint) const {
10625   ConstraintWeight weight = CW_Invalid;
10626   Value *CallOperandVal = info.CallOperandVal;
10627     // If we don't have a value, we can't do a match,
10628     // but allow it at the lowest weight.
10629   if (!CallOperandVal)
10630     return CW_Default;
10631   Type *type = CallOperandVal->getType();
10632   // Look at the constraint type.
10633   switch (*constraint) {
10634   default:
10635     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10636     break;
10637   case 'l':
10638     if (type->isIntegerTy()) {
10639       if (Subtarget->isThumb())
10640         weight = CW_SpecificReg;
10641       else
10642         weight = CW_Register;
10643     }
10644     break;
10645   case 'w':
10646     if (type->isFloatingPointTy())
10647       weight = CW_Register;
10648     break;
10649   }
10650   return weight;
10651 }
10652
10653 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10654 RCPair
10655 ARMTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
10656                                                 const std::string &Constraint,
10657                                                 MVT VT) const {
10658   if (Constraint.size() == 1) {
10659     // GCC ARM Constraint Letters
10660     switch (Constraint[0]) {
10661     case 'l': // Low regs or general regs.
10662       if (Subtarget->isThumb())
10663         return RCPair(0U, &ARM::tGPRRegClass);
10664       return RCPair(0U, &ARM::GPRRegClass);
10665     case 'h': // High regs or no regs.
10666       if (Subtarget->isThumb())
10667         return RCPair(0U, &ARM::hGPRRegClass);
10668       break;
10669     case 'r':
10670       if (Subtarget->isThumb1Only())
10671         return RCPair(0U, &ARM::tGPRRegClass);
10672       return RCPair(0U, &ARM::GPRRegClass);
10673     case 'w':
10674       if (VT == MVT::Other)
10675         break;
10676       if (VT == MVT::f32)
10677         return RCPair(0U, &ARM::SPRRegClass);
10678       if (VT.getSizeInBits() == 64)
10679         return RCPair(0U, &ARM::DPRRegClass);
10680       if (VT.getSizeInBits() == 128)
10681         return RCPair(0U, &ARM::QPRRegClass);
10682       break;
10683     case 'x':
10684       if (VT == MVT::Other)
10685         break;
10686       if (VT == MVT::f32)
10687         return RCPair(0U, &ARM::SPR_8RegClass);
10688       if (VT.getSizeInBits() == 64)
10689         return RCPair(0U, &ARM::DPR_8RegClass);
10690       if (VT.getSizeInBits() == 128)
10691         return RCPair(0U, &ARM::QPR_8RegClass);
10692       break;
10693     case 't':
10694       if (VT == MVT::f32)
10695         return RCPair(0U, &ARM::SPRRegClass);
10696       break;
10697     }
10698   }
10699   if (StringRef("{cc}").equals_lower(Constraint))
10700     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10701
10702   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10703 }
10704
10705 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10706 /// vector.  If it is invalid, don't add anything to Ops.
10707 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10708                                                      std::string &Constraint,
10709                                                      std::vector<SDValue>&Ops,
10710                                                      SelectionDAG &DAG) const {
10711   SDValue Result;
10712
10713   // Currently only support length 1 constraints.
10714   if (Constraint.length() != 1) return;
10715
10716   char ConstraintLetter = Constraint[0];
10717   switch (ConstraintLetter) {
10718   default: break;
10719   case 'j':
10720   case 'I': case 'J': case 'K': case 'L':
10721   case 'M': case 'N': case 'O':
10722     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10723     if (!C)
10724       return;
10725
10726     int64_t CVal64 = C->getSExtValue();
10727     int CVal = (int) CVal64;
10728     // None of these constraints allow values larger than 32 bits.  Check
10729     // that the value fits in an int.
10730     if (CVal != CVal64)
10731       return;
10732
10733     switch (ConstraintLetter) {
10734       case 'j':
10735         // Constant suitable for movw, must be between 0 and
10736         // 65535.
10737         if (Subtarget->hasV6T2Ops())
10738           if (CVal >= 0 && CVal <= 65535)
10739             break;
10740         return;
10741       case 'I':
10742         if (Subtarget->isThumb1Only()) {
10743           // This must be a constant between 0 and 255, for ADD
10744           // immediates.
10745           if (CVal >= 0 && CVal <= 255)
10746             break;
10747         } else if (Subtarget->isThumb2()) {
10748           // A constant that can be used as an immediate value in a
10749           // data-processing instruction.
10750           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10751             break;
10752         } else {
10753           // A constant that can be used as an immediate value in a
10754           // data-processing instruction.
10755           if (ARM_AM::getSOImmVal(CVal) != -1)
10756             break;
10757         }
10758         return;
10759
10760       case 'J':
10761         if (Subtarget->isThumb()) {  // FIXME thumb2
10762           // This must be a constant between -255 and -1, for negated ADD
10763           // immediates. This can be used in GCC with an "n" modifier that
10764           // prints the negated value, for use with SUB instructions. It is
10765           // not useful otherwise but is implemented for compatibility.
10766           if (CVal >= -255 && CVal <= -1)
10767             break;
10768         } else {
10769           // This must be a constant between -4095 and 4095. It is not clear
10770           // what this constraint is intended for. Implemented for
10771           // compatibility with GCC.
10772           if (CVal >= -4095 && CVal <= 4095)
10773             break;
10774         }
10775         return;
10776
10777       case 'K':
10778         if (Subtarget->isThumb1Only()) {
10779           // A 32-bit value where only one byte has a nonzero value. Exclude
10780           // zero to match GCC. This constraint is used by GCC internally for
10781           // constants that can be loaded with a move/shift combination.
10782           // It is not useful otherwise but is implemented for compatibility.
10783           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10784             break;
10785         } else if (Subtarget->isThumb2()) {
10786           // A constant whose bitwise inverse can be used as an immediate
10787           // value in a data-processing instruction. This can be used in GCC
10788           // with a "B" modifier that prints the inverted value, for use with
10789           // BIC and MVN instructions. It is not useful otherwise but is
10790           // implemented for compatibility.
10791           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10792             break;
10793         } else {
10794           // A constant whose bitwise inverse can be used as an immediate
10795           // value in a data-processing instruction. This can be used in GCC
10796           // with a "B" modifier that prints the inverted value, for use with
10797           // BIC and MVN instructions. It is not useful otherwise but is
10798           // implemented for compatibility.
10799           if (ARM_AM::getSOImmVal(~CVal) != -1)
10800             break;
10801         }
10802         return;
10803
10804       case 'L':
10805         if (Subtarget->isThumb1Only()) {
10806           // This must be a constant between -7 and 7,
10807           // for 3-operand ADD/SUB immediate instructions.
10808           if (CVal >= -7 && CVal < 7)
10809             break;
10810         } else if (Subtarget->isThumb2()) {
10811           // A constant whose negation can be used as an immediate value in a
10812           // data-processing instruction. This can be used in GCC with an "n"
10813           // modifier that prints the negated value, for use with SUB
10814           // instructions. It is not useful otherwise but is implemented for
10815           // compatibility.
10816           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10817             break;
10818         } else {
10819           // A constant whose negation can be used as an immediate value in a
10820           // data-processing instruction. This can be used in GCC with an "n"
10821           // modifier that prints the negated value, for use with SUB
10822           // instructions. It is not useful otherwise but is implemented for
10823           // compatibility.
10824           if (ARM_AM::getSOImmVal(-CVal) != -1)
10825             break;
10826         }
10827         return;
10828
10829       case 'M':
10830         if (Subtarget->isThumb()) { // FIXME thumb2
10831           // This must be a multiple of 4 between 0 and 1020, for
10832           // ADD sp + immediate.
10833           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10834             break;
10835         } else {
10836           // A power of two or a constant between 0 and 32.  This is used in
10837           // GCC for the shift amount on shifted register operands, but it is
10838           // useful in general for any shift amounts.
10839           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10840             break;
10841         }
10842         return;
10843
10844       case 'N':
10845         if (Subtarget->isThumb()) {  // FIXME thumb2
10846           // This must be a constant between 0 and 31, for shift amounts.
10847           if (CVal >= 0 && CVal <= 31)
10848             break;
10849         }
10850         return;
10851
10852       case 'O':
10853         if (Subtarget->isThumb()) {  // FIXME thumb2
10854           // This must be a multiple of 4 between -508 and 508, for
10855           // ADD/SUB sp = sp + immediate.
10856           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10857             break;
10858         }
10859         return;
10860     }
10861     Result = DAG.getTargetConstant(CVal, Op.getValueType());
10862     break;
10863   }
10864
10865   if (Result.getNode()) {
10866     Ops.push_back(Result);
10867     return;
10868   }
10869   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10870 }
10871
10872 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10873   assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10874   unsigned Opcode = Op->getOpcode();
10875   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10876          "Invalid opcode for Div/Rem lowering");
10877   bool isSigned = (Opcode == ISD::SDIVREM);
10878   EVT VT = Op->getValueType(0);
10879   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10880
10881   RTLIB::Libcall LC;
10882   switch (VT.getSimpleVT().SimpleTy) {
10883   default: llvm_unreachable("Unexpected request for libcall!");
10884   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
10885   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10886   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10887   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10888   }
10889
10890   SDValue InChain = DAG.getEntryNode();
10891
10892   TargetLowering::ArgListTy Args;
10893   TargetLowering::ArgListEntry Entry;
10894   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
10895     EVT ArgVT = Op->getOperand(i).getValueType();
10896     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10897     Entry.Node = Op->getOperand(i);
10898     Entry.Ty = ArgTy;
10899     Entry.isSExt = isSigned;
10900     Entry.isZExt = !isSigned;
10901     Args.push_back(Entry);
10902   }
10903
10904   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
10905                                          getPointerTy());
10906
10907   Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
10908
10909   SDLoc dl(Op);
10910   TargetLowering::CallLoweringInfo CLI(DAG);
10911   CLI.setDebugLoc(dl).setChain(InChain)
10912     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
10913     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
10914
10915   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
10916   return CallInfo.first;
10917 }
10918
10919 SDValue
10920 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
10921   assert(Subtarget->isTargetWindows() && "unsupported target platform");
10922   SDLoc DL(Op);
10923
10924   // Get the inputs.
10925   SDValue Chain = Op.getOperand(0);
10926   SDValue Size  = Op.getOperand(1);
10927
10928   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
10929                               DAG.getConstant(2, MVT::i32));
10930
10931   SDValue Flag;
10932   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
10933   Flag = Chain.getValue(1);
10934
10935   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10936   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
10937
10938   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
10939   Chain = NewSP.getValue(1);
10940
10941   SDValue Ops[2] = { NewSP, Chain };
10942   return DAG.getMergeValues(Ops, DL);
10943 }
10944
10945 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
10946   assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
10947          "Unexpected type for custom-lowering FP_EXTEND");
10948
10949   RTLIB::Libcall LC;
10950   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
10951
10952   SDValue SrcVal = Op.getOperand(0);
10953   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
10954                      /*isSigned*/ false, SDLoc(Op)).first;
10955 }
10956
10957 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
10958   assert(Op.getOperand(0).getValueType() == MVT::f64 &&
10959          Subtarget->isFPOnlySP() &&
10960          "Unexpected type for custom-lowering FP_ROUND");
10961
10962   RTLIB::Libcall LC;
10963   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
10964
10965   SDValue SrcVal = Op.getOperand(0);
10966   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
10967                      /*isSigned*/ false, SDLoc(Op)).first;
10968 }
10969
10970 bool
10971 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10972   // The ARM target isn't yet aware of offsets.
10973   return false;
10974 }
10975
10976 bool ARM::isBitFieldInvertedMask(unsigned v) {
10977   if (v == 0xffffffff)
10978     return false;
10979
10980   // there can be 1's on either or both "outsides", all the "inside"
10981   // bits must be 0's
10982   return isShiftedMask_32(~v);
10983 }
10984
10985 /// isFPImmLegal - Returns true if the target can instruction select the
10986 /// specified FP immediate natively. If false, the legalizer will
10987 /// materialize the FP immediate as a load from a constant pool.
10988 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10989   if (!Subtarget->hasVFP3())
10990     return false;
10991   if (VT == MVT::f32)
10992     return ARM_AM::getFP32Imm(Imm) != -1;
10993   if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
10994     return ARM_AM::getFP64Imm(Imm) != -1;
10995   return false;
10996 }
10997
10998 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10999 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
11000 /// specified in the intrinsic calls.
11001 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11002                                            const CallInst &I,
11003                                            unsigned Intrinsic) const {
11004   switch (Intrinsic) {
11005   case Intrinsic::arm_neon_vld1:
11006   case Intrinsic::arm_neon_vld2:
11007   case Intrinsic::arm_neon_vld3:
11008   case Intrinsic::arm_neon_vld4:
11009   case Intrinsic::arm_neon_vld2lane:
11010   case Intrinsic::arm_neon_vld3lane:
11011   case Intrinsic::arm_neon_vld4lane: {
11012     Info.opc = ISD::INTRINSIC_W_CHAIN;
11013     // Conservatively set memVT to the entire set of vectors loaded.
11014     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
11015     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11016     Info.ptrVal = I.getArgOperand(0);
11017     Info.offset = 0;
11018     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11019     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11020     Info.vol = false; // volatile loads with NEON intrinsics not supported
11021     Info.readMem = true;
11022     Info.writeMem = false;
11023     return true;
11024   }
11025   case Intrinsic::arm_neon_vst1:
11026   case Intrinsic::arm_neon_vst2:
11027   case Intrinsic::arm_neon_vst3:
11028   case Intrinsic::arm_neon_vst4:
11029   case Intrinsic::arm_neon_vst2lane:
11030   case Intrinsic::arm_neon_vst3lane:
11031   case Intrinsic::arm_neon_vst4lane: {
11032     Info.opc = ISD::INTRINSIC_VOID;
11033     // Conservatively set memVT to the entire set of vectors stored.
11034     unsigned NumElts = 0;
11035     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11036       Type *ArgTy = I.getArgOperand(ArgI)->getType();
11037       if (!ArgTy->isVectorTy())
11038         break;
11039       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
11040     }
11041     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11042     Info.ptrVal = I.getArgOperand(0);
11043     Info.offset = 0;
11044     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11045     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11046     Info.vol = false; // volatile stores with NEON intrinsics not supported
11047     Info.readMem = false;
11048     Info.writeMem = true;
11049     return true;
11050   }
11051   case Intrinsic::arm_ldaex:
11052   case Intrinsic::arm_ldrex: {
11053     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11054     Info.opc = ISD::INTRINSIC_W_CHAIN;
11055     Info.memVT = MVT::getVT(PtrTy->getElementType());
11056     Info.ptrVal = I.getArgOperand(0);
11057     Info.offset = 0;
11058     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11059     Info.vol = true;
11060     Info.readMem = true;
11061     Info.writeMem = false;
11062     return true;
11063   }
11064   case Intrinsic::arm_stlex:
11065   case Intrinsic::arm_strex: {
11066     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11067     Info.opc = ISD::INTRINSIC_W_CHAIN;
11068     Info.memVT = MVT::getVT(PtrTy->getElementType());
11069     Info.ptrVal = I.getArgOperand(1);
11070     Info.offset = 0;
11071     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11072     Info.vol = true;
11073     Info.readMem = false;
11074     Info.writeMem = true;
11075     return true;
11076   }
11077   case Intrinsic::arm_stlexd:
11078   case Intrinsic::arm_strexd: {
11079     Info.opc = ISD::INTRINSIC_W_CHAIN;
11080     Info.memVT = MVT::i64;
11081     Info.ptrVal = I.getArgOperand(2);
11082     Info.offset = 0;
11083     Info.align = 8;
11084     Info.vol = true;
11085     Info.readMem = false;
11086     Info.writeMem = true;
11087     return true;
11088   }
11089   case Intrinsic::arm_ldaexd:
11090   case Intrinsic::arm_ldrexd: {
11091     Info.opc = ISD::INTRINSIC_W_CHAIN;
11092     Info.memVT = MVT::i64;
11093     Info.ptrVal = I.getArgOperand(0);
11094     Info.offset = 0;
11095     Info.align = 8;
11096     Info.vol = true;
11097     Info.readMem = true;
11098     Info.writeMem = false;
11099     return true;
11100   }
11101   default:
11102     break;
11103   }
11104
11105   return false;
11106 }
11107
11108 /// \brief Returns true if it is beneficial to convert a load of a constant
11109 /// to just the constant itself.
11110 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11111                                                           Type *Ty) const {
11112   assert(Ty->isIntegerTy());
11113
11114   unsigned Bits = Ty->getPrimitiveSizeInBits();
11115   if (Bits == 0 || Bits > 32)
11116     return false;
11117   return true;
11118 }
11119
11120 bool ARMTargetLowering::hasLoadLinkedStoreConditional() const { return true; }
11121
11122 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
11123                                         ARM_MB::MemBOpt Domain) const {
11124   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11125
11126   // First, if the target has no DMB, see what fallback we can use.
11127   if (!Subtarget->hasDataBarrier()) {
11128     // Some ARMv6 cpus can support data barriers with an mcr instruction.
11129     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
11130     // here.
11131     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
11132       Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
11133       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
11134                         Builder.getInt32(0), Builder.getInt32(7),
11135                         Builder.getInt32(10), Builder.getInt32(5)};
11136       return Builder.CreateCall(MCR, args);
11137     } else {
11138       // Instead of using barriers, atomic accesses on these subtargets use
11139       // libcalls.
11140       llvm_unreachable("makeDMB on a target so old that it has no barriers");
11141     }
11142   } else {
11143     Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
11144     // Only a full system barrier exists in the M-class architectures.
11145     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
11146     Constant *CDomain = Builder.getInt32(Domain);
11147     return Builder.CreateCall(DMB, CDomain);
11148   }
11149 }
11150
11151 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11152 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11153                                          AtomicOrdering Ord, bool IsStore,
11154                                          bool IsLoad) const {
11155   if (!getInsertFencesForAtomic())
11156     return nullptr;
11157
11158   switch (Ord) {
11159   case NotAtomic:
11160   case Unordered:
11161     llvm_unreachable("Invalid fence: unordered/non-atomic");
11162   case Monotonic:
11163   case Acquire:
11164     return nullptr; // Nothing to do
11165   case SequentiallyConsistent:
11166     if (!IsStore)
11167       return nullptr; // Nothing to do
11168     /*FALLTHROUGH*/
11169   case Release:
11170   case AcquireRelease:
11171     if (Subtarget->isSwift())
11172       return makeDMB(Builder, ARM_MB::ISHST);
11173     // FIXME: add a comment with a link to documentation justifying this.
11174     else
11175       return makeDMB(Builder, ARM_MB::ISH);
11176   }
11177   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
11178 }
11179
11180 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11181                                           AtomicOrdering Ord, bool IsStore,
11182                                           bool IsLoad) const {
11183   if (!getInsertFencesForAtomic())
11184     return nullptr;
11185
11186   switch (Ord) {
11187   case NotAtomic:
11188   case Unordered:
11189     llvm_unreachable("Invalid fence: unordered/not-atomic");
11190   case Monotonic:
11191   case Release:
11192     return nullptr; // Nothing to do
11193   case Acquire:
11194   case AcquireRelease:
11195   case SequentiallyConsistent:
11196     return makeDMB(Builder, ARM_MB::ISH);
11197   }
11198   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
11199 }
11200
11201 // Loads and stores less than 64-bits are already atomic; ones above that
11202 // are doomed anyway, so defer to the default libcall and blame the OS when
11203 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11204 // anything for those.
11205 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11206   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11207   return (Size == 64) && !Subtarget->isMClass();
11208 }
11209
11210 // Loads and stores less than 64-bits are already atomic; ones above that
11211 // are doomed anyway, so defer to the default libcall and blame the OS when
11212 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11213 // anything for those.
11214 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
11215 // guarantee, see DDI0406C ARM architecture reference manual,
11216 // sections A8.8.72-74 LDRD)
11217 bool ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11218   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11219   return (Size == 64) && !Subtarget->isMClass();
11220 }
11221
11222 // For the real atomic operations, we have ldrex/strex up to 32 bits,
11223 // and up to 64 bits on the non-M profiles
11224 TargetLoweringBase::AtomicRMWExpansionKind
11225 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11226   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11227   return (Size <= (Subtarget->isMClass() ? 32U : 64U))
11228              ? AtomicRMWExpansionKind::LLSC
11229              : AtomicRMWExpansionKind::None;
11230 }
11231
11232 // This has so far only been implemented for MachO.
11233 bool ARMTargetLowering::useLoadStackGuardNode() const {
11234   return Subtarget->isTargetMachO();
11235 }
11236
11237 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
11238                                                   unsigned &Cost) const {
11239   // If we do not have NEON, vector types are not natively supported.
11240   if (!Subtarget->hasNEON())
11241     return false;
11242
11243   // Floating point values and vector values map to the same register file.
11244   // Therefore, althought we could do a store extract of a vector type, this is
11245   // better to leave at float as we have more freedom in the addressing mode for
11246   // those.
11247   if (VectorTy->isFPOrFPVectorTy())
11248     return false;
11249
11250   // If the index is unknown at compile time, this is very expensive to lower
11251   // and it is not possible to combine the store with the extract.
11252   if (!isa<ConstantInt>(Idx))
11253     return false;
11254
11255   assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
11256   unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
11257   // We can do a store + vector extract on any vector that fits perfectly in a D
11258   // or Q register.
11259   if (BitWidth == 64 || BitWidth == 128) {
11260     Cost = 0;
11261     return true;
11262   }
11263   return false;
11264 }
11265
11266 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11267                                          AtomicOrdering Ord) const {
11268   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11269   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11270   bool IsAcquire = isAtLeastAcquire(Ord);
11271
11272   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
11273   // intrinsic must return {i32, i32} and we have to recombine them into a
11274   // single i64 here.
11275   if (ValTy->getPrimitiveSizeInBits() == 64) {
11276     Intrinsic::ID Int =
11277         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
11278     Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
11279
11280     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11281     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
11282
11283     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11284     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11285     if (!Subtarget->isLittle())
11286       std::swap (Lo, Hi);
11287     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11288     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11289     return Builder.CreateOr(
11290         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
11291   }
11292
11293   Type *Tys[] = { Addr->getType() };
11294   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
11295   Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
11296
11297   return Builder.CreateTruncOrBitCast(
11298       Builder.CreateCall(Ldrex, Addr),
11299       cast<PointerType>(Addr->getType())->getElementType());
11300 }
11301
11302 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
11303                                                Value *Addr,
11304                                                AtomicOrdering Ord) const {
11305   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11306   bool IsRelease = isAtLeastRelease(Ord);
11307
11308   // Since the intrinsics must have legal type, the i64 intrinsics take two
11309   // parameters: "i32, i32". We must marshal Val into the appropriate form
11310   // before the call.
11311   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
11312     Intrinsic::ID Int =
11313         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
11314     Function *Strex = Intrinsic::getDeclaration(M, Int);
11315     Type *Int32Ty = Type::getInt32Ty(M->getContext());
11316
11317     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
11318     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
11319     if (!Subtarget->isLittle())
11320       std::swap (Lo, Hi);
11321     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11322     return Builder.CreateCall3(Strex, Lo, Hi, Addr);
11323   }
11324
11325   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
11326   Type *Tys[] = { Addr->getType() };
11327   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
11328
11329   return Builder.CreateCall2(
11330       Strex, Builder.CreateZExtOrBitCast(
11331                  Val, Strex->getFunctionType()->getParamType(0)),
11332       Addr);
11333 }
11334
11335 enum HABaseType {
11336   HA_UNKNOWN = 0,
11337   HA_FLOAT,
11338   HA_DOUBLE,
11339   HA_VECT64,
11340   HA_VECT128
11341 };
11342
11343 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
11344                                    uint64_t &Members) {
11345   if (const StructType *ST = dyn_cast<StructType>(Ty)) {
11346     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
11347       uint64_t SubMembers = 0;
11348       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
11349         return false;
11350       Members += SubMembers;
11351     }
11352   } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
11353     uint64_t SubMembers = 0;
11354     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
11355       return false;
11356     Members += SubMembers * AT->getNumElements();
11357   } else if (Ty->isFloatTy()) {
11358     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
11359       return false;
11360     Members = 1;
11361     Base = HA_FLOAT;
11362   } else if (Ty->isDoubleTy()) {
11363     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
11364       return false;
11365     Members = 1;
11366     Base = HA_DOUBLE;
11367   } else if (const VectorType *VT = dyn_cast<VectorType>(Ty)) {
11368     Members = 1;
11369     switch (Base) {
11370     case HA_FLOAT:
11371     case HA_DOUBLE:
11372       return false;
11373     case HA_VECT64:
11374       return VT->getBitWidth() == 64;
11375     case HA_VECT128:
11376       return VT->getBitWidth() == 128;
11377     case HA_UNKNOWN:
11378       switch (VT->getBitWidth()) {
11379       case 64:
11380         Base = HA_VECT64;
11381         return true;
11382       case 128:
11383         Base = HA_VECT128;
11384         return true;
11385       default:
11386         return false;
11387       }
11388     }
11389   }
11390
11391   return (Members > 0 && Members <= 4);
11392 }
11393
11394 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
11395 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
11396 /// passing according to AAPCS rules.
11397 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
11398     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11399   if (getEffectiveCallingConv(CallConv, isVarArg) !=
11400       CallingConv::ARM_AAPCS_VFP)
11401     return false;
11402
11403   HABaseType Base = HA_UNKNOWN;
11404   uint64_t Members = 0;
11405   bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
11406   DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
11407
11408   bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
11409   return IsHA || IsIntArray;
11410 }