[ARM] Remove target-specific ITOFP/FPTOI nodes
[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/IntrinsicInst.h"
46 #include "llvm/IR/Type.h"
47 #include "llvm/MC/MCSectionMachO.h"
48 #include "llvm/Support/CommandLine.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Target/TargetOptions.h"
53 #include <utility>
54 using namespace llvm;
55
56 #define DEBUG_TYPE "arm-isel"
57
58 STATISTIC(NumTailCalls, "Number of tail calls");
59 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
60 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
61
62 cl::opt<bool>
63 EnableARMLongCalls("arm-long-calls", cl::Hidden,
64   cl::desc("Generate calls via indirect call instructions"),
65   cl::init(false));
66
67 static cl::opt<bool>
68 ARMInterworking("arm-interworking", cl::Hidden,
69   cl::desc("Enable / disable ARM interworking (for debugging only)"),
70   cl::init(true));
71
72 namespace {
73   class ARMCCState : public CCState {
74   public:
75     ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
76                SmallVectorImpl<CCValAssign> &locs, LLVMContext &C,
77                ParmContext PC)
78         : CCState(CC, isVarArg, MF, locs, C) {
79       assert(((PC == Call) || (PC == Prologue)) &&
80              "ARMCCState users must specify whether their context is call"
81              "or prologue generation.");
82       CallOrPrologue = PC;
83     }
84   };
85 }
86
87 // The APCS parameter registers.
88 static const MCPhysReg GPRArgRegs[] = {
89   ARM::R0, ARM::R1, ARM::R2, ARM::R3
90 };
91
92 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
93                                        MVT PromotedBitwiseVT) {
94   if (VT != PromotedLdStVT) {
95     setOperationAction(ISD::LOAD, VT, Promote);
96     AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
97
98     setOperationAction(ISD::STORE, VT, Promote);
99     AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
100   }
101
102   MVT ElemTy = VT.getVectorElementType();
103   if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
104     setOperationAction(ISD::SETCC, VT, Custom);
105   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
106   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
107   if (ElemTy == MVT::i32) {
108     setOperationAction(ISD::SINT_TO_FP, VT, Custom);
109     setOperationAction(ISD::UINT_TO_FP, VT, Custom);
110     setOperationAction(ISD::FP_TO_SINT, VT, Custom);
111     setOperationAction(ISD::FP_TO_UINT, VT, Custom);
112   } else {
113     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
114     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
115     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
116     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
117   }
118   setOperationAction(ISD::BUILD_VECTOR,      VT, Custom);
119   setOperationAction(ISD::VECTOR_SHUFFLE,    VT, Custom);
120   setOperationAction(ISD::CONCAT_VECTORS,    VT, Legal);
121   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
122   setOperationAction(ISD::SELECT,            VT, Expand);
123   setOperationAction(ISD::SELECT_CC,         VT, Expand);
124   setOperationAction(ISD::VSELECT,           VT, Expand);
125   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
126   if (VT.isInteger()) {
127     setOperationAction(ISD::SHL, VT, Custom);
128     setOperationAction(ISD::SRA, VT, Custom);
129     setOperationAction(ISD::SRL, VT, Custom);
130   }
131
132   // Promote all bit-wise operations.
133   if (VT.isInteger() && VT != PromotedBitwiseVT) {
134     setOperationAction(ISD::AND, VT, Promote);
135     AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
136     setOperationAction(ISD::OR,  VT, Promote);
137     AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
138     setOperationAction(ISD::XOR, VT, Promote);
139     AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
140   }
141
142   // Neon does not support vector divide/remainder operations.
143   setOperationAction(ISD::SDIV, VT, Expand);
144   setOperationAction(ISD::UDIV, VT, Expand);
145   setOperationAction(ISD::FDIV, VT, Expand);
146   setOperationAction(ISD::SREM, VT, Expand);
147   setOperationAction(ISD::UREM, VT, Expand);
148   setOperationAction(ISD::FREM, VT, Expand);
149 }
150
151 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
152   addRegisterClass(VT, &ARM::DPRRegClass);
153   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
154 }
155
156 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
157   addRegisterClass(VT, &ARM::DPairRegClass);
158   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
159 }
160
161 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM,
162                                      const ARMSubtarget &STI)
163     : TargetLowering(TM), Subtarget(&STI) {
164   RegInfo = Subtarget->getRegisterInfo();
165   Itins = Subtarget->getInstrItineraryData();
166
167   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
168
169   if (Subtarget->isTargetMachO()) {
170     // Uses VFP for Thumb libfuncs if available.
171     if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
172         Subtarget->hasARMOps() && !TM.Options.UseSoftFloat) {
173       // Single-precision floating-point arithmetic.
174       setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
175       setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
176       setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
177       setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
178
179       // Double-precision floating-point arithmetic.
180       setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
181       setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
182       setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
183       setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
184
185       // Single-precision comparisons.
186       setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
187       setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
188       setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
189       setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
190       setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
191       setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
192       setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
193       setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
194
195       setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
196       setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
197       setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
198       setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
199       setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
200       setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
201       setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
202       setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
203
204       // Double-precision comparisons.
205       setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
206       setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
207       setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
208       setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
209       setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
210       setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
211       setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
212       setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
213
214       setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
215       setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
216       setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
217       setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
218       setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
219       setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
220       setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
221       setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
222
223       // Floating-point to integer conversions.
224       // i64 conversions are done via library routines even when generating VFP
225       // instructions, so use the same ones.
226       setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
227       setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
228       setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
229       setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
230
231       // Conversions between floating types.
232       setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
233       setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
234
235       // Integer to floating-point conversions.
236       // i64 conversions are done via library routines even when generating VFP
237       // instructions, so use the same ones.
238       // FIXME: There appears to be some naming inconsistency in ARM libgcc:
239       // e.g., __floatunsidf vs. __floatunssidfvfp.
240       setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
241       setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
242       setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
243       setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
244     }
245   }
246
247   // These libcalls are not available in 32-bit.
248   setLibcallName(RTLIB::SHL_I128, nullptr);
249   setLibcallName(RTLIB::SRL_I128, nullptr);
250   setLibcallName(RTLIB::SRA_I128, nullptr);
251
252   if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO() &&
253       !Subtarget->isTargetWindows()) {
254     static const struct {
255       const RTLIB::Libcall Op;
256       const char * const Name;
257       const CallingConv::ID CC;
258       const ISD::CondCode Cond;
259     } LibraryCalls[] = {
260       // Double-precision floating-point arithmetic helper functions
261       // RTABI chapter 4.1.2, Table 2
262       { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
263       { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
264       { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
265       { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
266
267       // Double-precision floating-point comparison helper functions
268       // RTABI chapter 4.1.2, Table 3
269       { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
270       { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
271       { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
272       { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
273       { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
274       { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
275       { RTLIB::UO_F64,  "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
276       { RTLIB::O_F64,   "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
277
278       // Single-precision floating-point arithmetic helper functions
279       // RTABI chapter 4.1.2, Table 4
280       { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
281       { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
282       { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
283       { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
284
285       // Single-precision floating-point comparison helper functions
286       // RTABI chapter 4.1.2, Table 5
287       { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
288       { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
289       { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
290       { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
291       { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
292       { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
293       { RTLIB::UO_F32,  "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
294       { RTLIB::O_F32,   "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
295
296       // Floating-point to integer conversions.
297       // RTABI chapter 4.1.2, Table 6
298       { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
299       { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
300       { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
301       { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
302       { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
303       { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
304       { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
305       { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
306
307       // Conversions between floating types.
308       // RTABI chapter 4.1.2, Table 7
309       { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
310       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
311       { RTLIB::FPEXT_F32_F64,   "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
312
313       // Integer to floating-point conversions.
314       // RTABI chapter 4.1.2, Table 8
315       { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
316       { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
317       { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
318       { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
319       { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
320       { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
321       { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
322       { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
323
324       // Long long helper functions
325       // RTABI chapter 4.2, Table 9
326       { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
327       { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
328       { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
329       { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
330
331       // Integer division functions
332       // RTABI chapter 4.3.1
333       { RTLIB::SDIV_I8,  "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
334       { RTLIB::SDIV_I16, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
335       { RTLIB::SDIV_I32, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
336       { RTLIB::SDIV_I64, "__aeabi_ldivmod",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
337       { RTLIB::UDIV_I8,  "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
338       { RTLIB::UDIV_I16, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
339       { RTLIB::UDIV_I32, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
340       { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
341
342       // Memory operations
343       // RTABI chapter 4.3.4
344       { RTLIB::MEMCPY,  "__aeabi_memcpy",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
345       { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
346       { RTLIB::MEMSET,  "__aeabi_memset",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
347     };
348
349     for (const auto &LC : LibraryCalls) {
350       setLibcallName(LC.Op, LC.Name);
351       setLibcallCallingConv(LC.Op, LC.CC);
352       if (LC.Cond != ISD::SETCC_INVALID)
353         setCmpLibcallCC(LC.Op, LC.Cond);
354     }
355   }
356
357   if (Subtarget->isTargetWindows()) {
358     static const struct {
359       const RTLIB::Libcall Op;
360       const char * const Name;
361       const CallingConv::ID CC;
362     } LibraryCalls[] = {
363       { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
364       { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
365       { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
366       { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
367       { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
368       { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
369       { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
370       { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
371     };
372
373     for (const auto &LC : LibraryCalls) {
374       setLibcallName(LC.Op, LC.Name);
375       setLibcallCallingConv(LC.Op, LC.CC);
376     }
377   }
378
379   // Use divmod compiler-rt calls for iOS 5.0 and later.
380   if (Subtarget->getTargetTriple().isiOS() &&
381       !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
382     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
383     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
384   }
385
386   // The half <-> float conversion functions are always soft-float, but are
387   // needed for some targets which use a hard-float calling convention by
388   // default.
389   if (Subtarget->isAAPCS_ABI()) {
390     setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
391     setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
392     setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
393   } else {
394     setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
395     setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
396     setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
397   }
398
399   if (Subtarget->isThumb1Only())
400     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
401   else
402     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
403   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
404       !Subtarget->isThumb1Only()) {
405     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
406     addRegisterClass(MVT::f64, &ARM::DPRRegClass);
407   }
408
409   for (MVT VT : MVT::vector_valuetypes()) {
410     for (MVT InnerVT : MVT::vector_valuetypes()) {
411       setTruncStoreAction(VT, InnerVT, Expand);
412       setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
413       setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
414       setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
415     }
416
417     setOperationAction(ISD::MULHS, VT, Expand);
418     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
419     setOperationAction(ISD::MULHU, VT, Expand);
420     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
421
422     setOperationAction(ISD::BSWAP, VT, Expand);
423   }
424
425   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
426   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
427
428   if (Subtarget->hasNEON()) {
429     addDRTypeForNEON(MVT::v2f32);
430     addDRTypeForNEON(MVT::v8i8);
431     addDRTypeForNEON(MVT::v4i16);
432     addDRTypeForNEON(MVT::v2i32);
433     addDRTypeForNEON(MVT::v1i64);
434
435     addQRTypeForNEON(MVT::v4f32);
436     addQRTypeForNEON(MVT::v2f64);
437     addQRTypeForNEON(MVT::v16i8);
438     addQRTypeForNEON(MVT::v8i16);
439     addQRTypeForNEON(MVT::v4i32);
440     addQRTypeForNEON(MVT::v2i64);
441
442     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
443     // neither Neon nor VFP support any arithmetic operations on it.
444     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
445     // supported for v4f32.
446     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
447     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
448     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
449     // FIXME: Code duplication: FDIV and FREM are expanded always, see
450     // ARMTargetLowering::addTypeForNEON method for details.
451     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
452     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
453     // FIXME: Create unittest.
454     // In another words, find a way when "copysign" appears in DAG with vector
455     // operands.
456     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
457     // FIXME: Code duplication: SETCC has custom operation action, see
458     // ARMTargetLowering::addTypeForNEON method for details.
459     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
460     // FIXME: Create unittest for FNEG and for FABS.
461     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
462     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
463     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
464     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
465     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
466     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
467     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
468     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
469     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
470     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
471     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
472     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
473     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
474     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
475     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
476     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
477     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
478     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
479     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
480
481     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
482     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
483     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
484     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
485     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
486     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
487     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
488     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
489     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
490     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
491     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
492     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
493     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
494     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
495     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
496
497     // Mark v2f32 intrinsics.
498     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
499     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
500     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
501     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
502     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
503     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
504     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
505     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
506     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
507     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
508     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
509     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
510     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
511     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
512     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
513
514     // Neon does not support some operations on v1i64 and v2i64 types.
515     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
516     // Custom handling for some quad-vector types to detect VMULL.
517     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
518     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
519     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
520     // Custom handling for some vector types to avoid expensive expansions
521     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
522     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
523     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
524     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
525     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
526     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
527     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
528     // a destination type that is wider than the source, and nor does
529     // it have a FP_TO_[SU]INT instruction with a narrower destination than
530     // source.
531     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
532     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
533     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
534     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
535
536     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
537     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
538
539     // NEON does not have single instruction CTPOP for vectors with element
540     // types wider than 8-bits.  However, custom lowering can leverage the
541     // v8i8/v16i8 vcnt instruction.
542     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
543     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
544     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
545     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
546
547     // NEON only has FMA instructions as of VFP4.
548     if (!Subtarget->hasVFP4()) {
549       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
550       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
551     }
552
553     setTargetDAGCombine(ISD::INTRINSIC_VOID);
554     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
555     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
556     setTargetDAGCombine(ISD::SHL);
557     setTargetDAGCombine(ISD::SRL);
558     setTargetDAGCombine(ISD::SRA);
559     setTargetDAGCombine(ISD::SIGN_EXTEND);
560     setTargetDAGCombine(ISD::ZERO_EXTEND);
561     setTargetDAGCombine(ISD::ANY_EXTEND);
562     setTargetDAGCombine(ISD::SELECT_CC);
563     setTargetDAGCombine(ISD::BUILD_VECTOR);
564     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
565     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
566     setTargetDAGCombine(ISD::STORE);
567     setTargetDAGCombine(ISD::FP_TO_SINT);
568     setTargetDAGCombine(ISD::FP_TO_UINT);
569     setTargetDAGCombine(ISD::FDIV);
570     setTargetDAGCombine(ISD::LOAD);
571
572     // It is legal to extload from v4i8 to v4i16 or v4i32.
573     for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
574                    MVT::v2i32}) {
575       for (MVT VT : MVT::integer_vector_valuetypes()) {
576         setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
577         setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
578         setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
579       }
580     }
581   }
582
583   // ARM and Thumb2 support UMLAL/SMLAL.
584   if (!Subtarget->isThumb1Only())
585     setTargetDAGCombine(ISD::ADDC);
586
587   if (Subtarget->isFPOnlySP()) {
588     // When targetting a floating-point unit with only single-precision
589     // operations, f64 is legal for the few double-precision instructions which
590     // are present However, no double-precision operations other than moves,
591     // loads and stores are provided by the hardware.
592     setOperationAction(ISD::FADD,       MVT::f64, Expand);
593     setOperationAction(ISD::FSUB,       MVT::f64, Expand);
594     setOperationAction(ISD::FMUL,       MVT::f64, Expand);
595     setOperationAction(ISD::FMA,        MVT::f64, Expand);
596     setOperationAction(ISD::FDIV,       MVT::f64, Expand);
597     setOperationAction(ISD::FREM,       MVT::f64, Expand);
598     setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
599     setOperationAction(ISD::FGETSIGN,   MVT::f64, Expand);
600     setOperationAction(ISD::FNEG,       MVT::f64, Expand);
601     setOperationAction(ISD::FABS,       MVT::f64, Expand);
602     setOperationAction(ISD::FSQRT,      MVT::f64, Expand);
603     setOperationAction(ISD::FSIN,       MVT::f64, Expand);
604     setOperationAction(ISD::FCOS,       MVT::f64, Expand);
605     setOperationAction(ISD::FPOWI,      MVT::f64, Expand);
606     setOperationAction(ISD::FPOW,       MVT::f64, Expand);
607     setOperationAction(ISD::FLOG,       MVT::f64, Expand);
608     setOperationAction(ISD::FLOG2,      MVT::f64, Expand);
609     setOperationAction(ISD::FLOG10,     MVT::f64, Expand);
610     setOperationAction(ISD::FEXP,       MVT::f64, Expand);
611     setOperationAction(ISD::FEXP2,      MVT::f64, Expand);
612     setOperationAction(ISD::FCEIL,      MVT::f64, Expand);
613     setOperationAction(ISD::FTRUNC,     MVT::f64, Expand);
614     setOperationAction(ISD::FRINT,      MVT::f64, Expand);
615     setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
616     setOperationAction(ISD::FFLOOR,     MVT::f64, Expand);
617     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
618     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
619     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
620     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
621     setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
622     setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
623     setOperationAction(ISD::FP_ROUND,   MVT::f32, Custom);
624     setOperationAction(ISD::FP_EXTEND,  MVT::f64, Custom);
625   }
626
627   computeRegisterProperties(Subtarget->getRegisterInfo());
628
629   // ARM does not have floating-point extending loads.
630   for (MVT VT : MVT::fp_valuetypes()) {
631     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
632     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
633   }
634
635   // ... or truncating stores
636   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
637   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
638   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
639
640   // ARM does not have i1 sign extending load.
641   for (MVT VT : MVT::integer_valuetypes())
642     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
643
644   // ARM supports all 4 flavors of integer indexed load / store.
645   if (!Subtarget->isThumb1Only()) {
646     for (unsigned im = (unsigned)ISD::PRE_INC;
647          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
648       setIndexedLoadAction(im,  MVT::i1,  Legal);
649       setIndexedLoadAction(im,  MVT::i8,  Legal);
650       setIndexedLoadAction(im,  MVT::i16, Legal);
651       setIndexedLoadAction(im,  MVT::i32, Legal);
652       setIndexedStoreAction(im, MVT::i1,  Legal);
653       setIndexedStoreAction(im, MVT::i8,  Legal);
654       setIndexedStoreAction(im, MVT::i16, Legal);
655       setIndexedStoreAction(im, MVT::i32, Legal);
656     }
657   }
658
659   setOperationAction(ISD::SADDO, MVT::i32, Custom);
660   setOperationAction(ISD::UADDO, MVT::i32, Custom);
661   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
662   setOperationAction(ISD::USUBO, MVT::i32, Custom);
663
664   // i64 operation support.
665   setOperationAction(ISD::MUL,     MVT::i64, Expand);
666   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
667   if (Subtarget->isThumb1Only()) {
668     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
669     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
670   }
671   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
672       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
673     setOperationAction(ISD::MULHS, MVT::i32, Expand);
674
675   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
676   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
677   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
678   setOperationAction(ISD::SRL,       MVT::i64, Custom);
679   setOperationAction(ISD::SRA,       MVT::i64, Custom);
680
681   if (!Subtarget->isThumb1Only()) {
682     // FIXME: We should do this for Thumb1 as well.
683     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
684     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
685     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
686     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
687   }
688
689   // ARM does not have ROTL.
690   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
691   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
692   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
693   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
694     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
695
696   // These just redirect to CTTZ and CTLZ on ARM.
697   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
698   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
699
700   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
701
702   // Only ARMv6 has BSWAP.
703   if (!Subtarget->hasV6Ops())
704     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
705
706   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
707       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
708     // These are expanded into libcalls if the cpu doesn't have HW divider.
709     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
710     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
711   }
712
713   // FIXME: Also set divmod for SREM on EABI
714   setOperationAction(ISD::SREM,  MVT::i32, Expand);
715   setOperationAction(ISD::UREM,  MVT::i32, Expand);
716   // Register based DivRem for AEABI (RTABI 4.2)
717   if (Subtarget->isTargetAEABI()) {
718     setLibcallName(RTLIB::SDIVREM_I8,  "__aeabi_idivmod");
719     setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
720     setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
721     setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
722     setLibcallName(RTLIB::UDIVREM_I8,  "__aeabi_uidivmod");
723     setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
724     setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
725     setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
726
727     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
728     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
729     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
730     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
731     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
732     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
733     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
734     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
735
736     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
737     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
738   } else {
739     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
740     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
741   }
742
743   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
744   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
745   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
746   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
747   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
748
749   setOperationAction(ISD::TRAP, MVT::Other, Legal);
750
751   // Use the default implementation.
752   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
753   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
754   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
755   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
756   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
757   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
758
759   if (!Subtarget->isTargetMachO()) {
760     // Non-MachO platforms may return values in these registers via the
761     // personality function.
762     setExceptionPointerRegister(ARM::R0);
763     setExceptionSelectorRegister(ARM::R1);
764   }
765
766   if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
767     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
768   else
769     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
770
771   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
772   // the default expansion. If we are targeting a single threaded system,
773   // then set them all for expand so we can lower them later into their
774   // non-atomic form.
775   if (TM.Options.ThreadModel == ThreadModel::Single)
776     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
777   else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
778     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
779     // to ldrex/strex loops already.
780     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
781
782     // On v8, we have particularly efficient implementations of atomic fences
783     // if they can be combined with nearby atomic loads and stores.
784     if (!Subtarget->hasV8Ops()) {
785       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
786       setInsertFencesForAtomic(true);
787     }
788   } else {
789     // If there's anything we can use as a barrier, go through custom lowering
790     // for ATOMIC_FENCE.
791     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
792                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
793
794     // Set them all for expansion, which will force libcalls.
795     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
796     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
797     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
798     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
799     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
800     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
801     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
802     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
803     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
804     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
805     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
806     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
807     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
808     // Unordered/Monotonic case.
809     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
810     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
811   }
812
813   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
814
815   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
816   if (!Subtarget->hasV6Ops()) {
817     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
818     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
819   }
820   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
821
822   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
823       !Subtarget->isThumb1Only()) {
824     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
825     // iff target supports vfp2.
826     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
827     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
828   }
829
830   // We want to custom lower some of our intrinsics.
831   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
832   if (Subtarget->isTargetDarwin()) {
833     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
834     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
835     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
836   }
837
838   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
839   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
840   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
841   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
842   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
843   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
844   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
845   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
846   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
847
848   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
849   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
850   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
851   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
852   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
853
854   // We don't support sin/cos/fmod/copysign/pow
855   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
856   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
857   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
858   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
859   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
860   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
861   setOperationAction(ISD::FREM,      MVT::f64, Expand);
862   setOperationAction(ISD::FREM,      MVT::f32, Expand);
863   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
864       !Subtarget->isThumb1Only()) {
865     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
866     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
867   }
868   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
869   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
870
871   if (!Subtarget->hasVFP4()) {
872     setOperationAction(ISD::FMA, MVT::f64, Expand);
873     setOperationAction(ISD::FMA, MVT::f32, Expand);
874   }
875
876   // Various VFP goodness
877   if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
878     // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
879     if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
880       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
881       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
882     }
883
884     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
885     if (!Subtarget->hasFP16()) {
886       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
887       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
888     }
889   }
890
891   // Combine sin / cos into one node or libcall if possible.
892   if (Subtarget->hasSinCos()) {
893     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
894     setLibcallName(RTLIB::SINCOS_F64, "sincos");
895     if (Subtarget->getTargetTriple().isiOS()) {
896       // For iOS, we don't want to the normal expansion of a libcall to
897       // sincos. We want to issue a libcall to __sincos_stret.
898       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
899       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
900     }
901   }
902
903   // FP-ARMv8 implements a lot of rounding-like FP operations.
904   if (Subtarget->hasFPARMv8()) {
905     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
906     setOperationAction(ISD::FCEIL, MVT::f32, Legal);
907     setOperationAction(ISD::FROUND, MVT::f32, Legal);
908     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
909     setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
910     setOperationAction(ISD::FRINT, MVT::f32, Legal);
911     if (!Subtarget->isFPOnlySP()) {
912       setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
913       setOperationAction(ISD::FCEIL, MVT::f64, Legal);
914       setOperationAction(ISD::FROUND, MVT::f64, Legal);
915       setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
916       setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
917       setOperationAction(ISD::FRINT, MVT::f64, Legal);
918     }
919   }
920   // We have target-specific dag combine patterns for the following nodes:
921   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
922   setTargetDAGCombine(ISD::ADD);
923   setTargetDAGCombine(ISD::SUB);
924   setTargetDAGCombine(ISD::MUL);
925   setTargetDAGCombine(ISD::AND);
926   setTargetDAGCombine(ISD::OR);
927   setTargetDAGCombine(ISD::XOR);
928
929   if (Subtarget->hasV6Ops())
930     setTargetDAGCombine(ISD::SRL);
931
932   setStackPointerRegisterToSaveRestore(ARM::SP);
933
934   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
935       !Subtarget->hasVFP2())
936     setSchedulingPreference(Sched::RegPressure);
937   else
938     setSchedulingPreference(Sched::Hybrid);
939
940   //// temporary - rewrite interface to use type
941   MaxStoresPerMemset = 8;
942   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
943   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
944   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
945   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
946   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
947
948   // On ARM arguments smaller than 4 bytes are extended, so all arguments
949   // are at least 4 bytes aligned.
950   setMinStackArgumentAlignment(4);
951
952   // Prefer likely predicted branches to selects on out-of-order cores.
953   PredictableSelectIsExpensive = Subtarget->isLikeA9();
954
955   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
956 }
957
958 // FIXME: It might make sense to define the representative register class as the
959 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
960 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
961 // SPR's representative would be DPR_VFP2. This should work well if register
962 // pressure tracking were modified such that a register use would increment the
963 // pressure of the register class's representative and all of it's super
964 // classes' representatives transitively. We have not implemented this because
965 // of the difficulty prior to coalescing of modeling operand register classes
966 // due to the common occurrence of cross class copies and subregister insertions
967 // and extractions.
968 std::pair<const TargetRegisterClass *, uint8_t>
969 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
970                                            MVT VT) const {
971   const TargetRegisterClass *RRC = nullptr;
972   uint8_t Cost = 1;
973   switch (VT.SimpleTy) {
974   default:
975     return TargetLowering::findRepresentativeClass(TRI, VT);
976   // Use DPR as representative register class for all floating point
977   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
978   // the cost is 1 for both f32 and f64.
979   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
980   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
981     RRC = &ARM::DPRRegClass;
982     // When NEON is used for SP, only half of the register file is available
983     // because operations that define both SP and DP results will be constrained
984     // to the VFP2 class (D0-D15). We currently model this constraint prior to
985     // coalescing by double-counting the SP regs. See the FIXME above.
986     if (Subtarget->useNEONForSinglePrecisionFP())
987       Cost = 2;
988     break;
989   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
990   case MVT::v4f32: case MVT::v2f64:
991     RRC = &ARM::DPRRegClass;
992     Cost = 2;
993     break;
994   case MVT::v4i64:
995     RRC = &ARM::DPRRegClass;
996     Cost = 4;
997     break;
998   case MVT::v8i64:
999     RRC = &ARM::DPRRegClass;
1000     Cost = 8;
1001     break;
1002   }
1003   return std::make_pair(RRC, Cost);
1004 }
1005
1006 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1007   switch (Opcode) {
1008   default: return nullptr;
1009   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1010   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1011   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1012   case ARMISD::CALL:          return "ARMISD::CALL";
1013   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1014   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1015   case ARMISD::tCALL:         return "ARMISD::tCALL";
1016   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1017   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1018   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1019   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1020   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1021   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1022   case ARMISD::CMP:           return "ARMISD::CMP";
1023   case ARMISD::CMN:           return "ARMISD::CMN";
1024   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1025   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1026   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1027   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1028   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1029
1030   case ARMISD::CMOV:          return "ARMISD::CMOV";
1031
1032   case ARMISD::RBIT:          return "ARMISD::RBIT";
1033
1034   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1035   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1036   case ARMISD::RRX:           return "ARMISD::RRX";
1037
1038   case ARMISD::ADDC:          return "ARMISD::ADDC";
1039   case ARMISD::ADDE:          return "ARMISD::ADDE";
1040   case ARMISD::SUBC:          return "ARMISD::SUBC";
1041   case ARMISD::SUBE:          return "ARMISD::SUBE";
1042
1043   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1044   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1045
1046   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1047   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
1048
1049   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1050
1051   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1052
1053   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1054
1055   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1056
1057   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1058
1059   case ARMISD::WIN__CHKSTK:   return "ARMISD:::WIN__CHKSTK";
1060
1061   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1062   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1063   case ARMISD::VCGE:          return "ARMISD::VCGE";
1064   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1065   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1066   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1067   case ARMISD::VCGT:          return "ARMISD::VCGT";
1068   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1069   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1070   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1071   case ARMISD::VTST:          return "ARMISD::VTST";
1072
1073   case ARMISD::VSHL:          return "ARMISD::VSHL";
1074   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1075   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1076   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1077   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1078   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1079   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1080   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1081   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1082   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1083   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1084   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1085   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1086   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1087   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1088   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1089   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1090   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1091   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1092   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1093   case ARMISD::VDUP:          return "ARMISD::VDUP";
1094   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1095   case ARMISD::VEXT:          return "ARMISD::VEXT";
1096   case ARMISD::VREV64:        return "ARMISD::VREV64";
1097   case ARMISD::VREV32:        return "ARMISD::VREV32";
1098   case ARMISD::VREV16:        return "ARMISD::VREV16";
1099   case ARMISD::VZIP:          return "ARMISD::VZIP";
1100   case ARMISD::VUZP:          return "ARMISD::VUZP";
1101   case ARMISD::VTRN:          return "ARMISD::VTRN";
1102   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1103   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1104   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1105   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1106   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1107   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1108   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1109   case ARMISD::FMAX:          return "ARMISD::FMAX";
1110   case ARMISD::FMIN:          return "ARMISD::FMIN";
1111   case ARMISD::VMAXNM:        return "ARMISD::VMAX";
1112   case ARMISD::VMINNM:        return "ARMISD::VMIN";
1113   case ARMISD::BFI:           return "ARMISD::BFI";
1114   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1115   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1116   case ARMISD::VBSL:          return "ARMISD::VBSL";
1117   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1118   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1119   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1120   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1121   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1122   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1123   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1124   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1125   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1126   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1127   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1128   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1129   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1130   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1131   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1132   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1133   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1134   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1135   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1136   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1137   }
1138 }
1139
1140 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1141   if (!VT.isVector()) return getPointerTy();
1142   return VT.changeVectorElementTypeToInteger();
1143 }
1144
1145 /// getRegClassFor - Return the register class that should be used for the
1146 /// specified value type.
1147 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1148   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1149   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1150   // load / store 4 to 8 consecutive D registers.
1151   if (Subtarget->hasNEON()) {
1152     if (VT == MVT::v4i64)
1153       return &ARM::QQPRRegClass;
1154     if (VT == MVT::v8i64)
1155       return &ARM::QQQQPRRegClass;
1156   }
1157   return TargetLowering::getRegClassFor(VT);
1158 }
1159
1160 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1161 // source/dest is aligned and the copy size is large enough. We therefore want
1162 // to align such objects passed to memory intrinsics.
1163 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1164                                                unsigned &PrefAlign) const {
1165   if (!isa<MemIntrinsic>(CI))
1166     return false;
1167   MinSize = 8;
1168   // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1169   // cycle faster than 4-byte aligned LDM.
1170   PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1171   return true;
1172 }
1173
1174 // Create a fast isel object.
1175 FastISel *
1176 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1177                                   const TargetLibraryInfo *libInfo) const {
1178   return ARM::createFastISel(funcInfo, libInfo);
1179 }
1180
1181 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1182   unsigned NumVals = N->getNumValues();
1183   if (!NumVals)
1184     return Sched::RegPressure;
1185
1186   for (unsigned i = 0; i != NumVals; ++i) {
1187     EVT VT = N->getValueType(i);
1188     if (VT == MVT::Glue || VT == MVT::Other)
1189       continue;
1190     if (VT.isFloatingPoint() || VT.isVector())
1191       return Sched::ILP;
1192   }
1193
1194   if (!N->isMachineOpcode())
1195     return Sched::RegPressure;
1196
1197   // Load are scheduled for latency even if there instruction itinerary
1198   // is not available.
1199   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1200   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1201
1202   if (MCID.getNumDefs() == 0)
1203     return Sched::RegPressure;
1204   if (!Itins->isEmpty() &&
1205       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1206     return Sched::ILP;
1207
1208   return Sched::RegPressure;
1209 }
1210
1211 //===----------------------------------------------------------------------===//
1212 // Lowering Code
1213 //===----------------------------------------------------------------------===//
1214
1215 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1216 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1217   switch (CC) {
1218   default: llvm_unreachable("Unknown condition code!");
1219   case ISD::SETNE:  return ARMCC::NE;
1220   case ISD::SETEQ:  return ARMCC::EQ;
1221   case ISD::SETGT:  return ARMCC::GT;
1222   case ISD::SETGE:  return ARMCC::GE;
1223   case ISD::SETLT:  return ARMCC::LT;
1224   case ISD::SETLE:  return ARMCC::LE;
1225   case ISD::SETUGT: return ARMCC::HI;
1226   case ISD::SETUGE: return ARMCC::HS;
1227   case ISD::SETULT: return ARMCC::LO;
1228   case ISD::SETULE: return ARMCC::LS;
1229   }
1230 }
1231
1232 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1233 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1234                         ARMCC::CondCodes &CondCode2) {
1235   CondCode2 = ARMCC::AL;
1236   switch (CC) {
1237   default: llvm_unreachable("Unknown FP condition!");
1238   case ISD::SETEQ:
1239   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1240   case ISD::SETGT:
1241   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1242   case ISD::SETGE:
1243   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1244   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1245   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1246   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1247   case ISD::SETO:   CondCode = ARMCC::VC; break;
1248   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1249   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1250   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1251   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1252   case ISD::SETLT:
1253   case ISD::SETULT: CondCode = ARMCC::LT; break;
1254   case ISD::SETLE:
1255   case ISD::SETULE: CondCode = ARMCC::LE; break;
1256   case ISD::SETNE:
1257   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1258   }
1259 }
1260
1261 //===----------------------------------------------------------------------===//
1262 //                      Calling Convention Implementation
1263 //===----------------------------------------------------------------------===//
1264
1265 #include "ARMGenCallingConv.inc"
1266
1267 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1268 /// account presence of floating point hardware and calling convention
1269 /// limitations, such as support for variadic functions.
1270 CallingConv::ID
1271 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1272                                            bool isVarArg) const {
1273   switch (CC) {
1274   default:
1275     llvm_unreachable("Unsupported calling convention");
1276   case CallingConv::ARM_AAPCS:
1277   case CallingConv::ARM_APCS:
1278   case CallingConv::GHC:
1279     return CC;
1280   case CallingConv::ARM_AAPCS_VFP:
1281     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1282   case CallingConv::C:
1283     if (!Subtarget->isAAPCS_ABI())
1284       return CallingConv::ARM_APCS;
1285     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1286              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1287              !isVarArg)
1288       return CallingConv::ARM_AAPCS_VFP;
1289     else
1290       return CallingConv::ARM_AAPCS;
1291   case CallingConv::Fast:
1292     if (!Subtarget->isAAPCS_ABI()) {
1293       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1294         return CallingConv::Fast;
1295       return CallingConv::ARM_APCS;
1296     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1297       return CallingConv::ARM_AAPCS_VFP;
1298     else
1299       return CallingConv::ARM_AAPCS;
1300   }
1301 }
1302
1303 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1304 /// CallingConvention.
1305 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1306                                                  bool Return,
1307                                                  bool isVarArg) const {
1308   switch (getEffectiveCallingConv(CC, isVarArg)) {
1309   default:
1310     llvm_unreachable("Unsupported calling convention");
1311   case CallingConv::ARM_APCS:
1312     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1313   case CallingConv::ARM_AAPCS:
1314     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1315   case CallingConv::ARM_AAPCS_VFP:
1316     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1317   case CallingConv::Fast:
1318     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1319   case CallingConv::GHC:
1320     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1321   }
1322 }
1323
1324 /// LowerCallResult - Lower the result values of a call into the
1325 /// appropriate copies out of appropriate physical registers.
1326 SDValue
1327 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1328                                    CallingConv::ID CallConv, bool isVarArg,
1329                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1330                                    SDLoc dl, SelectionDAG &DAG,
1331                                    SmallVectorImpl<SDValue> &InVals,
1332                                    bool isThisReturn, SDValue ThisVal) const {
1333
1334   // Assign locations to each value returned by this call.
1335   SmallVector<CCValAssign, 16> RVLocs;
1336   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1337                     *DAG.getContext(), Call);
1338   CCInfo.AnalyzeCallResult(Ins,
1339                            CCAssignFnForNode(CallConv, /* Return*/ true,
1340                                              isVarArg));
1341
1342   // Copy all of the result registers out of their specified physreg.
1343   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1344     CCValAssign VA = RVLocs[i];
1345
1346     // Pass 'this' value directly from the argument to return value, to avoid
1347     // reg unit interference
1348     if (i == 0 && isThisReturn) {
1349       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1350              "unexpected return calling convention register assignment");
1351       InVals.push_back(ThisVal);
1352       continue;
1353     }
1354
1355     SDValue Val;
1356     if (VA.needsCustom()) {
1357       // Handle f64 or half of a v2f64.
1358       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1359                                       InFlag);
1360       Chain = Lo.getValue(1);
1361       InFlag = Lo.getValue(2);
1362       VA = RVLocs[++i]; // skip ahead to next loc
1363       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1364                                       InFlag);
1365       Chain = Hi.getValue(1);
1366       InFlag = Hi.getValue(2);
1367       if (!Subtarget->isLittle())
1368         std::swap (Lo, Hi);
1369       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1370
1371       if (VA.getLocVT() == MVT::v2f64) {
1372         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1373         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1374                           DAG.getConstant(0, MVT::i32));
1375
1376         VA = RVLocs[++i]; // skip ahead to next loc
1377         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1378         Chain = Lo.getValue(1);
1379         InFlag = Lo.getValue(2);
1380         VA = RVLocs[++i]; // skip ahead to next loc
1381         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1382         Chain = Hi.getValue(1);
1383         InFlag = Hi.getValue(2);
1384         if (!Subtarget->isLittle())
1385           std::swap (Lo, Hi);
1386         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1387         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1388                           DAG.getConstant(1, MVT::i32));
1389       }
1390     } else {
1391       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1392                                InFlag);
1393       Chain = Val.getValue(1);
1394       InFlag = Val.getValue(2);
1395     }
1396
1397     switch (VA.getLocInfo()) {
1398     default: llvm_unreachable("Unknown loc info!");
1399     case CCValAssign::Full: break;
1400     case CCValAssign::BCvt:
1401       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1402       break;
1403     }
1404
1405     InVals.push_back(Val);
1406   }
1407
1408   return Chain;
1409 }
1410
1411 /// LowerMemOpCallTo - Store the argument to the stack.
1412 SDValue
1413 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1414                                     SDValue StackPtr, SDValue Arg,
1415                                     SDLoc dl, SelectionDAG &DAG,
1416                                     const CCValAssign &VA,
1417                                     ISD::ArgFlagsTy Flags) const {
1418   unsigned LocMemOffset = VA.getLocMemOffset();
1419   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1420   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1421   return DAG.getStore(Chain, dl, Arg, PtrOff,
1422                       MachinePointerInfo::getStack(LocMemOffset),
1423                       false, false, 0);
1424 }
1425
1426 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1427                                          SDValue Chain, SDValue &Arg,
1428                                          RegsToPassVector &RegsToPass,
1429                                          CCValAssign &VA, CCValAssign &NextVA,
1430                                          SDValue &StackPtr,
1431                                          SmallVectorImpl<SDValue> &MemOpChains,
1432                                          ISD::ArgFlagsTy Flags) const {
1433
1434   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1435                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1436   unsigned id = Subtarget->isLittle() ? 0 : 1;
1437   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1438
1439   if (NextVA.isRegLoc())
1440     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1441   else {
1442     assert(NextVA.isMemLoc());
1443     if (!StackPtr.getNode())
1444       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1445
1446     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1447                                            dl, DAG, NextVA,
1448                                            Flags));
1449   }
1450 }
1451
1452 /// LowerCall - Lowering a call into a callseq_start <-
1453 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1454 /// nodes.
1455 SDValue
1456 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1457                              SmallVectorImpl<SDValue> &InVals) const {
1458   SelectionDAG &DAG                     = CLI.DAG;
1459   SDLoc &dl                          = CLI.DL;
1460   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1461   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1462   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1463   SDValue Chain                         = CLI.Chain;
1464   SDValue Callee                        = CLI.Callee;
1465   bool &isTailCall                      = CLI.IsTailCall;
1466   CallingConv::ID CallConv              = CLI.CallConv;
1467   bool doesNotRet                       = CLI.DoesNotReturn;
1468   bool isVarArg                         = CLI.IsVarArg;
1469
1470   MachineFunction &MF = DAG.getMachineFunction();
1471   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1472   bool isThisReturn   = false;
1473   bool isSibCall      = false;
1474
1475   // Disable tail calls if they're not supported.
1476   if (!Subtarget->supportsTailCall() || MF.getTarget().Options.DisableTailCalls)
1477     isTailCall = false;
1478
1479   if (isTailCall) {
1480     // Check if it's really possible to do a tail call.
1481     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1482                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1483                                                    Outs, OutVals, Ins, DAG);
1484     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1485       report_fatal_error("failed to perform tail call elimination on a call "
1486                          "site marked musttail");
1487     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1488     // detected sibcalls.
1489     if (isTailCall) {
1490       ++NumTailCalls;
1491       isSibCall = true;
1492     }
1493   }
1494
1495   // Analyze operands of the call, assigning locations to each operand.
1496   SmallVector<CCValAssign, 16> ArgLocs;
1497   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1498                     *DAG.getContext(), Call);
1499   CCInfo.AnalyzeCallOperands(Outs,
1500                              CCAssignFnForNode(CallConv, /* Return*/ false,
1501                                                isVarArg));
1502
1503   // Get a count of how many bytes are to be pushed on the stack.
1504   unsigned NumBytes = CCInfo.getNextStackOffset();
1505
1506   // For tail calls, memory operands are available in our caller's stack.
1507   if (isSibCall)
1508     NumBytes = 0;
1509
1510   // Adjust the stack pointer for the new arguments...
1511   // These operations are automatically eliminated by the prolog/epilog pass
1512   if (!isSibCall)
1513     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1514                                  dl);
1515
1516   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1517
1518   RegsToPassVector RegsToPass;
1519   SmallVector<SDValue, 8> MemOpChains;
1520
1521   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1522   // of tail call optimization, arguments are handled later.
1523   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1524        i != e;
1525        ++i, ++realArgIdx) {
1526     CCValAssign &VA = ArgLocs[i];
1527     SDValue Arg = OutVals[realArgIdx];
1528     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1529     bool isByVal = Flags.isByVal();
1530
1531     // Promote the value if needed.
1532     switch (VA.getLocInfo()) {
1533     default: llvm_unreachable("Unknown loc info!");
1534     case CCValAssign::Full: break;
1535     case CCValAssign::SExt:
1536       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1537       break;
1538     case CCValAssign::ZExt:
1539       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1540       break;
1541     case CCValAssign::AExt:
1542       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1543       break;
1544     case CCValAssign::BCvt:
1545       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1546       break;
1547     }
1548
1549     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1550     if (VA.needsCustom()) {
1551       if (VA.getLocVT() == MVT::v2f64) {
1552         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1553                                   DAG.getConstant(0, MVT::i32));
1554         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1555                                   DAG.getConstant(1, MVT::i32));
1556
1557         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1558                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1559
1560         VA = ArgLocs[++i]; // skip ahead to next loc
1561         if (VA.isRegLoc()) {
1562           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1563                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1564         } else {
1565           assert(VA.isMemLoc());
1566
1567           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1568                                                  dl, DAG, VA, Flags));
1569         }
1570       } else {
1571         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1572                          StackPtr, MemOpChains, Flags);
1573       }
1574     } else if (VA.isRegLoc()) {
1575       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1576         assert(VA.getLocVT() == MVT::i32 &&
1577                "unexpected calling convention register assignment");
1578         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1579                "unexpected use of 'returned'");
1580         isThisReturn = true;
1581       }
1582       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1583     } else if (isByVal) {
1584       assert(VA.isMemLoc());
1585       unsigned offset = 0;
1586
1587       // True if this byval aggregate will be split between registers
1588       // and memory.
1589       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1590       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1591
1592       if (CurByValIdx < ByValArgsCount) {
1593
1594         unsigned RegBegin, RegEnd;
1595         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1596
1597         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1598         unsigned int i, j;
1599         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1600           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1601           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1602           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1603                                      MachinePointerInfo(),
1604                                      false, false, false,
1605                                      DAG.InferPtrAlignment(AddArg));
1606           MemOpChains.push_back(Load.getValue(1));
1607           RegsToPass.push_back(std::make_pair(j, Load));
1608         }
1609
1610         // If parameter size outsides register area, "offset" value
1611         // helps us to calculate stack slot for remained part properly.
1612         offset = RegEnd - RegBegin;
1613
1614         CCInfo.nextInRegsParam();
1615       }
1616
1617       if (Flags.getByValSize() > 4*offset) {
1618         unsigned LocMemOffset = VA.getLocMemOffset();
1619         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1620         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1621                                   StkPtrOff);
1622         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1623         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1624         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1625                                            MVT::i32);
1626         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1627
1628         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1629         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1630         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1631                                           Ops));
1632       }
1633     } else if (!isSibCall) {
1634       assert(VA.isMemLoc());
1635
1636       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1637                                              dl, DAG, VA, Flags));
1638     }
1639   }
1640
1641   if (!MemOpChains.empty())
1642     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1643
1644   // Build a sequence of copy-to-reg nodes chained together with token chain
1645   // and flag operands which copy the outgoing args into the appropriate regs.
1646   SDValue InFlag;
1647   // Tail call byval lowering might overwrite argument registers so in case of
1648   // tail call optimization the copies to registers are lowered later.
1649   if (!isTailCall)
1650     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1651       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1652                                RegsToPass[i].second, InFlag);
1653       InFlag = Chain.getValue(1);
1654     }
1655
1656   // For tail calls lower the arguments to the 'real' stack slot.
1657   if (isTailCall) {
1658     // Force all the incoming stack arguments to be loaded from the stack
1659     // before any new outgoing arguments are stored to the stack, because the
1660     // outgoing stack slots may alias the incoming argument stack slots, and
1661     // the alias isn't otherwise explicit. This is slightly more conservative
1662     // than necessary, because it means that each store effectively depends
1663     // on every argument instead of just those arguments it would clobber.
1664
1665     // Do not flag preceding copytoreg stuff together with the following stuff.
1666     InFlag = SDValue();
1667     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1668       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1669                                RegsToPass[i].second, InFlag);
1670       InFlag = Chain.getValue(1);
1671     }
1672     InFlag = SDValue();
1673   }
1674
1675   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1676   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1677   // node so that legalize doesn't hack it.
1678   bool isDirect = false;
1679   bool isARMFunc = false;
1680   bool isLocalARMFunc = false;
1681   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1682
1683   if (EnableARMLongCalls) {
1684     assert((Subtarget->isTargetWindows() ||
1685             getTargetMachine().getRelocationModel() == Reloc::Static) &&
1686            "long-calls with non-static relocation model!");
1687     // Handle a global address or an external symbol. If it's not one of
1688     // those, the target's already in a register, so we don't need to do
1689     // anything extra.
1690     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1691       const GlobalValue *GV = G->getGlobal();
1692       // Create a constant pool entry for the callee address
1693       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1694       ARMConstantPoolValue *CPV =
1695         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1696
1697       // Get the address of the callee into a register
1698       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1699       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1700       Callee = DAG.getLoad(getPointerTy(), dl,
1701                            DAG.getEntryNode(), CPAddr,
1702                            MachinePointerInfo::getConstantPool(),
1703                            false, false, false, 0);
1704     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1705       const char *Sym = S->getSymbol();
1706
1707       // Create a constant pool entry for the callee address
1708       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1709       ARMConstantPoolValue *CPV =
1710         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1711                                       ARMPCLabelIndex, 0);
1712       // Get the address of the callee into a register
1713       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1714       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1715       Callee = DAG.getLoad(getPointerTy(), dl,
1716                            DAG.getEntryNode(), CPAddr,
1717                            MachinePointerInfo::getConstantPool(),
1718                            false, false, false, 0);
1719     }
1720   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1721     const GlobalValue *GV = G->getGlobal();
1722     isDirect = true;
1723     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1724     bool isStub = (isExt && Subtarget->isTargetMachO()) &&
1725                    getTargetMachine().getRelocationModel() != Reloc::Static;
1726     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1727     // ARM call to a local ARM function is predicable.
1728     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1729     // tBX takes a register source operand.
1730     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1731       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1732       Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1733                            DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
1734                                                       0, ARMII::MO_NONLAZY));
1735       Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
1736                            MachinePointerInfo::getGOT(), false, false, true, 0);
1737     } else if (Subtarget->isTargetCOFF()) {
1738       assert(Subtarget->isTargetWindows() &&
1739              "Windows is the only supported COFF target");
1740       unsigned TargetFlags = GV->hasDLLImportStorageClass()
1741                                  ? ARMII::MO_DLLIMPORT
1742                                  : ARMII::MO_NO_FLAG;
1743       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), /*Offset=*/0,
1744                                           TargetFlags);
1745       if (GV->hasDLLImportStorageClass())
1746         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
1747                              DAG.getNode(ARMISD::Wrapper, dl, getPointerTy(),
1748                                          Callee), MachinePointerInfo::getGOT(),
1749                              false, false, false, 0);
1750     } else {
1751       // On ELF targets for PIC code, direct calls should go through the PLT
1752       unsigned OpFlags = 0;
1753       if (Subtarget->isTargetELF() &&
1754           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1755         OpFlags = ARMII::MO_PLT;
1756       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1757     }
1758   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1759     isDirect = true;
1760     bool isStub = Subtarget->isTargetMachO() &&
1761                   getTargetMachine().getRelocationModel() != Reloc::Static;
1762     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1763     // tBX takes a register source operand.
1764     const char *Sym = S->getSymbol();
1765     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1766       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1767       ARMConstantPoolValue *CPV =
1768         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1769                                       ARMPCLabelIndex, 4);
1770       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1771       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1772       Callee = DAG.getLoad(getPointerTy(), dl,
1773                            DAG.getEntryNode(), CPAddr,
1774                            MachinePointerInfo::getConstantPool(),
1775                            false, false, false, 0);
1776       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1777       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1778                            getPointerTy(), Callee, PICLabel);
1779     } else {
1780       unsigned OpFlags = 0;
1781       // On ELF targets for PIC code, direct calls should go through the PLT
1782       if (Subtarget->isTargetELF() &&
1783                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1784         OpFlags = ARMII::MO_PLT;
1785       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1786     }
1787   }
1788
1789   // FIXME: handle tail calls differently.
1790   unsigned CallOpc;
1791   bool HasMinSizeAttr = MF.getFunction()->hasFnAttribute(Attribute::MinSize);
1792   if (Subtarget->isThumb()) {
1793     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1794       CallOpc = ARMISD::CALL_NOLINK;
1795     else
1796       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1797   } else {
1798     if (!isDirect && !Subtarget->hasV5TOps())
1799       CallOpc = ARMISD::CALL_NOLINK;
1800     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1801                // Emit regular call when code size is the priority
1802                !HasMinSizeAttr)
1803       // "mov lr, pc; b _foo" to avoid confusing the RSP
1804       CallOpc = ARMISD::CALL_NOLINK;
1805     else
1806       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1807   }
1808
1809   std::vector<SDValue> Ops;
1810   Ops.push_back(Chain);
1811   Ops.push_back(Callee);
1812
1813   // Add argument registers to the end of the list so that they are known live
1814   // into the call.
1815   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1816     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1817                                   RegsToPass[i].second.getValueType()));
1818
1819   // Add a register mask operand representing the call-preserved registers.
1820   if (!isTailCall) {
1821     const uint32_t *Mask;
1822     const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
1823     if (isThisReturn) {
1824       // For 'this' returns, use the R0-preserving mask if applicable
1825       Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
1826       if (!Mask) {
1827         // Set isThisReturn to false if the calling convention is not one that
1828         // allows 'returned' to be modeled in this way, so LowerCallResult does
1829         // not try to pass 'this' straight through
1830         isThisReturn = false;
1831         Mask = ARI->getCallPreservedMask(MF, CallConv);
1832       }
1833     } else
1834       Mask = ARI->getCallPreservedMask(MF, CallConv);
1835
1836     assert(Mask && "Missing call preserved mask for calling convention");
1837     Ops.push_back(DAG.getRegisterMask(Mask));
1838   }
1839
1840   if (InFlag.getNode())
1841     Ops.push_back(InFlag);
1842
1843   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1844   if (isTailCall)
1845     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1846
1847   // Returns a chain and a flag for retval copy to use.
1848   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1849   InFlag = Chain.getValue(1);
1850
1851   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1852                              DAG.getIntPtrConstant(0, true), InFlag, dl);
1853   if (!Ins.empty())
1854     InFlag = Chain.getValue(1);
1855
1856   // Handle result values, copying them out of physregs into vregs that we
1857   // return.
1858   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1859                          InVals, isThisReturn,
1860                          isThisReturn ? OutVals[0] : SDValue());
1861 }
1862
1863 /// HandleByVal - Every parameter *after* a byval parameter is passed
1864 /// on the stack.  Remember the next parameter register to allocate,
1865 /// and then confiscate the rest of the parameter registers to insure
1866 /// this.
1867 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
1868                                     unsigned Align) const {
1869   assert((State->getCallOrPrologue() == Prologue ||
1870           State->getCallOrPrologue() == Call) &&
1871          "unhandled ParmContext");
1872
1873   // Byval (as with any stack) slots are always at least 4 byte aligned.
1874   Align = std::max(Align, 4U);
1875
1876   unsigned Reg = State->AllocateReg(GPRArgRegs);
1877   if (!Reg)
1878     return;
1879
1880   unsigned AlignInRegs = Align / 4;
1881   unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
1882   for (unsigned i = 0; i < Waste; ++i)
1883     Reg = State->AllocateReg(GPRArgRegs);
1884
1885   if (!Reg)
1886     return;
1887
1888   unsigned Excess = 4 * (ARM::R4 - Reg);
1889
1890   // Special case when NSAA != SP and parameter size greater than size of
1891   // all remained GPR regs. In that case we can't split parameter, we must
1892   // send it to stack. We also must set NCRN to R4, so waste all
1893   // remained registers.
1894   const unsigned NSAAOffset = State->getNextStackOffset();
1895   if (NSAAOffset != 0 && Size > Excess) {
1896     while (State->AllocateReg(GPRArgRegs))
1897       ;
1898     return;
1899   }
1900
1901   // First register for byval parameter is the first register that wasn't
1902   // allocated before this method call, so it would be "reg".
1903   // If parameter is small enough to be saved in range [reg, r4), then
1904   // the end (first after last) register would be reg + param-size-in-regs,
1905   // else parameter would be splitted between registers and stack,
1906   // end register would be r4 in this case.
1907   unsigned ByValRegBegin = Reg;
1908   unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
1909   State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1910   // Note, first register is allocated in the beginning of function already,
1911   // allocate remained amount of registers we need.
1912   for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
1913     State->AllocateReg(GPRArgRegs);
1914   // A byval parameter that is split between registers and memory needs its
1915   // size truncated here.
1916   // In the case where the entire structure fits in registers, we set the
1917   // size in memory to zero.
1918   Size = std::max<int>(Size - Excess, 0);
1919 }
1920
1921
1922 /// MatchingStackOffset - Return true if the given stack call argument is
1923 /// already available in the same position (relatively) of the caller's
1924 /// incoming argument stack.
1925 static
1926 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1927                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1928                          const TargetInstrInfo *TII) {
1929   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1930   int FI = INT_MAX;
1931   if (Arg.getOpcode() == ISD::CopyFromReg) {
1932     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1933     if (!TargetRegisterInfo::isVirtualRegister(VR))
1934       return false;
1935     MachineInstr *Def = MRI->getVRegDef(VR);
1936     if (!Def)
1937       return false;
1938     if (!Flags.isByVal()) {
1939       if (!TII->isLoadFromStackSlot(Def, FI))
1940         return false;
1941     } else {
1942       return false;
1943     }
1944   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1945     if (Flags.isByVal())
1946       // ByVal argument is passed in as a pointer but it's now being
1947       // dereferenced. e.g.
1948       // define @foo(%struct.X* %A) {
1949       //   tail call @bar(%struct.X* byval %A)
1950       // }
1951       return false;
1952     SDValue Ptr = Ld->getBasePtr();
1953     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1954     if (!FINode)
1955       return false;
1956     FI = FINode->getIndex();
1957   } else
1958     return false;
1959
1960   assert(FI != INT_MAX);
1961   if (!MFI->isFixedObjectIndex(FI))
1962     return false;
1963   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1964 }
1965
1966 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1967 /// for tail call optimization. Targets which want to do tail call
1968 /// optimization should implement this function.
1969 bool
1970 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1971                                                      CallingConv::ID CalleeCC,
1972                                                      bool isVarArg,
1973                                                      bool isCalleeStructRet,
1974                                                      bool isCallerStructRet,
1975                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1976                                     const SmallVectorImpl<SDValue> &OutVals,
1977                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1978                                                      SelectionDAG& DAG) const {
1979   const Function *CallerF = DAG.getMachineFunction().getFunction();
1980   CallingConv::ID CallerCC = CallerF->getCallingConv();
1981   bool CCMatch = CallerCC == CalleeCC;
1982
1983   // Look for obvious safe cases to perform tail call optimization that do not
1984   // require ABI changes. This is what gcc calls sibcall.
1985
1986   // Do not sibcall optimize vararg calls unless the call site is not passing
1987   // any arguments.
1988   if (isVarArg && !Outs.empty())
1989     return false;
1990
1991   // Exception-handling functions need a special set of instructions to indicate
1992   // a return to the hardware. Tail-calling another function would probably
1993   // break this.
1994   if (CallerF->hasFnAttribute("interrupt"))
1995     return false;
1996
1997   // Also avoid sibcall optimization if either caller or callee uses struct
1998   // return semantics.
1999   if (isCalleeStructRet || isCallerStructRet)
2000     return false;
2001
2002   // FIXME: Completely disable sibcall for Thumb1 since ThumbRegisterInfo::
2003   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
2004   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
2005   // support in the assembler and linker to be used. This would need to be
2006   // fixed to fully support tail calls in Thumb1.
2007   //
2008   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
2009   // LR.  This means if we need to reload LR, it takes an extra instructions,
2010   // which outweighs the value of the tail call; but here we don't know yet
2011   // whether LR is going to be used.  Probably the right approach is to
2012   // generate the tail call here and turn it back into CALL/RET in
2013   // emitEpilogue if LR is used.
2014
2015   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
2016   // but we need to make sure there are enough registers; the only valid
2017   // registers are the 4 used for parameters.  We don't currently do this
2018   // case.
2019   if (Subtarget->isThumb1Only())
2020     return false;
2021
2022   // Externally-defined functions with weak linkage should not be
2023   // tail-called on ARM when the OS does not support dynamic
2024   // pre-emption of symbols, as the AAELF spec requires normal calls
2025   // to undefined weak functions to be replaced with a NOP or jump to the
2026   // next instruction. The behaviour of branch instructions in this
2027   // situation (as used for tail calls) is implementation-defined, so we
2028   // cannot rely on the linker replacing the tail call with a return.
2029   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2030     const GlobalValue *GV = G->getGlobal();
2031     const Triple TT(getTargetMachine().getTargetTriple());
2032     if (GV->hasExternalWeakLinkage() &&
2033         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2034       return false;
2035   }
2036
2037   // If the calling conventions do not match, then we'd better make sure the
2038   // results are returned in the same way as what the caller expects.
2039   if (!CCMatch) {
2040     SmallVector<CCValAssign, 16> RVLocs1;
2041     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2042                        *DAG.getContext(), Call);
2043     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2044
2045     SmallVector<CCValAssign, 16> RVLocs2;
2046     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2047                        *DAG.getContext(), Call);
2048     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2049
2050     if (RVLocs1.size() != RVLocs2.size())
2051       return false;
2052     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2053       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2054         return false;
2055       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2056         return false;
2057       if (RVLocs1[i].isRegLoc()) {
2058         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2059           return false;
2060       } else {
2061         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2062           return false;
2063       }
2064     }
2065   }
2066
2067   // If Caller's vararg or byval argument has been split between registers and
2068   // stack, do not perform tail call, since part of the argument is in caller's
2069   // local frame.
2070   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2071                                       getInfo<ARMFunctionInfo>();
2072   if (AFI_Caller->getArgRegsSaveSize())
2073     return false;
2074
2075   // If the callee takes no arguments then go on to check the results of the
2076   // call.
2077   if (!Outs.empty()) {
2078     // Check if stack adjustment is needed. For now, do not do this if any
2079     // argument is passed on the stack.
2080     SmallVector<CCValAssign, 16> ArgLocs;
2081     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2082                       *DAG.getContext(), Call);
2083     CCInfo.AnalyzeCallOperands(Outs,
2084                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2085     if (CCInfo.getNextStackOffset()) {
2086       MachineFunction &MF = DAG.getMachineFunction();
2087
2088       // Check if the arguments are already laid out in the right way as
2089       // the caller's fixed stack objects.
2090       MachineFrameInfo *MFI = MF.getFrameInfo();
2091       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2092       const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2093       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2094            i != e;
2095            ++i, ++realArgIdx) {
2096         CCValAssign &VA = ArgLocs[i];
2097         EVT RegVT = VA.getLocVT();
2098         SDValue Arg = OutVals[realArgIdx];
2099         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2100         if (VA.getLocInfo() == CCValAssign::Indirect)
2101           return false;
2102         if (VA.needsCustom()) {
2103           // f64 and vector types are split into multiple registers or
2104           // register/stack-slot combinations.  The types will not match
2105           // the registers; give up on memory f64 refs until we figure
2106           // out what to do about this.
2107           if (!VA.isRegLoc())
2108             return false;
2109           if (!ArgLocs[++i].isRegLoc())
2110             return false;
2111           if (RegVT == MVT::v2f64) {
2112             if (!ArgLocs[++i].isRegLoc())
2113               return false;
2114             if (!ArgLocs[++i].isRegLoc())
2115               return false;
2116           }
2117         } else if (!VA.isRegLoc()) {
2118           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2119                                    MFI, MRI, TII))
2120             return false;
2121         }
2122       }
2123     }
2124   }
2125
2126   return true;
2127 }
2128
2129 bool
2130 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2131                                   MachineFunction &MF, bool isVarArg,
2132                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2133                                   LLVMContext &Context) const {
2134   SmallVector<CCValAssign, 16> RVLocs;
2135   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2136   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2137                                                     isVarArg));
2138 }
2139
2140 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2141                                     SDLoc DL, SelectionDAG &DAG) {
2142   const MachineFunction &MF = DAG.getMachineFunction();
2143   const Function *F = MF.getFunction();
2144
2145   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2146
2147   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2148   // version of the "preferred return address". These offsets affect the return
2149   // instruction if this is a return from PL1 without hypervisor extensions.
2150   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2151   //    SWI:     0      "subs pc, lr, #0"
2152   //    ABORT:   +4     "subs pc, lr, #4"
2153   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2154   // UNDEF varies depending on where the exception came from ARM or Thumb
2155   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2156
2157   int64_t LROffset;
2158   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2159       IntKind == "ABORT")
2160     LROffset = 4;
2161   else if (IntKind == "SWI" || IntKind == "UNDEF")
2162     LROffset = 0;
2163   else
2164     report_fatal_error("Unsupported interrupt attribute. If present, value "
2165                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2166
2167   RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2168
2169   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2170 }
2171
2172 SDValue
2173 ARMTargetLowering::LowerReturn(SDValue Chain,
2174                                CallingConv::ID CallConv, bool isVarArg,
2175                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2176                                const SmallVectorImpl<SDValue> &OutVals,
2177                                SDLoc dl, SelectionDAG &DAG) const {
2178
2179   // CCValAssign - represent the assignment of the return value to a location.
2180   SmallVector<CCValAssign, 16> RVLocs;
2181
2182   // CCState - Info about the registers and stack slots.
2183   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2184                     *DAG.getContext(), Call);
2185
2186   // Analyze outgoing return values.
2187   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2188                                                isVarArg));
2189
2190   SDValue Flag;
2191   SmallVector<SDValue, 4> RetOps;
2192   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2193   bool isLittleEndian = Subtarget->isLittle();
2194
2195   MachineFunction &MF = DAG.getMachineFunction();
2196   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2197   AFI->setReturnRegsCount(RVLocs.size());
2198
2199   // Copy the result values into the output registers.
2200   for (unsigned i = 0, realRVLocIdx = 0;
2201        i != RVLocs.size();
2202        ++i, ++realRVLocIdx) {
2203     CCValAssign &VA = RVLocs[i];
2204     assert(VA.isRegLoc() && "Can only return in registers!");
2205
2206     SDValue Arg = OutVals[realRVLocIdx];
2207
2208     switch (VA.getLocInfo()) {
2209     default: llvm_unreachable("Unknown loc info!");
2210     case CCValAssign::Full: break;
2211     case CCValAssign::BCvt:
2212       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2213       break;
2214     }
2215
2216     if (VA.needsCustom()) {
2217       if (VA.getLocVT() == MVT::v2f64) {
2218         // Extract the first half and return it in two registers.
2219         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2220                                    DAG.getConstant(0, MVT::i32));
2221         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2222                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2223
2224         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2225                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2226                                  Flag);
2227         Flag = Chain.getValue(1);
2228         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2229         VA = RVLocs[++i]; // skip ahead to next loc
2230         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2231                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2232                                  Flag);
2233         Flag = Chain.getValue(1);
2234         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2235         VA = RVLocs[++i]; // skip ahead to next loc
2236
2237         // Extract the 2nd half and fall through to handle it as an f64 value.
2238         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2239                           DAG.getConstant(1, MVT::i32));
2240       }
2241       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2242       // available.
2243       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2244                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2245       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2246                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2247                                Flag);
2248       Flag = Chain.getValue(1);
2249       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2250       VA = RVLocs[++i]; // skip ahead to next loc
2251       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2252                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2253                                Flag);
2254     } else
2255       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2256
2257     // Guarantee that all emitted copies are
2258     // stuck together, avoiding something bad.
2259     Flag = Chain.getValue(1);
2260     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2261   }
2262
2263   // Update chain and glue.
2264   RetOps[0] = Chain;
2265   if (Flag.getNode())
2266     RetOps.push_back(Flag);
2267
2268   // CPUs which aren't M-class use a special sequence to return from
2269   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2270   // though we use "subs pc, lr, #N").
2271   //
2272   // M-class CPUs actually use a normal return sequence with a special
2273   // (hardware-provided) value in LR, so the normal code path works.
2274   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2275       !Subtarget->isMClass()) {
2276     if (Subtarget->isThumb1Only())
2277       report_fatal_error("interrupt attribute is not supported in Thumb1");
2278     return LowerInterruptReturn(RetOps, dl, DAG);
2279   }
2280
2281   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2282 }
2283
2284 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2285   if (N->getNumValues() != 1)
2286     return false;
2287   if (!N->hasNUsesOfValue(1, 0))
2288     return false;
2289
2290   SDValue TCChain = Chain;
2291   SDNode *Copy = *N->use_begin();
2292   if (Copy->getOpcode() == ISD::CopyToReg) {
2293     // If the copy has a glue operand, we conservatively assume it isn't safe to
2294     // perform a tail call.
2295     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2296       return false;
2297     TCChain = Copy->getOperand(0);
2298   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2299     SDNode *VMov = Copy;
2300     // f64 returned in a pair of GPRs.
2301     SmallPtrSet<SDNode*, 2> Copies;
2302     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2303          UI != UE; ++UI) {
2304       if (UI->getOpcode() != ISD::CopyToReg)
2305         return false;
2306       Copies.insert(*UI);
2307     }
2308     if (Copies.size() > 2)
2309       return false;
2310
2311     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2312          UI != UE; ++UI) {
2313       SDValue UseChain = UI->getOperand(0);
2314       if (Copies.count(UseChain.getNode()))
2315         // Second CopyToReg
2316         Copy = *UI;
2317       else {
2318         // We are at the top of this chain.
2319         // If the copy has a glue operand, we conservatively assume it
2320         // isn't safe to perform a tail call.
2321         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2322           return false;
2323         // First CopyToReg
2324         TCChain = UseChain;
2325       }
2326     }
2327   } else if (Copy->getOpcode() == ISD::BITCAST) {
2328     // f32 returned in a single GPR.
2329     if (!Copy->hasOneUse())
2330       return false;
2331     Copy = *Copy->use_begin();
2332     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2333       return false;
2334     // If the copy has a glue operand, we conservatively assume it isn't safe to
2335     // perform a tail call.
2336     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2337       return false;
2338     TCChain = Copy->getOperand(0);
2339   } else {
2340     return false;
2341   }
2342
2343   bool HasRet = false;
2344   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2345        UI != UE; ++UI) {
2346     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2347         UI->getOpcode() != ARMISD::INTRET_FLAG)
2348       return false;
2349     HasRet = true;
2350   }
2351
2352   if (!HasRet)
2353     return false;
2354
2355   Chain = TCChain;
2356   return true;
2357 }
2358
2359 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2360   if (!Subtarget->supportsTailCall())
2361     return false;
2362
2363   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2364     return false;
2365
2366   return !Subtarget->isThumb1Only();
2367 }
2368
2369 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2370 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2371 // one of the above mentioned nodes. It has to be wrapped because otherwise
2372 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2373 // be used to form addressing mode. These wrapped nodes will be selected
2374 // into MOVi.
2375 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2376   EVT PtrVT = Op.getValueType();
2377   // FIXME there is no actual debug info here
2378   SDLoc dl(Op);
2379   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2380   SDValue Res;
2381   if (CP->isMachineConstantPoolEntry())
2382     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2383                                     CP->getAlignment());
2384   else
2385     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2386                                     CP->getAlignment());
2387   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2388 }
2389
2390 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2391   return MachineJumpTableInfo::EK_Inline;
2392 }
2393
2394 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2395                                              SelectionDAG &DAG) const {
2396   MachineFunction &MF = DAG.getMachineFunction();
2397   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2398   unsigned ARMPCLabelIndex = 0;
2399   SDLoc DL(Op);
2400   EVT PtrVT = getPointerTy();
2401   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2402   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2403   SDValue CPAddr;
2404   if (RelocM == Reloc::Static) {
2405     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2406   } else {
2407     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2408     ARMPCLabelIndex = AFI->createPICLabelUId();
2409     ARMConstantPoolValue *CPV =
2410       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2411                                       ARMCP::CPBlockAddress, PCAdj);
2412     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2413   }
2414   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2415   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2416                                MachinePointerInfo::getConstantPool(),
2417                                false, false, false, 0);
2418   if (RelocM == Reloc::Static)
2419     return Result;
2420   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2421   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2422 }
2423
2424 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2425 SDValue
2426 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2427                                                  SelectionDAG &DAG) const {
2428   SDLoc dl(GA);
2429   EVT PtrVT = getPointerTy();
2430   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2431   MachineFunction &MF = DAG.getMachineFunction();
2432   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2433   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2434   ARMConstantPoolValue *CPV =
2435     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2436                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2437   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2438   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2439   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2440                          MachinePointerInfo::getConstantPool(),
2441                          false, false, false, 0);
2442   SDValue Chain = Argument.getValue(1);
2443
2444   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2445   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2446
2447   // call __tls_get_addr.
2448   ArgListTy Args;
2449   ArgListEntry Entry;
2450   Entry.Node = Argument;
2451   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2452   Args.push_back(Entry);
2453
2454   // FIXME: is there useful debug info available here?
2455   TargetLowering::CallLoweringInfo CLI(DAG);
2456   CLI.setDebugLoc(dl).setChain(Chain)
2457     .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2458                DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2459                0);
2460
2461   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2462   return CallResult.first;
2463 }
2464
2465 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2466 // "local exec" model.
2467 SDValue
2468 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2469                                         SelectionDAG &DAG,
2470                                         TLSModel::Model model) const {
2471   const GlobalValue *GV = GA->getGlobal();
2472   SDLoc dl(GA);
2473   SDValue Offset;
2474   SDValue Chain = DAG.getEntryNode();
2475   EVT PtrVT = getPointerTy();
2476   // Get the Thread Pointer
2477   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2478
2479   if (model == TLSModel::InitialExec) {
2480     MachineFunction &MF = DAG.getMachineFunction();
2481     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2482     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2483     // Initial exec model.
2484     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2485     ARMConstantPoolValue *CPV =
2486       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2487                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2488                                       true);
2489     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2490     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2491     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2492                          MachinePointerInfo::getConstantPool(),
2493                          false, false, false, 0);
2494     Chain = Offset.getValue(1);
2495
2496     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2497     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2498
2499     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2500                          MachinePointerInfo::getConstantPool(),
2501                          false, false, false, 0);
2502   } else {
2503     // local exec model
2504     assert(model == TLSModel::LocalExec);
2505     ARMConstantPoolValue *CPV =
2506       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2507     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2508     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2509     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2510                          MachinePointerInfo::getConstantPool(),
2511                          false, false, false, 0);
2512   }
2513
2514   // The address of the thread local variable is the add of the thread
2515   // pointer with the offset of the variable.
2516   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2517 }
2518
2519 SDValue
2520 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2521   // TODO: implement the "local dynamic" model
2522   assert(Subtarget->isTargetELF() &&
2523          "TLS not implemented for non-ELF targets");
2524   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2525
2526   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2527
2528   switch (model) {
2529     case TLSModel::GeneralDynamic:
2530     case TLSModel::LocalDynamic:
2531       return LowerToTLSGeneralDynamicModel(GA, DAG);
2532     case TLSModel::InitialExec:
2533     case TLSModel::LocalExec:
2534       return LowerToTLSExecModels(GA, DAG, model);
2535   }
2536   llvm_unreachable("bogus TLS model");
2537 }
2538
2539 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2540                                                  SelectionDAG &DAG) const {
2541   EVT PtrVT = getPointerTy();
2542   SDLoc dl(Op);
2543   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2544   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2545     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2546     ARMConstantPoolValue *CPV =
2547       ARMConstantPoolConstant::Create(GV,
2548                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2549     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2550     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2551     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2552                                  CPAddr,
2553                                  MachinePointerInfo::getConstantPool(),
2554                                  false, false, false, 0);
2555     SDValue Chain = Result.getValue(1);
2556     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2557     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2558     if (!UseGOTOFF)
2559       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2560                            MachinePointerInfo::getGOT(),
2561                            false, false, false, 0);
2562     return Result;
2563   }
2564
2565   // If we have T2 ops, we can materialize the address directly via movt/movw
2566   // pair. This is always cheaper.
2567   if (Subtarget->useMovt(DAG.getMachineFunction())) {
2568     ++NumMovwMovt;
2569     // FIXME: Once remat is capable of dealing with instructions with register
2570     // operands, expand this into two nodes.
2571     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2572                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2573   } else {
2574     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2575     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2576     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2577                        MachinePointerInfo::getConstantPool(),
2578                        false, false, false, 0);
2579   }
2580 }
2581
2582 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2583                                                     SelectionDAG &DAG) const {
2584   EVT PtrVT = getPointerTy();
2585   SDLoc dl(Op);
2586   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2587   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2588
2589   if (Subtarget->useMovt(DAG.getMachineFunction()))
2590     ++NumMovwMovt;
2591
2592   // FIXME: Once remat is capable of dealing with instructions with register
2593   // operands, expand this into multiple nodes
2594   unsigned Wrapper =
2595       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2596
2597   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2598   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2599
2600   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2601     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2602                          MachinePointerInfo::getGOT(), false, false, false, 0);
2603   return Result;
2604 }
2605
2606 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2607                                                      SelectionDAG &DAG) const {
2608   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2609   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2610          "Windows on ARM expects to use movw/movt");
2611
2612   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2613   const ARMII::TOF TargetFlags =
2614     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2615   EVT PtrVT = getPointerTy();
2616   SDValue Result;
2617   SDLoc DL(Op);
2618
2619   ++NumMovwMovt;
2620
2621   // FIXME: Once remat is capable of dealing with instructions with register
2622   // operands, expand this into two nodes.
2623   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2624                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2625                                                   TargetFlags));
2626   if (GV->hasDLLImportStorageClass())
2627     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2628                          MachinePointerInfo::getGOT(), false, false, false, 0);
2629   return Result;
2630 }
2631
2632 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2633                                                     SelectionDAG &DAG) const {
2634   assert(Subtarget->isTargetELF() &&
2635          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2636   MachineFunction &MF = DAG.getMachineFunction();
2637   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2638   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2639   EVT PtrVT = getPointerTy();
2640   SDLoc dl(Op);
2641   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2642   ARMConstantPoolValue *CPV =
2643     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2644                                   ARMPCLabelIndex, PCAdj);
2645   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2646   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2647   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2648                                MachinePointerInfo::getConstantPool(),
2649                                false, false, false, 0);
2650   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2651   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2652 }
2653
2654 SDValue
2655 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2656   SDLoc dl(Op);
2657   SDValue Val = DAG.getConstant(0, MVT::i32);
2658   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2659                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2660                      Op.getOperand(1), Val);
2661 }
2662
2663 SDValue
2664 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2665   SDLoc dl(Op);
2666   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2667                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2668 }
2669
2670 SDValue
2671 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2672                                           const ARMSubtarget *Subtarget) const {
2673   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2674   SDLoc dl(Op);
2675   switch (IntNo) {
2676   default: return SDValue();    // Don't custom lower most intrinsics.
2677   case Intrinsic::arm_rbit: {
2678     assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2679            "RBIT intrinsic must have i32 type!");
2680     return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1));
2681   }
2682   case Intrinsic::arm_thread_pointer: {
2683     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2684     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2685   }
2686   case Intrinsic::eh_sjlj_lsda: {
2687     MachineFunction &MF = DAG.getMachineFunction();
2688     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2689     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2690     EVT PtrVT = getPointerTy();
2691     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2692     SDValue CPAddr;
2693     unsigned PCAdj = (RelocM != Reloc::PIC_)
2694       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2695     ARMConstantPoolValue *CPV =
2696       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2697                                       ARMCP::CPLSDA, PCAdj);
2698     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2699     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2700     SDValue Result =
2701       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2702                   MachinePointerInfo::getConstantPool(),
2703                   false, false, false, 0);
2704
2705     if (RelocM == Reloc::PIC_) {
2706       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2707       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2708     }
2709     return Result;
2710   }
2711   case Intrinsic::arm_neon_vmulls:
2712   case Intrinsic::arm_neon_vmullu: {
2713     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2714       ? ARMISD::VMULLs : ARMISD::VMULLu;
2715     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2716                        Op.getOperand(1), Op.getOperand(2));
2717   }
2718   }
2719 }
2720
2721 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2722                                  const ARMSubtarget *Subtarget) {
2723   // FIXME: handle "fence singlethread" more efficiently.
2724   SDLoc dl(Op);
2725   if (!Subtarget->hasDataBarrier()) {
2726     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2727     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2728     // here.
2729     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2730            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2731     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2732                        DAG.getConstant(0, MVT::i32));
2733   }
2734
2735   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2736   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2737   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
2738   if (Subtarget->isMClass()) {
2739     // Only a full system barrier exists in the M-class architectures.
2740     Domain = ARM_MB::SY;
2741   } else if (Subtarget->isSwift() && Ord == Release) {
2742     // Swift happens to implement ISHST barriers in a way that's compatible with
2743     // Release semantics but weaker than ISH so we'd be fools not to use
2744     // it. Beware: other processors probably don't!
2745     Domain = ARM_MB::ISHST;
2746   }
2747
2748   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2749                      DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2750                      DAG.getConstant(Domain, MVT::i32));
2751 }
2752
2753 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2754                              const ARMSubtarget *Subtarget) {
2755   // ARM pre v5TE and Thumb1 does not have preload instructions.
2756   if (!(Subtarget->isThumb2() ||
2757         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2758     // Just preserve the chain.
2759     return Op.getOperand(0);
2760
2761   SDLoc dl(Op);
2762   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2763   if (!isRead &&
2764       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2765     // ARMv7 with MP extension has PLDW.
2766     return Op.getOperand(0);
2767
2768   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2769   if (Subtarget->isThumb()) {
2770     // Invert the bits.
2771     isRead = ~isRead & 1;
2772     isData = ~isData & 1;
2773   }
2774
2775   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2776                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2777                      DAG.getConstant(isData, MVT::i32));
2778 }
2779
2780 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2781   MachineFunction &MF = DAG.getMachineFunction();
2782   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2783
2784   // vastart just stores the address of the VarArgsFrameIndex slot into the
2785   // memory location argument.
2786   SDLoc dl(Op);
2787   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2788   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2789   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2790   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2791                       MachinePointerInfo(SV), false, false, 0);
2792 }
2793
2794 SDValue
2795 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2796                                         SDValue &Root, SelectionDAG &DAG,
2797                                         SDLoc dl) const {
2798   MachineFunction &MF = DAG.getMachineFunction();
2799   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2800
2801   const TargetRegisterClass *RC;
2802   if (AFI->isThumb1OnlyFunction())
2803     RC = &ARM::tGPRRegClass;
2804   else
2805     RC = &ARM::GPRRegClass;
2806
2807   // Transform the arguments stored in physical registers into virtual ones.
2808   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2809   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2810
2811   SDValue ArgValue2;
2812   if (NextVA.isMemLoc()) {
2813     MachineFrameInfo *MFI = MF.getFrameInfo();
2814     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2815
2816     // Create load node to retrieve arguments from the stack.
2817     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2818     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2819                             MachinePointerInfo::getFixedStack(FI),
2820                             false, false, false, 0);
2821   } else {
2822     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2823     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2824   }
2825   if (!Subtarget->isLittle())
2826     std::swap (ArgValue, ArgValue2);
2827   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2828 }
2829
2830 // The remaining GPRs hold either the beginning of variable-argument
2831 // data, or the beginning of an aggregate passed by value (usually
2832 // byval).  Either way, we allocate stack slots adjacent to the data
2833 // provided by our caller, and store the unallocated registers there.
2834 // If this is a variadic function, the va_list pointer will begin with
2835 // these values; otherwise, this reassembles a (byval) structure that
2836 // was split between registers and memory.
2837 // Return: The frame index registers were stored into.
2838 int
2839 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2840                                   SDLoc dl, SDValue &Chain,
2841                                   const Value *OrigArg,
2842                                   unsigned InRegsParamRecordIdx,
2843                                   int ArgOffset,
2844                                   unsigned ArgSize) const {
2845   // Currently, two use-cases possible:
2846   // Case #1. Non-var-args function, and we meet first byval parameter.
2847   //          Setup first unallocated register as first byval register;
2848   //          eat all remained registers
2849   //          (these two actions are performed by HandleByVal method).
2850   //          Then, here, we initialize stack frame with
2851   //          "store-reg" instructions.
2852   // Case #2. Var-args function, that doesn't contain byval parameters.
2853   //          The same: eat all remained unallocated registers,
2854   //          initialize stack frame.
2855
2856   MachineFunction &MF = DAG.getMachineFunction();
2857   MachineFrameInfo *MFI = MF.getFrameInfo();
2858   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2859   unsigned RBegin, REnd;
2860   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2861     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2862   } else {
2863     unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
2864     RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
2865     REnd = ARM::R4;
2866   }
2867
2868   if (REnd != RBegin)
2869     ArgOffset = -4 * (ARM::R4 - RBegin);
2870
2871   int FrameIndex = MFI->CreateFixedObject(ArgSize, ArgOffset, false);
2872   SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2873
2874   SmallVector<SDValue, 4> MemOps;
2875   const TargetRegisterClass *RC =
2876       AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
2877
2878   for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
2879     unsigned VReg = MF.addLiveIn(Reg, RC);
2880     SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2881     SDValue Store =
2882         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2883                      MachinePointerInfo(OrigArg, 4 * i), false, false, 0);
2884     MemOps.push_back(Store);
2885     FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2886                       DAG.getConstant(4, getPointerTy()));
2887   }
2888
2889   if (!MemOps.empty())
2890     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2891   return FrameIndex;
2892 }
2893
2894 // Setup stack frame, the va_list pointer will start from.
2895 void
2896 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2897                                         SDLoc dl, SDValue &Chain,
2898                                         unsigned ArgOffset,
2899                                         unsigned TotalArgRegsSaveSize,
2900                                         bool ForceMutable) const {
2901   MachineFunction &MF = DAG.getMachineFunction();
2902   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2903
2904   // Try to store any remaining integer argument regs
2905   // to their spots on the stack so that they may be loaded by deferencing
2906   // the result of va_next.
2907   // If there is no regs to be stored, just point address after last
2908   // argument passed via stack.
2909   int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
2910                                   CCInfo.getInRegsParamsCount(),
2911                                   CCInfo.getNextStackOffset(), 4);
2912   AFI->setVarArgsFrameIndex(FrameIndex);
2913 }
2914
2915 SDValue
2916 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2917                                         CallingConv::ID CallConv, bool isVarArg,
2918                                         const SmallVectorImpl<ISD::InputArg>
2919                                           &Ins,
2920                                         SDLoc dl, SelectionDAG &DAG,
2921                                         SmallVectorImpl<SDValue> &InVals)
2922                                           const {
2923   MachineFunction &MF = DAG.getMachineFunction();
2924   MachineFrameInfo *MFI = MF.getFrameInfo();
2925
2926   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2927
2928   // Assign locations to all of the incoming arguments.
2929   SmallVector<CCValAssign, 16> ArgLocs;
2930   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2931                     *DAG.getContext(), Prologue);
2932   CCInfo.AnalyzeFormalArguments(Ins,
2933                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2934                                                   isVarArg));
2935
2936   SmallVector<SDValue, 16> ArgValues;
2937   SDValue ArgValue;
2938   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2939   unsigned CurArgIdx = 0;
2940
2941   // Initially ArgRegsSaveSize is zero.
2942   // Then we increase this value each time we meet byval parameter.
2943   // We also increase this value in case of varargs function.
2944   AFI->setArgRegsSaveSize(0);
2945
2946   // Calculate the amount of stack space that we need to allocate to store
2947   // byval and variadic arguments that are passed in registers.
2948   // We need to know this before we allocate the first byval or variadic
2949   // argument, as they will be allocated a stack slot below the CFA (Canonical
2950   // Frame Address, the stack pointer at entry to the function).
2951   unsigned ArgRegBegin = ARM::R4;
2952   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2953     if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
2954       break;
2955
2956     CCValAssign &VA = ArgLocs[i];
2957     unsigned Index = VA.getValNo();
2958     ISD::ArgFlagsTy Flags = Ins[Index].Flags;
2959     if (!Flags.isByVal())
2960       continue;
2961
2962     assert(VA.isMemLoc() && "unexpected byval pointer in reg");
2963     unsigned RBegin, REnd;
2964     CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
2965     ArgRegBegin = std::min(ArgRegBegin, RBegin);
2966
2967     CCInfo.nextInRegsParam();
2968   }
2969   CCInfo.rewindByValRegsInfo();
2970
2971   int lastInsIndex = -1;
2972   if (isVarArg && MFI->hasVAStart()) {
2973     unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
2974     if (RegIdx != array_lengthof(GPRArgRegs))
2975       ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
2976   }
2977
2978   unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
2979   AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
2980
2981   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2982     CCValAssign &VA = ArgLocs[i];
2983     if (Ins[VA.getValNo()].isOrigArg()) {
2984       std::advance(CurOrigArg,
2985                    Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
2986       CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
2987     }
2988     // Arguments stored in registers.
2989     if (VA.isRegLoc()) {
2990       EVT RegVT = VA.getLocVT();
2991
2992       if (VA.needsCustom()) {
2993         // f64 and vector types are split up into multiple registers or
2994         // combinations of registers and stack slots.
2995         if (VA.getLocVT() == MVT::v2f64) {
2996           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2997                                                    Chain, DAG, dl);
2998           VA = ArgLocs[++i]; // skip ahead to next loc
2999           SDValue ArgValue2;
3000           if (VA.isMemLoc()) {
3001             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3002             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3003             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3004                                     MachinePointerInfo::getFixedStack(FI),
3005                                     false, false, false, 0);
3006           } else {
3007             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3008                                              Chain, DAG, dl);
3009           }
3010           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3011           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3012                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
3013           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3014                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
3015         } else
3016           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3017
3018       } else {
3019         const TargetRegisterClass *RC;
3020
3021         if (RegVT == MVT::f32)
3022           RC = &ARM::SPRRegClass;
3023         else if (RegVT == MVT::f64)
3024           RC = &ARM::DPRRegClass;
3025         else if (RegVT == MVT::v2f64)
3026           RC = &ARM::QPRRegClass;
3027         else if (RegVT == MVT::i32)
3028           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3029                                            : &ARM::GPRRegClass;
3030         else
3031           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3032
3033         // Transform the arguments in physical registers into virtual ones.
3034         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3035         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3036       }
3037
3038       // If this is an 8 or 16-bit value, it is really passed promoted
3039       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3040       // truncate to the right size.
3041       switch (VA.getLocInfo()) {
3042       default: llvm_unreachable("Unknown loc info!");
3043       case CCValAssign::Full: break;
3044       case CCValAssign::BCvt:
3045         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3046         break;
3047       case CCValAssign::SExt:
3048         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3049                                DAG.getValueType(VA.getValVT()));
3050         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3051         break;
3052       case CCValAssign::ZExt:
3053         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3054                                DAG.getValueType(VA.getValVT()));
3055         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3056         break;
3057       }
3058
3059       InVals.push_back(ArgValue);
3060
3061     } else { // VA.isRegLoc()
3062
3063       // sanity check
3064       assert(VA.isMemLoc());
3065       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3066
3067       int index = VA.getValNo();
3068
3069       // Some Ins[] entries become multiple ArgLoc[] entries.
3070       // Process them only once.
3071       if (index != lastInsIndex)
3072         {
3073           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3074           // FIXME: For now, all byval parameter objects are marked mutable.
3075           // This can be changed with more analysis.
3076           // In case of tail call optimization mark all arguments mutable.
3077           // Since they could be overwritten by lowering of arguments in case of
3078           // a tail call.
3079           if (Flags.isByVal()) {
3080             assert(Ins[index].isOrigArg() &&
3081                    "Byval arguments cannot be implicit");
3082             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3083
3084             int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, CurOrigArg,
3085                                             CurByValIndex, VA.getLocMemOffset(),
3086                                             Flags.getByValSize());
3087             InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3088             CCInfo.nextInRegsParam();
3089           } else {
3090             unsigned FIOffset = VA.getLocMemOffset();
3091             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3092                                             FIOffset, true);
3093
3094             // Create load nodes to retrieve arguments from the stack.
3095             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3096             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3097                                          MachinePointerInfo::getFixedStack(FI),
3098                                          false, false, false, 0));
3099           }
3100           lastInsIndex = index;
3101         }
3102     }
3103   }
3104
3105   // varargs
3106   if (isVarArg && MFI->hasVAStart())
3107     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3108                          CCInfo.getNextStackOffset(),
3109                          TotalArgRegsSaveSize);
3110
3111   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3112
3113   return Chain;
3114 }
3115
3116 /// isFloatingPointZero - Return true if this is +0.0.
3117 static bool isFloatingPointZero(SDValue Op) {
3118   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3119     return CFP->getValueAPF().isPosZero();
3120   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3121     // Maybe this has already been legalized into the constant pool?
3122     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3123       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3124       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3125         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3126           return CFP->getValueAPF().isPosZero();
3127     }
3128   } else if (Op->getOpcode() == ISD::BITCAST &&
3129              Op->getValueType(0) == MVT::f64) {
3130     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3131     // created by LowerConstantFP().
3132     SDValue BitcastOp = Op->getOperand(0);
3133     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM) {
3134       SDValue MoveOp = BitcastOp->getOperand(0);
3135       if (MoveOp->getOpcode() == ISD::TargetConstant &&
3136           cast<ConstantSDNode>(MoveOp)->getZExtValue() == 0) {
3137         return true;
3138       }
3139     }
3140   }
3141   return false;
3142 }
3143
3144 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3145 /// the given operands.
3146 SDValue
3147 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3148                              SDValue &ARMcc, SelectionDAG &DAG,
3149                              SDLoc dl) const {
3150   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3151     unsigned C = RHSC->getZExtValue();
3152     if (!isLegalICmpImmediate(C)) {
3153       // Constant does not fit, try adjusting it by one?
3154       switch (CC) {
3155       default: break;
3156       case ISD::SETLT:
3157       case ISD::SETGE:
3158         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3159           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3160           RHS = DAG.getConstant(C-1, MVT::i32);
3161         }
3162         break;
3163       case ISD::SETULT:
3164       case ISD::SETUGE:
3165         if (C != 0 && isLegalICmpImmediate(C-1)) {
3166           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3167           RHS = DAG.getConstant(C-1, MVT::i32);
3168         }
3169         break;
3170       case ISD::SETLE:
3171       case ISD::SETGT:
3172         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3173           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3174           RHS = DAG.getConstant(C+1, MVT::i32);
3175         }
3176         break;
3177       case ISD::SETULE:
3178       case ISD::SETUGT:
3179         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3180           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3181           RHS = DAG.getConstant(C+1, MVT::i32);
3182         }
3183         break;
3184       }
3185     }
3186   }
3187
3188   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3189   ARMISD::NodeType CompareType;
3190   switch (CondCode) {
3191   default:
3192     CompareType = ARMISD::CMP;
3193     break;
3194   case ARMCC::EQ:
3195   case ARMCC::NE:
3196     // Uses only Z Flag
3197     CompareType = ARMISD::CMPZ;
3198     break;
3199   }
3200   ARMcc = DAG.getConstant(CondCode, MVT::i32);
3201   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3202 }
3203
3204 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3205 SDValue
3206 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3207                              SDLoc dl) const {
3208   assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3209   SDValue Cmp;
3210   if (!isFloatingPointZero(RHS))
3211     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3212   else
3213     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3214   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3215 }
3216
3217 /// duplicateCmp - Glue values can have only one use, so this function
3218 /// duplicates a comparison node.
3219 SDValue
3220 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3221   unsigned Opc = Cmp.getOpcode();
3222   SDLoc DL(Cmp);
3223   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3224     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3225
3226   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3227   Cmp = Cmp.getOperand(0);
3228   Opc = Cmp.getOpcode();
3229   if (Opc == ARMISD::CMPFP)
3230     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3231   else {
3232     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3233     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3234   }
3235   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3236 }
3237
3238 std::pair<SDValue, SDValue>
3239 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3240                                  SDValue &ARMcc) const {
3241   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3242
3243   SDValue Value, OverflowCmp;
3244   SDValue LHS = Op.getOperand(0);
3245   SDValue RHS = Op.getOperand(1);
3246
3247
3248   // FIXME: We are currently always generating CMPs because we don't support
3249   // generating CMN through the backend. This is not as good as the natural
3250   // CMP case because it causes a register dependency and cannot be folded
3251   // later.
3252
3253   switch (Op.getOpcode()) {
3254   default:
3255     llvm_unreachable("Unknown overflow instruction!");
3256   case ISD::SADDO:
3257     ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3258     Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3259     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3260     break;
3261   case ISD::UADDO:
3262     ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3263     Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3264     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3265     break;
3266   case ISD::SSUBO:
3267     ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3268     Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3269     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3270     break;
3271   case ISD::USUBO:
3272     ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3273     Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3274     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3275     break;
3276   } // switch (...)
3277
3278   return std::make_pair(Value, OverflowCmp);
3279 }
3280
3281
3282 SDValue
3283 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3284   // Let legalize expand this if it isn't a legal type yet.
3285   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3286     return SDValue();
3287
3288   SDValue Value, OverflowCmp;
3289   SDValue ARMcc;
3290   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3291   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3292   // We use 0 and 1 as false and true values.
3293   SDValue TVal = DAG.getConstant(1, MVT::i32);
3294   SDValue FVal = DAG.getConstant(0, MVT::i32);
3295   EVT VT = Op.getValueType();
3296
3297   SDValue Overflow = DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, TVal, FVal,
3298                                  ARMcc, CCR, OverflowCmp);
3299
3300   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3301   return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), VTs, Value, Overflow);
3302 }
3303
3304
3305 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3306   SDValue Cond = Op.getOperand(0);
3307   SDValue SelectTrue = Op.getOperand(1);
3308   SDValue SelectFalse = Op.getOperand(2);
3309   SDLoc dl(Op);
3310   unsigned Opc = Cond.getOpcode();
3311
3312   if (Cond.getResNo() == 1 &&
3313       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3314        Opc == ISD::USUBO)) {
3315     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3316       return SDValue();
3317
3318     SDValue Value, OverflowCmp;
3319     SDValue ARMcc;
3320     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3321     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3322     EVT VT = Op.getValueType();
3323
3324     return getCMOV(SDLoc(Op), VT, SelectTrue, SelectFalse, ARMcc, CCR,
3325                    OverflowCmp, DAG);
3326   }
3327
3328   // Convert:
3329   //
3330   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3331   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3332   //
3333   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3334     const ConstantSDNode *CMOVTrue =
3335       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3336     const ConstantSDNode *CMOVFalse =
3337       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3338
3339     if (CMOVTrue && CMOVFalse) {
3340       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3341       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3342
3343       SDValue True;
3344       SDValue False;
3345       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3346         True = SelectTrue;
3347         False = SelectFalse;
3348       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3349         True = SelectFalse;
3350         False = SelectTrue;
3351       }
3352
3353       if (True.getNode() && False.getNode()) {
3354         EVT VT = Op.getValueType();
3355         SDValue ARMcc = Cond.getOperand(2);
3356         SDValue CCR = Cond.getOperand(3);
3357         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3358         assert(True.getValueType() == VT);
3359         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3360       }
3361     }
3362   }
3363
3364   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3365   // undefined bits before doing a full-word comparison with zero.
3366   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3367                      DAG.getConstant(1, Cond.getValueType()));
3368
3369   return DAG.getSelectCC(dl, Cond,
3370                          DAG.getConstant(0, Cond.getValueType()),
3371                          SelectTrue, SelectFalse, ISD::SETNE);
3372 }
3373
3374 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3375   if (CC == ISD::SETNE)
3376     return ISD::SETEQ;
3377   return ISD::getSetCCInverse(CC, true);
3378 }
3379
3380 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3381                                  bool &swpCmpOps, bool &swpVselOps) {
3382   // Start by selecting the GE condition code for opcodes that return true for
3383   // 'equality'
3384   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3385       CC == ISD::SETULE)
3386     CondCode = ARMCC::GE;
3387
3388   // and GT for opcodes that return false for 'equality'.
3389   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3390            CC == ISD::SETULT)
3391     CondCode = ARMCC::GT;
3392
3393   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3394   // to swap the compare operands.
3395   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3396       CC == ISD::SETULT)
3397     swpCmpOps = true;
3398
3399   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3400   // If we have an unordered opcode, we need to swap the operands to the VSEL
3401   // instruction (effectively negating the condition).
3402   //
3403   // This also has the effect of swapping which one of 'less' or 'greater'
3404   // returns true, so we also swap the compare operands. It also switches
3405   // whether we return true for 'equality', so we compensate by picking the
3406   // opposite condition code to our original choice.
3407   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3408       CC == ISD::SETUGT) {
3409     swpCmpOps = !swpCmpOps;
3410     swpVselOps = !swpVselOps;
3411     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3412   }
3413
3414   // 'ordered' is 'anything but unordered', so use the VS condition code and
3415   // swap the VSEL operands.
3416   if (CC == ISD::SETO) {
3417     CondCode = ARMCC::VS;
3418     swpVselOps = true;
3419   }
3420
3421   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3422   // code and swap the VSEL operands.
3423   if (CC == ISD::SETUNE) {
3424     CondCode = ARMCC::EQ;
3425     swpVselOps = true;
3426   }
3427 }
3428
3429 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3430                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3431                                    SDValue Cmp, SelectionDAG &DAG) const {
3432   if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3433     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3434                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3435     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3436                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3437
3438     SDValue TrueLow = TrueVal.getValue(0);
3439     SDValue TrueHigh = TrueVal.getValue(1);
3440     SDValue FalseLow = FalseVal.getValue(0);
3441     SDValue FalseHigh = FalseVal.getValue(1);
3442
3443     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3444                               ARMcc, CCR, Cmp);
3445     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3446                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
3447
3448     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3449   } else {
3450     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3451                        Cmp);
3452   }
3453 }
3454
3455 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3456   EVT VT = Op.getValueType();
3457   SDValue LHS = Op.getOperand(0);
3458   SDValue RHS = Op.getOperand(1);
3459   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3460   SDValue TrueVal = Op.getOperand(2);
3461   SDValue FalseVal = Op.getOperand(3);
3462   SDLoc dl(Op);
3463
3464   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3465     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3466                                                     dl);
3467
3468     // If softenSetCCOperands only returned one value, we should compare it to
3469     // zero.
3470     if (!RHS.getNode()) {
3471       RHS = DAG.getConstant(0, LHS.getValueType());
3472       CC = ISD::SETNE;
3473     }
3474   }
3475
3476   if (LHS.getValueType() == MVT::i32) {
3477     // Try to generate VSEL on ARMv8.
3478     // The VSEL instruction can't use all the usual ARM condition
3479     // codes: it only has two bits to select the condition code, so it's
3480     // constrained to use only GE, GT, VS and EQ.
3481     //
3482     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3483     // swap the operands of the previous compare instruction (effectively
3484     // inverting the compare condition, swapping 'less' and 'greater') and
3485     // sometimes need to swap the operands to the VSEL (which inverts the
3486     // condition in the sense of firing whenever the previous condition didn't)
3487     if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3488                                     TrueVal.getValueType() == MVT::f64)) {
3489       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3490       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3491           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3492         CC = getInverseCCForVSEL(CC);
3493         std::swap(TrueVal, FalseVal);
3494       }
3495     }
3496
3497     SDValue ARMcc;
3498     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3499     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3500     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3501   }
3502
3503   ARMCC::CondCodes CondCode, CondCode2;
3504   FPCCToARMCC(CC, CondCode, CondCode2);
3505
3506   // Try to generate VSEL on ARMv8.
3507   if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3508                                   TrueVal.getValueType() == MVT::f64)) {
3509     // We can select VMAXNM/VMINNM from a compare followed by a select with the
3510     // same operands, as follows:
3511     //   c = fcmp [ogt, olt, ugt, ult] a, b
3512     //   select c, a, b
3513     // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3514     // handled differently than the original code sequence.
3515     if (getTargetMachine().Options.UnsafeFPMath) {
3516       if (LHS == TrueVal && RHS == FalseVal) {
3517         if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3518           return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3519         if (CC == ISD::SETOLT || CC == ISD::SETULT)
3520           return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3521       } else if (LHS == FalseVal && RHS == TrueVal) {
3522         if (CC == ISD::SETOLT || CC == ISD::SETULT)
3523           return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3524         if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3525           return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3526       }
3527     }
3528
3529     bool swpCmpOps = false;
3530     bool swpVselOps = false;
3531     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3532
3533     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3534         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3535       if (swpCmpOps)
3536         std::swap(LHS, RHS);
3537       if (swpVselOps)
3538         std::swap(TrueVal, FalseVal);
3539     }
3540   }
3541
3542   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3543   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3544   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3545   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3546   if (CondCode2 != ARMCC::AL) {
3547     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3548     // FIXME: Needs another CMP because flag can have but one use.
3549     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3550     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3551   }
3552   return Result;
3553 }
3554
3555 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3556 /// to morph to an integer compare sequence.
3557 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3558                            const ARMSubtarget *Subtarget) {
3559   SDNode *N = Op.getNode();
3560   if (!N->hasOneUse())
3561     // Otherwise it requires moving the value from fp to integer registers.
3562     return false;
3563   if (!N->getNumValues())
3564     return false;
3565   EVT VT = Op.getValueType();
3566   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3567     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3568     // vmrs are very slow, e.g. cortex-a8.
3569     return false;
3570
3571   if (isFloatingPointZero(Op)) {
3572     SeenZero = true;
3573     return true;
3574   }
3575   return ISD::isNormalLoad(N);
3576 }
3577
3578 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3579   if (isFloatingPointZero(Op))
3580     return DAG.getConstant(0, MVT::i32);
3581
3582   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3583     return DAG.getLoad(MVT::i32, SDLoc(Op),
3584                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3585                        Ld->isVolatile(), Ld->isNonTemporal(),
3586                        Ld->isInvariant(), Ld->getAlignment());
3587
3588   llvm_unreachable("Unknown VFP cmp argument!");
3589 }
3590
3591 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3592                            SDValue &RetVal1, SDValue &RetVal2) {
3593   if (isFloatingPointZero(Op)) {
3594     RetVal1 = DAG.getConstant(0, MVT::i32);
3595     RetVal2 = DAG.getConstant(0, MVT::i32);
3596     return;
3597   }
3598
3599   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3600     SDValue Ptr = Ld->getBasePtr();
3601     RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3602                           Ld->getChain(), Ptr,
3603                           Ld->getPointerInfo(),
3604                           Ld->isVolatile(), Ld->isNonTemporal(),
3605                           Ld->isInvariant(), Ld->getAlignment());
3606
3607     EVT PtrType = Ptr.getValueType();
3608     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3609     SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3610                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
3611     RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3612                           Ld->getChain(), NewPtr,
3613                           Ld->getPointerInfo().getWithOffset(4),
3614                           Ld->isVolatile(), Ld->isNonTemporal(),
3615                           Ld->isInvariant(), NewAlign);
3616     return;
3617   }
3618
3619   llvm_unreachable("Unknown VFP cmp argument!");
3620 }
3621
3622 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3623 /// f32 and even f64 comparisons to integer ones.
3624 SDValue
3625 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3626   SDValue Chain = Op.getOperand(0);
3627   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3628   SDValue LHS = Op.getOperand(2);
3629   SDValue RHS = Op.getOperand(3);
3630   SDValue Dest = Op.getOperand(4);
3631   SDLoc dl(Op);
3632
3633   bool LHSSeenZero = false;
3634   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3635   bool RHSSeenZero = false;
3636   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3637   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3638     // If unsafe fp math optimization is enabled and there are no other uses of
3639     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3640     // to an integer comparison.
3641     if (CC == ISD::SETOEQ)
3642       CC = ISD::SETEQ;
3643     else if (CC == ISD::SETUNE)
3644       CC = ISD::SETNE;
3645
3646     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3647     SDValue ARMcc;
3648     if (LHS.getValueType() == MVT::f32) {
3649       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3650                         bitcastf32Toi32(LHS, DAG), Mask);
3651       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3652                         bitcastf32Toi32(RHS, DAG), Mask);
3653       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3654       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3655       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3656                          Chain, Dest, ARMcc, CCR, Cmp);
3657     }
3658
3659     SDValue LHS1, LHS2;
3660     SDValue RHS1, RHS2;
3661     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3662     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3663     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3664     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3665     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3666     ARMcc = DAG.getConstant(CondCode, MVT::i32);
3667     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3668     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3669     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3670   }
3671
3672   return SDValue();
3673 }
3674
3675 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3676   SDValue Chain = Op.getOperand(0);
3677   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3678   SDValue LHS = Op.getOperand(2);
3679   SDValue RHS = Op.getOperand(3);
3680   SDValue Dest = Op.getOperand(4);
3681   SDLoc dl(Op);
3682
3683   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3684     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3685                                                     dl);
3686
3687     // If softenSetCCOperands only returned one value, we should compare it to
3688     // zero.
3689     if (!RHS.getNode()) {
3690       RHS = DAG.getConstant(0, LHS.getValueType());
3691       CC = ISD::SETNE;
3692     }
3693   }
3694
3695   if (LHS.getValueType() == MVT::i32) {
3696     SDValue ARMcc;
3697     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3698     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3699     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3700                        Chain, Dest, ARMcc, CCR, Cmp);
3701   }
3702
3703   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3704
3705   if (getTargetMachine().Options.UnsafeFPMath &&
3706       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3707        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3708     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3709     if (Result.getNode())
3710       return Result;
3711   }
3712
3713   ARMCC::CondCodes CondCode, CondCode2;
3714   FPCCToARMCC(CC, CondCode, CondCode2);
3715
3716   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3717   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3718   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3719   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3720   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3721   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3722   if (CondCode2 != ARMCC::AL) {
3723     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3724     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3725     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3726   }
3727   return Res;
3728 }
3729
3730 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3731   SDValue Chain = Op.getOperand(0);
3732   SDValue Table = Op.getOperand(1);
3733   SDValue Index = Op.getOperand(2);
3734   SDLoc dl(Op);
3735
3736   EVT PTy = getPointerTy();
3737   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3738   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3739   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3740   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3741   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3742   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3743   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3744   if (Subtarget->isThumb2()) {
3745     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3746     // which does another jump to the destination. This also makes it easier
3747     // to translate it to TBB / TBH later.
3748     // FIXME: This might not work if the function is extremely large.
3749     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3750                        Addr, Op.getOperand(2), JTI, UId);
3751   }
3752   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3753     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3754                        MachinePointerInfo::getJumpTable(),
3755                        false, false, false, 0);
3756     Chain = Addr.getValue(1);
3757     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3758     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3759   } else {
3760     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3761                        MachinePointerInfo::getJumpTable(),
3762                        false, false, false, 0);
3763     Chain = Addr.getValue(1);
3764     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3765   }
3766 }
3767
3768 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3769   EVT VT = Op.getValueType();
3770   SDLoc dl(Op);
3771
3772   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3773     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3774       return Op;
3775     return DAG.UnrollVectorOp(Op.getNode());
3776   }
3777
3778   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3779          "Invalid type for custom lowering!");
3780   if (VT != MVT::v4i16)
3781     return DAG.UnrollVectorOp(Op.getNode());
3782
3783   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3784   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3785 }
3786
3787 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3788   EVT VT = Op.getValueType();
3789   if (VT.isVector())
3790     return LowerVectorFP_TO_INT(Op, DAG);
3791   if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3792     RTLIB::Libcall LC;
3793     if (Op.getOpcode() == ISD::FP_TO_SINT)
3794       LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
3795                               Op.getValueType());
3796     else
3797       LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
3798                               Op.getValueType());
3799     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3800                        /*isSigned*/ false, SDLoc(Op)).first;
3801   }
3802
3803   return Op;
3804 }
3805
3806 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3807   EVT VT = Op.getValueType();
3808   SDLoc dl(Op);
3809
3810   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3811     if (VT.getVectorElementType() == MVT::f32)
3812       return Op;
3813     return DAG.UnrollVectorOp(Op.getNode());
3814   }
3815
3816   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3817          "Invalid type for custom lowering!");
3818   if (VT != MVT::v4f32)
3819     return DAG.UnrollVectorOp(Op.getNode());
3820
3821   unsigned CastOpc;
3822   unsigned Opc;
3823   switch (Op.getOpcode()) {
3824   default: llvm_unreachable("Invalid opcode!");
3825   case ISD::SINT_TO_FP:
3826     CastOpc = ISD::SIGN_EXTEND;
3827     Opc = ISD::SINT_TO_FP;
3828     break;
3829   case ISD::UINT_TO_FP:
3830     CastOpc = ISD::ZERO_EXTEND;
3831     Opc = ISD::UINT_TO_FP;
3832     break;
3833   }
3834
3835   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3836   return DAG.getNode(Opc, dl, VT, Op);
3837 }
3838
3839 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
3840   EVT VT = Op.getValueType();
3841   if (VT.isVector())
3842     return LowerVectorINT_TO_FP(Op, DAG);
3843   if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
3844     RTLIB::Libcall LC;
3845     if (Op.getOpcode() == ISD::SINT_TO_FP)
3846       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
3847                               Op.getValueType());
3848     else
3849       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
3850                               Op.getValueType());
3851     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3852                        /*isSigned*/ false, SDLoc(Op)).first;
3853   }
3854
3855   return Op;
3856 }
3857
3858 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3859   // Implement fcopysign with a fabs and a conditional fneg.
3860   SDValue Tmp0 = Op.getOperand(0);
3861   SDValue Tmp1 = Op.getOperand(1);
3862   SDLoc dl(Op);
3863   EVT VT = Op.getValueType();
3864   EVT SrcVT = Tmp1.getValueType();
3865   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3866     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3867   bool UseNEON = !InGPR && Subtarget->hasNEON();
3868
3869   if (UseNEON) {
3870     // Use VBSL to copy the sign bit.
3871     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3872     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3873                                DAG.getTargetConstant(EncodedVal, MVT::i32));
3874     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3875     if (VT == MVT::f64)
3876       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3877                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3878                          DAG.getConstant(32, MVT::i32));
3879     else /*if (VT == MVT::f32)*/
3880       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3881     if (SrcVT == MVT::f32) {
3882       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3883       if (VT == MVT::f64)
3884         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3885                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3886                            DAG.getConstant(32, MVT::i32));
3887     } else if (VT == MVT::f32)
3888       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3889                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3890                          DAG.getConstant(32, MVT::i32));
3891     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3892     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3893
3894     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3895                                             MVT::i32);
3896     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3897     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3898                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3899
3900     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3901                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3902                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3903     if (VT == MVT::f32) {
3904       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3905       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3906                         DAG.getConstant(0, MVT::i32));
3907     } else {
3908       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3909     }
3910
3911     return Res;
3912   }
3913
3914   // Bitcast operand 1 to i32.
3915   if (SrcVT == MVT::f64)
3916     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3917                        Tmp1).getValue(1);
3918   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3919
3920   // Or in the signbit with integer operations.
3921   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3922   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3923   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3924   if (VT == MVT::f32) {
3925     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3926                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3927     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3928                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3929   }
3930
3931   // f64: Or the high part with signbit and then combine two parts.
3932   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3933                      Tmp0);
3934   SDValue Lo = Tmp0.getValue(0);
3935   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3936   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3937   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3938 }
3939
3940 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3941   MachineFunction &MF = DAG.getMachineFunction();
3942   MachineFrameInfo *MFI = MF.getFrameInfo();
3943   MFI->setReturnAddressIsTaken(true);
3944
3945   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3946     return SDValue();
3947
3948   EVT VT = Op.getValueType();
3949   SDLoc dl(Op);
3950   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3951   if (Depth) {
3952     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3953     SDValue Offset = DAG.getConstant(4, MVT::i32);
3954     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3955                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3956                        MachinePointerInfo(), false, false, false, 0);
3957   }
3958
3959   // Return LR, which contains the return address. Mark it an implicit live-in.
3960   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3961   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3962 }
3963
3964 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3965   const ARMBaseRegisterInfo &ARI =
3966     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
3967   MachineFunction &MF = DAG.getMachineFunction();
3968   MachineFrameInfo *MFI = MF.getFrameInfo();
3969   MFI->setFrameAddressIsTaken(true);
3970
3971   EVT VT = Op.getValueType();
3972   SDLoc dl(Op);  // FIXME probably not meaningful
3973   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3974   unsigned FrameReg = ARI.getFrameRegister(MF);
3975   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3976   while (Depth--)
3977     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3978                             MachinePointerInfo(),
3979                             false, false, false, 0);
3980   return FrameAddr;
3981 }
3982
3983 // FIXME? Maybe this could be a TableGen attribute on some registers and
3984 // this table could be generated automatically from RegInfo.
3985 unsigned ARMTargetLowering::getRegisterByName(const char* RegName,
3986                                               EVT VT) const {
3987   unsigned Reg = StringSwitch<unsigned>(RegName)
3988                        .Case("sp", ARM::SP)
3989                        .Default(0);
3990   if (Reg)
3991     return Reg;
3992   report_fatal_error("Invalid register name global variable");
3993 }
3994
3995 /// ExpandBITCAST - If the target supports VFP, this function is called to
3996 /// expand a bit convert where either the source or destination type is i64 to
3997 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
3998 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3999 /// vectors), since the legalizer won't know what to do with that.
4000 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4001   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4002   SDLoc dl(N);
4003   SDValue Op = N->getOperand(0);
4004
4005   // This function is only supposed to be called for i64 types, either as the
4006   // source or destination of the bit convert.
4007   EVT SrcVT = Op.getValueType();
4008   EVT DstVT = N->getValueType(0);
4009   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4010          "ExpandBITCAST called for non-i64 type");
4011
4012   // Turn i64->f64 into VMOVDRR.
4013   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4014     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4015                              DAG.getConstant(0, MVT::i32));
4016     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4017                              DAG.getConstant(1, MVT::i32));
4018     return DAG.getNode(ISD::BITCAST, dl, DstVT,
4019                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4020   }
4021
4022   // Turn f64->i64 into VMOVRRD.
4023   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4024     SDValue Cvt;
4025     if (TLI.isBigEndian() && SrcVT.isVector() &&
4026         SrcVT.getVectorNumElements() > 1)
4027       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4028                         DAG.getVTList(MVT::i32, MVT::i32),
4029                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4030     else
4031       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4032                         DAG.getVTList(MVT::i32, MVT::i32), Op);
4033     // Merge the pieces into a single i64 value.
4034     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4035   }
4036
4037   return SDValue();
4038 }
4039
4040 /// getZeroVector - Returns a vector of specified type with all zero elements.
4041 /// Zero vectors are used to represent vector negation and in those cases
4042 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
4043 /// not support i64 elements, so sometimes the zero vectors will need to be
4044 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
4045 /// zero vector.
4046 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4047   assert(VT.isVector() && "Expected a vector type");
4048   // The canonical modified immediate encoding of a zero vector is....0!
4049   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
4050   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4051   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4052   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4053 }
4054
4055 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4056 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4057 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4058                                                 SelectionDAG &DAG) const {
4059   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4060   EVT VT = Op.getValueType();
4061   unsigned VTBits = VT.getSizeInBits();
4062   SDLoc dl(Op);
4063   SDValue ShOpLo = Op.getOperand(0);
4064   SDValue ShOpHi = Op.getOperand(1);
4065   SDValue ShAmt  = Op.getOperand(2);
4066   SDValue ARMcc;
4067   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4068
4069   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4070
4071   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4072                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
4073   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4074   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4075                                    DAG.getConstant(VTBits, MVT::i32));
4076   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4077   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4078   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4079
4080   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4081   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4082                           ARMcc, DAG, dl);
4083   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4084   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4085                            CCR, Cmp);
4086
4087   SDValue Ops[2] = { Lo, Hi };
4088   return DAG.getMergeValues(Ops, dl);
4089 }
4090
4091 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4092 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4093 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4094                                                SelectionDAG &DAG) const {
4095   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4096   EVT VT = Op.getValueType();
4097   unsigned VTBits = VT.getSizeInBits();
4098   SDLoc dl(Op);
4099   SDValue ShOpLo = Op.getOperand(0);
4100   SDValue ShOpHi = Op.getOperand(1);
4101   SDValue ShAmt  = Op.getOperand(2);
4102   SDValue ARMcc;
4103
4104   assert(Op.getOpcode() == ISD::SHL_PARTS);
4105   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4106                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
4107   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4108   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4109                                    DAG.getConstant(VTBits, MVT::i32));
4110   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4111   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4112
4113   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4114   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4115   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4116                           ARMcc, DAG, dl);
4117   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4118   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4119                            CCR, Cmp);
4120
4121   SDValue Ops[2] = { Lo, Hi };
4122   return DAG.getMergeValues(Ops, dl);
4123 }
4124
4125 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4126                                             SelectionDAG &DAG) const {
4127   // The rounding mode is in bits 23:22 of the FPSCR.
4128   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4129   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4130   // so that the shift + and get folded into a bitfield extract.
4131   SDLoc dl(Op);
4132   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4133                               DAG.getConstant(Intrinsic::arm_get_fpscr,
4134                                               MVT::i32));
4135   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4136                                   DAG.getConstant(1U << 22, MVT::i32));
4137   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4138                               DAG.getConstant(22, MVT::i32));
4139   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4140                      DAG.getConstant(3, MVT::i32));
4141 }
4142
4143 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4144                          const ARMSubtarget *ST) {
4145   EVT VT = N->getValueType(0);
4146   SDLoc dl(N);
4147
4148   if (!ST->hasV6T2Ops())
4149     return SDValue();
4150
4151   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4152   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4153 }
4154
4155 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4156 /// for each 16-bit element from operand, repeated.  The basic idea is to
4157 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4158 ///
4159 /// Trace for v4i16:
4160 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
4161 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4162 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4163 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4164 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
4165 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
4166 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4167 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
4168 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4169   EVT VT = N->getValueType(0);
4170   SDLoc DL(N);
4171
4172   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4173   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4174   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4175   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4176   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4177   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4178 }
4179
4180 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4181 /// bit-count for each 16-bit element from the operand.  We need slightly
4182 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4183 /// 64/128-bit registers.
4184 ///
4185 /// Trace for v4i16:
4186 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
4187 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4188 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
4189 /// v4i16:Extracted = [k0    k1    k2    k3    ]
4190 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4191   EVT VT = N->getValueType(0);
4192   SDLoc DL(N);
4193
4194   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4195   if (VT.is64BitVector()) {
4196     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4197     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4198                        DAG.getIntPtrConstant(0));
4199   } else {
4200     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4201                                     BitCounts, DAG.getIntPtrConstant(0));
4202     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4203   }
4204 }
4205
4206 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4207 /// bit-count for each 32-bit element from the operand.  The idea here is
4208 /// to split the vector into 16-bit elements, leverage the 16-bit count
4209 /// routine, and then combine the results.
4210 ///
4211 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4212 /// input    = [v0    v1    ] (vi: 32-bit elements)
4213 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4214 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4215 /// vrev: N0 = [k1 k0 k3 k2 ]
4216 ///            [k0 k1 k2 k3 ]
4217 ///       N1 =+[k1 k0 k3 k2 ]
4218 ///            [k0 k2 k1 k3 ]
4219 ///       N2 =+[k1 k3 k0 k2 ]
4220 ///            [k0    k2    k1    k3    ]
4221 /// Extended =+[k1    k3    k0    k2    ]
4222 ///            [k0    k2    ]
4223 /// Extracted=+[k1    k3    ]
4224 ///
4225 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4226   EVT VT = N->getValueType(0);
4227   SDLoc DL(N);
4228
4229   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4230
4231   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4232   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4233   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4234   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4235   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4236
4237   if (VT.is64BitVector()) {
4238     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4239     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4240                        DAG.getIntPtrConstant(0));
4241   } else {
4242     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4243                                     DAG.getIntPtrConstant(0));
4244     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4245   }
4246 }
4247
4248 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4249                           const ARMSubtarget *ST) {
4250   EVT VT = N->getValueType(0);
4251
4252   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4253   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4254           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4255          "Unexpected type for custom ctpop lowering");
4256
4257   if (VT.getVectorElementType() == MVT::i32)
4258     return lowerCTPOP32BitElements(N, DAG);
4259   else
4260     return lowerCTPOP16BitElements(N, DAG);
4261 }
4262
4263 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4264                           const ARMSubtarget *ST) {
4265   EVT VT = N->getValueType(0);
4266   SDLoc dl(N);
4267
4268   if (!VT.isVector())
4269     return SDValue();
4270
4271   // Lower vector shifts on NEON to use VSHL.
4272   assert(ST->hasNEON() && "unexpected vector shift");
4273
4274   // Left shifts translate directly to the vshiftu intrinsic.
4275   if (N->getOpcode() == ISD::SHL)
4276     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4277                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4278                        N->getOperand(0), N->getOperand(1));
4279
4280   assert((N->getOpcode() == ISD::SRA ||
4281           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4282
4283   // NEON uses the same intrinsics for both left and right shifts.  For
4284   // right shifts, the shift amounts are negative, so negate the vector of
4285   // shift amounts.
4286   EVT ShiftVT = N->getOperand(1).getValueType();
4287   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4288                                      getZeroVector(ShiftVT, DAG, dl),
4289                                      N->getOperand(1));
4290   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4291                              Intrinsic::arm_neon_vshifts :
4292                              Intrinsic::arm_neon_vshiftu);
4293   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4294                      DAG.getConstant(vshiftInt, MVT::i32),
4295                      N->getOperand(0), NegatedCount);
4296 }
4297
4298 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4299                                 const ARMSubtarget *ST) {
4300   EVT VT = N->getValueType(0);
4301   SDLoc dl(N);
4302
4303   // We can get here for a node like i32 = ISD::SHL i32, i64
4304   if (VT != MVT::i64)
4305     return SDValue();
4306
4307   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4308          "Unknown shift to lower!");
4309
4310   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4311   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4312       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4313     return SDValue();
4314
4315   // If we are in thumb mode, we don't have RRX.
4316   if (ST->isThumb1Only()) return SDValue();
4317
4318   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4319   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4320                            DAG.getConstant(0, MVT::i32));
4321   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4322                            DAG.getConstant(1, MVT::i32));
4323
4324   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4325   // captures the result into a carry flag.
4326   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4327   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4328
4329   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4330   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4331
4332   // Merge the pieces into a single i64 value.
4333  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4334 }
4335
4336 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4337   SDValue TmpOp0, TmpOp1;
4338   bool Invert = false;
4339   bool Swap = false;
4340   unsigned Opc = 0;
4341
4342   SDValue Op0 = Op.getOperand(0);
4343   SDValue Op1 = Op.getOperand(1);
4344   SDValue CC = Op.getOperand(2);
4345   EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
4346   EVT VT = Op.getValueType();
4347   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4348   SDLoc dl(Op);
4349
4350   if (Op1.getValueType().isFloatingPoint()) {
4351     switch (SetCCOpcode) {
4352     default: llvm_unreachable("Illegal FP comparison");
4353     case ISD::SETUNE:
4354     case ISD::SETNE:  Invert = true; // Fallthrough
4355     case ISD::SETOEQ:
4356     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4357     case ISD::SETOLT:
4358     case ISD::SETLT: Swap = true; // Fallthrough
4359     case ISD::SETOGT:
4360     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4361     case ISD::SETOLE:
4362     case ISD::SETLE:  Swap = true; // Fallthrough
4363     case ISD::SETOGE:
4364     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4365     case ISD::SETUGE: Swap = true; // Fallthrough
4366     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4367     case ISD::SETUGT: Swap = true; // Fallthrough
4368     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4369     case ISD::SETUEQ: Invert = true; // Fallthrough
4370     case ISD::SETONE:
4371       // Expand this to (OLT | OGT).
4372       TmpOp0 = Op0;
4373       TmpOp1 = Op1;
4374       Opc = ISD::OR;
4375       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4376       Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
4377       break;
4378     case ISD::SETUO: Invert = true; // Fallthrough
4379     case ISD::SETO:
4380       // Expand this to (OLT | OGE).
4381       TmpOp0 = Op0;
4382       TmpOp1 = Op1;
4383       Opc = ISD::OR;
4384       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4385       Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
4386       break;
4387     }
4388   } else {
4389     // Integer comparisons.
4390     switch (SetCCOpcode) {
4391     default: llvm_unreachable("Illegal integer comparison");
4392     case ISD::SETNE:  Invert = true;
4393     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4394     case ISD::SETLT:  Swap = true;
4395     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4396     case ISD::SETLE:  Swap = true;
4397     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4398     case ISD::SETULT: Swap = true;
4399     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4400     case ISD::SETULE: Swap = true;
4401     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4402     }
4403
4404     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4405     if (Opc == ARMISD::VCEQ) {
4406
4407       SDValue AndOp;
4408       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4409         AndOp = Op0;
4410       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4411         AndOp = Op1;
4412
4413       // Ignore bitconvert.
4414       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4415         AndOp = AndOp.getOperand(0);
4416
4417       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4418         Opc = ARMISD::VTST;
4419         Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
4420         Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
4421         Invert = !Invert;
4422       }
4423     }
4424   }
4425
4426   if (Swap)
4427     std::swap(Op0, Op1);
4428
4429   // If one of the operands is a constant vector zero, attempt to fold the
4430   // comparison to a specialized compare-against-zero form.
4431   SDValue SingleOp;
4432   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4433     SingleOp = Op0;
4434   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4435     if (Opc == ARMISD::VCGE)
4436       Opc = ARMISD::VCLEZ;
4437     else if (Opc == ARMISD::VCGT)
4438       Opc = ARMISD::VCLTZ;
4439     SingleOp = Op1;
4440   }
4441
4442   SDValue Result;
4443   if (SingleOp.getNode()) {
4444     switch (Opc) {
4445     case ARMISD::VCEQ:
4446       Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
4447     case ARMISD::VCGE:
4448       Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
4449     case ARMISD::VCLEZ:
4450       Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
4451     case ARMISD::VCGT:
4452       Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
4453     case ARMISD::VCLTZ:
4454       Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
4455     default:
4456       Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4457     }
4458   } else {
4459      Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4460   }
4461
4462   Result = DAG.getSExtOrTrunc(Result, dl, VT);
4463
4464   if (Invert)
4465     Result = DAG.getNOT(dl, Result, VT);
4466
4467   return Result;
4468 }
4469
4470 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4471 /// valid vector constant for a NEON instruction with a "modified immediate"
4472 /// operand (e.g., VMOV).  If so, return the encoded value.
4473 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4474                                  unsigned SplatBitSize, SelectionDAG &DAG,
4475                                  EVT &VT, bool is128Bits, NEONModImmType type) {
4476   unsigned OpCmode, Imm;
4477
4478   // SplatBitSize is set to the smallest size that splats the vector, so a
4479   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4480   // immediate instructions others than VMOV do not support the 8-bit encoding
4481   // of a zero vector, and the default encoding of zero is supposed to be the
4482   // 32-bit version.
4483   if (SplatBits == 0)
4484     SplatBitSize = 32;
4485
4486   switch (SplatBitSize) {
4487   case 8:
4488     if (type != VMOVModImm)
4489       return SDValue();
4490     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4491     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4492     OpCmode = 0xe;
4493     Imm = SplatBits;
4494     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4495     break;
4496
4497   case 16:
4498     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4499     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4500     if ((SplatBits & ~0xff) == 0) {
4501       // Value = 0x00nn: Op=x, Cmode=100x.
4502       OpCmode = 0x8;
4503       Imm = SplatBits;
4504       break;
4505     }
4506     if ((SplatBits & ~0xff00) == 0) {
4507       // Value = 0xnn00: Op=x, Cmode=101x.
4508       OpCmode = 0xa;
4509       Imm = SplatBits >> 8;
4510       break;
4511     }
4512     return SDValue();
4513
4514   case 32:
4515     // NEON's 32-bit VMOV supports splat values where:
4516     // * only one byte is nonzero, or
4517     // * the least significant byte is 0xff and the second byte is nonzero, or
4518     // * the least significant 2 bytes are 0xff and the third is nonzero.
4519     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4520     if ((SplatBits & ~0xff) == 0) {
4521       // Value = 0x000000nn: Op=x, Cmode=000x.
4522       OpCmode = 0;
4523       Imm = SplatBits;
4524       break;
4525     }
4526     if ((SplatBits & ~0xff00) == 0) {
4527       // Value = 0x0000nn00: Op=x, Cmode=001x.
4528       OpCmode = 0x2;
4529       Imm = SplatBits >> 8;
4530       break;
4531     }
4532     if ((SplatBits & ~0xff0000) == 0) {
4533       // Value = 0x00nn0000: Op=x, Cmode=010x.
4534       OpCmode = 0x4;
4535       Imm = SplatBits >> 16;
4536       break;
4537     }
4538     if ((SplatBits & ~0xff000000) == 0) {
4539       // Value = 0xnn000000: Op=x, Cmode=011x.
4540       OpCmode = 0x6;
4541       Imm = SplatBits >> 24;
4542       break;
4543     }
4544
4545     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4546     if (type == OtherModImm) return SDValue();
4547
4548     if ((SplatBits & ~0xffff) == 0 &&
4549         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4550       // Value = 0x0000nnff: Op=x, Cmode=1100.
4551       OpCmode = 0xc;
4552       Imm = SplatBits >> 8;
4553       break;
4554     }
4555
4556     if ((SplatBits & ~0xffffff) == 0 &&
4557         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4558       // Value = 0x00nnffff: Op=x, Cmode=1101.
4559       OpCmode = 0xd;
4560       Imm = SplatBits >> 16;
4561       break;
4562     }
4563
4564     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4565     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4566     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4567     // and fall through here to test for a valid 64-bit splat.  But, then the
4568     // caller would also need to check and handle the change in size.
4569     return SDValue();
4570
4571   case 64: {
4572     if (type != VMOVModImm)
4573       return SDValue();
4574     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4575     uint64_t BitMask = 0xff;
4576     uint64_t Val = 0;
4577     unsigned ImmMask = 1;
4578     Imm = 0;
4579     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4580       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4581         Val |= BitMask;
4582         Imm |= ImmMask;
4583       } else if ((SplatBits & BitMask) != 0) {
4584         return SDValue();
4585       }
4586       BitMask <<= 8;
4587       ImmMask <<= 1;
4588     }
4589
4590     if (DAG.getTargetLoweringInfo().isBigEndian())
4591       // swap higher and lower 32 bit word
4592       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4593
4594     // Op=1, Cmode=1110.
4595     OpCmode = 0x1e;
4596     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4597     break;
4598   }
4599
4600   default:
4601     llvm_unreachable("unexpected size for isNEONModifiedImm");
4602   }
4603
4604   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4605   return DAG.getTargetConstant(EncodedVal, MVT::i32);
4606 }
4607
4608 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4609                                            const ARMSubtarget *ST) const {
4610   if (!ST->hasVFP3())
4611     return SDValue();
4612
4613   bool IsDouble = Op.getValueType() == MVT::f64;
4614   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4615
4616   // Use the default (constant pool) lowering for double constants when we have
4617   // an SP-only FPU
4618   if (IsDouble && Subtarget->isFPOnlySP())
4619     return SDValue();
4620
4621   // Try splatting with a VMOV.f32...
4622   APFloat FPVal = CFP->getValueAPF();
4623   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4624
4625   if (ImmVal != -1) {
4626     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4627       // We have code in place to select a valid ConstantFP already, no need to
4628       // do any mangling.
4629       return Op;
4630     }
4631
4632     // It's a float and we are trying to use NEON operations where
4633     // possible. Lower it to a splat followed by an extract.
4634     SDLoc DL(Op);
4635     SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4636     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4637                                       NewVal);
4638     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4639                        DAG.getConstant(0, MVT::i32));
4640   }
4641
4642   // The rest of our options are NEON only, make sure that's allowed before
4643   // proceeding..
4644   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4645     return SDValue();
4646
4647   EVT VMovVT;
4648   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4649
4650   // It wouldn't really be worth bothering for doubles except for one very
4651   // important value, which does happen to match: 0.0. So make sure we don't do
4652   // anything stupid.
4653   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4654     return SDValue();
4655
4656   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4657   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4658                                      false, VMOVModImm);
4659   if (NewVal != SDValue()) {
4660     SDLoc DL(Op);
4661     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4662                                       NewVal);
4663     if (IsDouble)
4664       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4665
4666     // It's a float: cast and extract a vector element.
4667     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4668                                        VecConstant);
4669     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4670                        DAG.getConstant(0, MVT::i32));
4671   }
4672
4673   // Finally, try a VMVN.i32
4674   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4675                              false, VMVNModImm);
4676   if (NewVal != SDValue()) {
4677     SDLoc DL(Op);
4678     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4679
4680     if (IsDouble)
4681       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4682
4683     // It's a float: cast and extract a vector element.
4684     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4685                                        VecConstant);
4686     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4687                        DAG.getConstant(0, MVT::i32));
4688   }
4689
4690   return SDValue();
4691 }
4692
4693 // check if an VEXT instruction can handle the shuffle mask when the
4694 // vector sources of the shuffle are the same.
4695 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4696   unsigned NumElts = VT.getVectorNumElements();
4697
4698   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4699   if (M[0] < 0)
4700     return false;
4701
4702   Imm = M[0];
4703
4704   // If this is a VEXT shuffle, the immediate value is the index of the first
4705   // element.  The other shuffle indices must be the successive elements after
4706   // the first one.
4707   unsigned ExpectedElt = Imm;
4708   for (unsigned i = 1; i < NumElts; ++i) {
4709     // Increment the expected index.  If it wraps around, just follow it
4710     // back to index zero and keep going.
4711     ++ExpectedElt;
4712     if (ExpectedElt == NumElts)
4713       ExpectedElt = 0;
4714
4715     if (M[i] < 0) continue; // ignore UNDEF indices
4716     if (ExpectedElt != static_cast<unsigned>(M[i]))
4717       return false;
4718   }
4719
4720   return true;
4721 }
4722
4723
4724 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4725                        bool &ReverseVEXT, unsigned &Imm) {
4726   unsigned NumElts = VT.getVectorNumElements();
4727   ReverseVEXT = false;
4728
4729   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4730   if (M[0] < 0)
4731     return false;
4732
4733   Imm = M[0];
4734
4735   // If this is a VEXT shuffle, the immediate value is the index of the first
4736   // element.  The other shuffle indices must be the successive elements after
4737   // the first one.
4738   unsigned ExpectedElt = Imm;
4739   for (unsigned i = 1; i < NumElts; ++i) {
4740     // Increment the expected index.  If it wraps around, it may still be
4741     // a VEXT but the source vectors must be swapped.
4742     ExpectedElt += 1;
4743     if (ExpectedElt == NumElts * 2) {
4744       ExpectedElt = 0;
4745       ReverseVEXT = true;
4746     }
4747
4748     if (M[i] < 0) continue; // ignore UNDEF indices
4749     if (ExpectedElt != static_cast<unsigned>(M[i]))
4750       return false;
4751   }
4752
4753   // Adjust the index value if the source operands will be swapped.
4754   if (ReverseVEXT)
4755     Imm -= NumElts;
4756
4757   return true;
4758 }
4759
4760 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4761 /// instruction with the specified blocksize.  (The order of the elements
4762 /// within each block of the vector is reversed.)
4763 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4764   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4765          "Only possible block sizes for VREV are: 16, 32, 64");
4766
4767   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4768   if (EltSz == 64)
4769     return false;
4770
4771   unsigned NumElts = VT.getVectorNumElements();
4772   unsigned BlockElts = M[0] + 1;
4773   // If the first shuffle index is UNDEF, be optimistic.
4774   if (M[0] < 0)
4775     BlockElts = BlockSize / EltSz;
4776
4777   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4778     return false;
4779
4780   for (unsigned i = 0; i < NumElts; ++i) {
4781     if (M[i] < 0) continue; // ignore UNDEF indices
4782     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4783       return false;
4784   }
4785
4786   return true;
4787 }
4788
4789 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4790   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4791   // range, then 0 is placed into the resulting vector. So pretty much any mask
4792   // of 8 elements can work here.
4793   return VT == MVT::v8i8 && M.size() == 8;
4794 }
4795
4796 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4797   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4798   if (EltSz == 64)
4799     return false;
4800
4801   unsigned NumElts = VT.getVectorNumElements();
4802   WhichResult = (M[0] == 0 ? 0 : 1);
4803   for (unsigned i = 0; i < NumElts; i += 2) {
4804     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4805         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4806       return false;
4807   }
4808   return true;
4809 }
4810
4811 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4812 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4813 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4814 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4815   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4816   if (EltSz == 64)
4817     return false;
4818
4819   unsigned NumElts = VT.getVectorNumElements();
4820   WhichResult = (M[0] == 0 ? 0 : 1);
4821   for (unsigned i = 0; i < NumElts; i += 2) {
4822     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4823         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4824       return false;
4825   }
4826   return true;
4827 }
4828
4829 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4830   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4831   if (EltSz == 64)
4832     return false;
4833
4834   unsigned NumElts = VT.getVectorNumElements();
4835   WhichResult = (M[0] == 0 ? 0 : 1);
4836   for (unsigned i = 0; i != NumElts; ++i) {
4837     if (M[i] < 0) continue; // ignore UNDEF indices
4838     if ((unsigned) M[i] != 2 * i + WhichResult)
4839       return false;
4840   }
4841
4842   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4843   if (VT.is64BitVector() && EltSz == 32)
4844     return false;
4845
4846   return true;
4847 }
4848
4849 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4850 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4851 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4852 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4853   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4854   if (EltSz == 64)
4855     return false;
4856
4857   unsigned Half = VT.getVectorNumElements() / 2;
4858   WhichResult = (M[0] == 0 ? 0 : 1);
4859   for (unsigned j = 0; j != 2; ++j) {
4860     unsigned Idx = WhichResult;
4861     for (unsigned i = 0; i != Half; ++i) {
4862       int MIdx = M[i + j * Half];
4863       if (MIdx >= 0 && (unsigned) MIdx != Idx)
4864         return false;
4865       Idx += 2;
4866     }
4867   }
4868
4869   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4870   if (VT.is64BitVector() && EltSz == 32)
4871     return false;
4872
4873   return true;
4874 }
4875
4876 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4877   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4878   if (EltSz == 64)
4879     return false;
4880
4881   unsigned NumElts = VT.getVectorNumElements();
4882   WhichResult = (M[0] == 0 ? 0 : 1);
4883   unsigned Idx = WhichResult * NumElts / 2;
4884   for (unsigned i = 0; i != NumElts; i += 2) {
4885     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4886         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4887       return false;
4888     Idx += 1;
4889   }
4890
4891   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4892   if (VT.is64BitVector() && EltSz == 32)
4893     return false;
4894
4895   return true;
4896 }
4897
4898 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4899 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4900 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4901 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4902   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4903   if (EltSz == 64)
4904     return false;
4905
4906   unsigned NumElts = VT.getVectorNumElements();
4907   WhichResult = (M[0] == 0 ? 0 : 1);
4908   unsigned Idx = WhichResult * NumElts / 2;
4909   for (unsigned i = 0; i != NumElts; i += 2) {
4910     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4911         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4912       return false;
4913     Idx += 1;
4914   }
4915
4916   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4917   if (VT.is64BitVector() && EltSz == 32)
4918     return false;
4919
4920   return true;
4921 }
4922
4923 /// \return true if this is a reverse operation on an vector.
4924 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4925   unsigned NumElts = VT.getVectorNumElements();
4926   // Make sure the mask has the right size.
4927   if (NumElts != M.size())
4928       return false;
4929
4930   // Look for <15, ..., 3, -1, 1, 0>.
4931   for (unsigned i = 0; i != NumElts; ++i)
4932     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4933       return false;
4934
4935   return true;
4936 }
4937
4938 // If N is an integer constant that can be moved into a register in one
4939 // instruction, return an SDValue of such a constant (will become a MOV
4940 // instruction).  Otherwise return null.
4941 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4942                                      const ARMSubtarget *ST, SDLoc dl) {
4943   uint64_t Val;
4944   if (!isa<ConstantSDNode>(N))
4945     return SDValue();
4946   Val = cast<ConstantSDNode>(N)->getZExtValue();
4947
4948   if (ST->isThumb1Only()) {
4949     if (Val <= 255 || ~Val <= 255)
4950       return DAG.getConstant(Val, MVT::i32);
4951   } else {
4952     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4953       return DAG.getConstant(Val, MVT::i32);
4954   }
4955   return SDValue();
4956 }
4957
4958 // If this is a case we can't handle, return null and let the default
4959 // expansion code take care of it.
4960 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4961                                              const ARMSubtarget *ST) const {
4962   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4963   SDLoc dl(Op);
4964   EVT VT = Op.getValueType();
4965
4966   APInt SplatBits, SplatUndef;
4967   unsigned SplatBitSize;
4968   bool HasAnyUndefs;
4969   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4970     if (SplatBitSize <= 64) {
4971       // Check if an immediate VMOV works.
4972       EVT VmovVT;
4973       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4974                                       SplatUndef.getZExtValue(), SplatBitSize,
4975                                       DAG, VmovVT, VT.is128BitVector(),
4976                                       VMOVModImm);
4977       if (Val.getNode()) {
4978         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4979         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4980       }
4981
4982       // Try an immediate VMVN.
4983       uint64_t NegatedImm = (~SplatBits).getZExtValue();
4984       Val = isNEONModifiedImm(NegatedImm,
4985                                       SplatUndef.getZExtValue(), SplatBitSize,
4986                                       DAG, VmovVT, VT.is128BitVector(),
4987                                       VMVNModImm);
4988       if (Val.getNode()) {
4989         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4990         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4991       }
4992
4993       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4994       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4995         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4996         if (ImmVal != -1) {
4997           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4998           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4999         }
5000       }
5001     }
5002   }
5003
5004   // Scan through the operands to see if only one value is used.
5005   //
5006   // As an optimisation, even if more than one value is used it may be more
5007   // profitable to splat with one value then change some lanes.
5008   //
5009   // Heuristically we decide to do this if the vector has a "dominant" value,
5010   // defined as splatted to more than half of the lanes.
5011   unsigned NumElts = VT.getVectorNumElements();
5012   bool isOnlyLowElement = true;
5013   bool usesOnlyOneValue = true;
5014   bool hasDominantValue = false;
5015   bool isConstant = true;
5016
5017   // Map of the number of times a particular SDValue appears in the
5018   // element list.
5019   DenseMap<SDValue, unsigned> ValueCounts;
5020   SDValue Value;
5021   for (unsigned i = 0; i < NumElts; ++i) {
5022     SDValue V = Op.getOperand(i);
5023     if (V.getOpcode() == ISD::UNDEF)
5024       continue;
5025     if (i > 0)
5026       isOnlyLowElement = false;
5027     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5028       isConstant = false;
5029
5030     ValueCounts.insert(std::make_pair(V, 0));
5031     unsigned &Count = ValueCounts[V];
5032
5033     // Is this value dominant? (takes up more than half of the lanes)
5034     if (++Count > (NumElts / 2)) {
5035       hasDominantValue = true;
5036       Value = V;
5037     }
5038   }
5039   if (ValueCounts.size() != 1)
5040     usesOnlyOneValue = false;
5041   if (!Value.getNode() && ValueCounts.size() > 0)
5042     Value = ValueCounts.begin()->first;
5043
5044   if (ValueCounts.size() == 0)
5045     return DAG.getUNDEF(VT);
5046
5047   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5048   // Keep going if we are hitting this case.
5049   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5050     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5051
5052   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5053
5054   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
5055   // i32 and try again.
5056   if (hasDominantValue && EltSize <= 32) {
5057     if (!isConstant) {
5058       SDValue N;
5059
5060       // If we are VDUPing a value that comes directly from a vector, that will
5061       // cause an unnecessary move to and from a GPR, where instead we could
5062       // just use VDUPLANE. We can only do this if the lane being extracted
5063       // is at a constant index, as the VDUP from lane instructions only have
5064       // constant-index forms.
5065       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5066           isa<ConstantSDNode>(Value->getOperand(1))) {
5067         // We need to create a new undef vector to use for the VDUPLANE if the
5068         // size of the vector from which we get the value is different than the
5069         // size of the vector that we need to create. We will insert the element
5070         // such that the register coalescer will remove unnecessary copies.
5071         if (VT != Value->getOperand(0).getValueType()) {
5072           ConstantSDNode *constIndex;
5073           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5074           assert(constIndex && "The index is not a constant!");
5075           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5076                              VT.getVectorNumElements();
5077           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5078                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5079                         Value, DAG.getConstant(index, MVT::i32)),
5080                            DAG.getConstant(index, MVT::i32));
5081         } else
5082           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5083                         Value->getOperand(0), Value->getOperand(1));
5084       } else
5085         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5086
5087       if (!usesOnlyOneValue) {
5088         // The dominant value was splatted as 'N', but we now have to insert
5089         // all differing elements.
5090         for (unsigned I = 0; I < NumElts; ++I) {
5091           if (Op.getOperand(I) == Value)
5092             continue;
5093           SmallVector<SDValue, 3> Ops;
5094           Ops.push_back(N);
5095           Ops.push_back(Op.getOperand(I));
5096           Ops.push_back(DAG.getConstant(I, MVT::i32));
5097           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5098         }
5099       }
5100       return N;
5101     }
5102     if (VT.getVectorElementType().isFloatingPoint()) {
5103       SmallVector<SDValue, 8> Ops;
5104       for (unsigned i = 0; i < NumElts; ++i)
5105         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5106                                   Op.getOperand(i)));
5107       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5108       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5109       Val = LowerBUILD_VECTOR(Val, DAG, ST);
5110       if (Val.getNode())
5111         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5112     }
5113     if (usesOnlyOneValue) {
5114       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5115       if (isConstant && Val.getNode())
5116         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5117     }
5118   }
5119
5120   // If all elements are constants and the case above didn't get hit, fall back
5121   // to the default expansion, which will generate a load from the constant
5122   // pool.
5123   if (isConstant)
5124     return SDValue();
5125
5126   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5127   if (NumElts >= 4) {
5128     SDValue shuffle = ReconstructShuffle(Op, DAG);
5129     if (shuffle != SDValue())
5130       return shuffle;
5131   }
5132
5133   // Vectors with 32- or 64-bit elements can be built by directly assigning
5134   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
5135   // will be legalized.
5136   if (EltSize >= 32) {
5137     // Do the expansion with floating-point types, since that is what the VFP
5138     // registers are defined to use, and since i64 is not legal.
5139     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5140     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5141     SmallVector<SDValue, 8> Ops;
5142     for (unsigned i = 0; i < NumElts; ++i)
5143       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5144     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5145     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5146   }
5147
5148   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5149   // know the default expansion would otherwise fall back on something even
5150   // worse. For a vector with one or two non-undef values, that's
5151   // scalar_to_vector for the elements followed by a shuffle (provided the
5152   // shuffle is valid for the target) and materialization element by element
5153   // on the stack followed by a load for everything else.
5154   if (!isConstant && !usesOnlyOneValue) {
5155     SDValue Vec = DAG.getUNDEF(VT);
5156     for (unsigned i = 0 ; i < NumElts; ++i) {
5157       SDValue V = Op.getOperand(i);
5158       if (V.getOpcode() == ISD::UNDEF)
5159         continue;
5160       SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
5161       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5162     }
5163     return Vec;
5164   }
5165
5166   return SDValue();
5167 }
5168
5169 // Gather data to see if the operation can be modelled as a
5170 // shuffle in combination with VEXTs.
5171 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5172                                               SelectionDAG &DAG) const {
5173   SDLoc dl(Op);
5174   EVT VT = Op.getValueType();
5175   unsigned NumElts = VT.getVectorNumElements();
5176
5177   SmallVector<SDValue, 2> SourceVecs;
5178   SmallVector<unsigned, 2> MinElts;
5179   SmallVector<unsigned, 2> MaxElts;
5180
5181   for (unsigned i = 0; i < NumElts; ++i) {
5182     SDValue V = Op.getOperand(i);
5183     if (V.getOpcode() == ISD::UNDEF)
5184       continue;
5185     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5186       // A shuffle can only come from building a vector from various
5187       // elements of other vectors.
5188       return SDValue();
5189     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5190                VT.getVectorElementType()) {
5191       // This code doesn't know how to handle shuffles where the vector
5192       // element types do not match (this happens because type legalization
5193       // promotes the return type of EXTRACT_VECTOR_ELT).
5194       // FIXME: It might be appropriate to extend this code to handle
5195       // mismatched types.
5196       return SDValue();
5197     }
5198
5199     // Record this extraction against the appropriate vector if possible...
5200     SDValue SourceVec = V.getOperand(0);
5201     // If the element number isn't a constant, we can't effectively
5202     // analyze what's going on.
5203     if (!isa<ConstantSDNode>(V.getOperand(1)))
5204       return SDValue();
5205     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5206     bool FoundSource = false;
5207     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5208       if (SourceVecs[j] == SourceVec) {
5209         if (MinElts[j] > EltNo)
5210           MinElts[j] = EltNo;
5211         if (MaxElts[j] < EltNo)
5212           MaxElts[j] = EltNo;
5213         FoundSource = true;
5214         break;
5215       }
5216     }
5217
5218     // Or record a new source if not...
5219     if (!FoundSource) {
5220       SourceVecs.push_back(SourceVec);
5221       MinElts.push_back(EltNo);
5222       MaxElts.push_back(EltNo);
5223     }
5224   }
5225
5226   // Currently only do something sane when at most two source vectors
5227   // involved.
5228   if (SourceVecs.size() > 2)
5229     return SDValue();
5230
5231   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5232   int VEXTOffsets[2] = {0, 0};
5233
5234   // This loop extracts the usage patterns of the source vectors
5235   // and prepares appropriate SDValues for a shuffle if possible.
5236   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5237     if (SourceVecs[i].getValueType() == VT) {
5238       // No VEXT necessary
5239       ShuffleSrcs[i] = SourceVecs[i];
5240       VEXTOffsets[i] = 0;
5241       continue;
5242     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5243       // It probably isn't worth padding out a smaller vector just to
5244       // break it down again in a shuffle.
5245       return SDValue();
5246     }
5247
5248     // Since only 64-bit and 128-bit vectors are legal on ARM and
5249     // we've eliminated the other cases...
5250     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5251            "unexpected vector sizes in ReconstructShuffle");
5252
5253     if (MaxElts[i] - MinElts[i] >= NumElts) {
5254       // Span too large for a VEXT to cope
5255       return SDValue();
5256     }
5257
5258     if (MinElts[i] >= NumElts) {
5259       // The extraction can just take the second half
5260       VEXTOffsets[i] = NumElts;
5261       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5262                                    SourceVecs[i],
5263                                    DAG.getIntPtrConstant(NumElts));
5264     } else if (MaxElts[i] < NumElts) {
5265       // The extraction can just take the first half
5266       VEXTOffsets[i] = 0;
5267       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5268                                    SourceVecs[i],
5269                                    DAG.getIntPtrConstant(0));
5270     } else {
5271       // An actual VEXT is needed
5272       VEXTOffsets[i] = MinElts[i];
5273       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5274                                      SourceVecs[i],
5275                                      DAG.getIntPtrConstant(0));
5276       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5277                                      SourceVecs[i],
5278                                      DAG.getIntPtrConstant(NumElts));
5279       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5280                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
5281     }
5282   }
5283
5284   SmallVector<int, 8> Mask;
5285
5286   for (unsigned i = 0; i < NumElts; ++i) {
5287     SDValue Entry = Op.getOperand(i);
5288     if (Entry.getOpcode() == ISD::UNDEF) {
5289       Mask.push_back(-1);
5290       continue;
5291     }
5292
5293     SDValue ExtractVec = Entry.getOperand(0);
5294     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5295                                           .getOperand(1))->getSExtValue();
5296     if (ExtractVec == SourceVecs[0]) {
5297       Mask.push_back(ExtractElt - VEXTOffsets[0]);
5298     } else {
5299       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5300     }
5301   }
5302
5303   // Final check before we try to produce nonsense...
5304   if (isShuffleMaskLegal(Mask, VT))
5305     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5306                                 &Mask[0]);
5307
5308   return SDValue();
5309 }
5310
5311 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5312 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5313 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5314 /// are assumed to be legal.
5315 bool
5316 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5317                                       EVT VT) const {
5318   if (VT.getVectorNumElements() == 4 &&
5319       (VT.is128BitVector() || VT.is64BitVector())) {
5320     unsigned PFIndexes[4];
5321     for (unsigned i = 0; i != 4; ++i) {
5322       if (M[i] < 0)
5323         PFIndexes[i] = 8;
5324       else
5325         PFIndexes[i] = M[i];
5326     }
5327
5328     // Compute the index in the perfect shuffle table.
5329     unsigned PFTableIndex =
5330       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5331     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5332     unsigned Cost = (PFEntry >> 30);
5333
5334     if (Cost <= 4)
5335       return true;
5336   }
5337
5338   bool ReverseVEXT;
5339   unsigned Imm, WhichResult;
5340
5341   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5342   return (EltSize >= 32 ||
5343           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5344           isVREVMask(M, VT, 64) ||
5345           isVREVMask(M, VT, 32) ||
5346           isVREVMask(M, VT, 16) ||
5347           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5348           isVTBLMask(M, VT) ||
5349           isVTRNMask(M, VT, WhichResult) ||
5350           isVUZPMask(M, VT, WhichResult) ||
5351           isVZIPMask(M, VT, WhichResult) ||
5352           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5353           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5354           isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5355           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5356 }
5357
5358 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5359 /// the specified operations to build the shuffle.
5360 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5361                                       SDValue RHS, SelectionDAG &DAG,
5362                                       SDLoc dl) {
5363   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5364   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5365   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5366
5367   enum {
5368     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5369     OP_VREV,
5370     OP_VDUP0,
5371     OP_VDUP1,
5372     OP_VDUP2,
5373     OP_VDUP3,
5374     OP_VEXT1,
5375     OP_VEXT2,
5376     OP_VEXT3,
5377     OP_VUZPL, // VUZP, left result
5378     OP_VUZPR, // VUZP, right result
5379     OP_VZIPL, // VZIP, left result
5380     OP_VZIPR, // VZIP, right result
5381     OP_VTRNL, // VTRN, left result
5382     OP_VTRNR  // VTRN, right result
5383   };
5384
5385   if (OpNum == OP_COPY) {
5386     if (LHSID == (1*9+2)*9+3) return LHS;
5387     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5388     return RHS;
5389   }
5390
5391   SDValue OpLHS, OpRHS;
5392   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5393   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5394   EVT VT = OpLHS.getValueType();
5395
5396   switch (OpNum) {
5397   default: llvm_unreachable("Unknown shuffle opcode!");
5398   case OP_VREV:
5399     // VREV divides the vector in half and swaps within the half.
5400     if (VT.getVectorElementType() == MVT::i32 ||
5401         VT.getVectorElementType() == MVT::f32)
5402       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5403     // vrev <4 x i16> -> VREV32
5404     if (VT.getVectorElementType() == MVT::i16)
5405       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5406     // vrev <4 x i8> -> VREV16
5407     assert(VT.getVectorElementType() == MVT::i8);
5408     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5409   case OP_VDUP0:
5410   case OP_VDUP1:
5411   case OP_VDUP2:
5412   case OP_VDUP3:
5413     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5414                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5415   case OP_VEXT1:
5416   case OP_VEXT2:
5417   case OP_VEXT3:
5418     return DAG.getNode(ARMISD::VEXT, dl, VT,
5419                        OpLHS, OpRHS,
5420                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5421   case OP_VUZPL:
5422   case OP_VUZPR:
5423     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5424                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5425   case OP_VZIPL:
5426   case OP_VZIPR:
5427     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5428                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5429   case OP_VTRNL:
5430   case OP_VTRNR:
5431     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5432                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5433   }
5434 }
5435
5436 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5437                                        ArrayRef<int> ShuffleMask,
5438                                        SelectionDAG &DAG) {
5439   // Check to see if we can use the VTBL instruction.
5440   SDValue V1 = Op.getOperand(0);
5441   SDValue V2 = Op.getOperand(1);
5442   SDLoc DL(Op);
5443
5444   SmallVector<SDValue, 8> VTBLMask;
5445   for (ArrayRef<int>::iterator
5446          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5447     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5448
5449   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5450     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5451                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5452
5453   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5454                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5455 }
5456
5457 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5458                                                       SelectionDAG &DAG) {
5459   SDLoc DL(Op);
5460   SDValue OpLHS = Op.getOperand(0);
5461   EVT VT = OpLHS.getValueType();
5462
5463   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5464          "Expect an v8i16/v16i8 type");
5465   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5466   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5467   // extract the first 8 bytes into the top double word and the last 8 bytes
5468   // into the bottom double word. The v8i16 case is similar.
5469   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5470   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5471                      DAG.getConstant(ExtractNum, MVT::i32));
5472 }
5473
5474 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5475   SDValue V1 = Op.getOperand(0);
5476   SDValue V2 = Op.getOperand(1);
5477   SDLoc dl(Op);
5478   EVT VT = Op.getValueType();
5479   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5480
5481   // Convert shuffles that are directly supported on NEON to target-specific
5482   // DAG nodes, instead of keeping them as shuffles and matching them again
5483   // during code selection.  This is more efficient and avoids the possibility
5484   // of inconsistencies between legalization and selection.
5485   // FIXME: floating-point vectors should be canonicalized to integer vectors
5486   // of the same time so that they get CSEd properly.
5487   ArrayRef<int> ShuffleMask = SVN->getMask();
5488
5489   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5490   if (EltSize <= 32) {
5491     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5492       int Lane = SVN->getSplatIndex();
5493       // If this is undef splat, generate it via "just" vdup, if possible.
5494       if (Lane == -1) Lane = 0;
5495
5496       // Test if V1 is a SCALAR_TO_VECTOR.
5497       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5498         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5499       }
5500       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5501       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5502       // reaches it).
5503       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5504           !isa<ConstantSDNode>(V1.getOperand(0))) {
5505         bool IsScalarToVector = true;
5506         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5507           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5508             IsScalarToVector = false;
5509             break;
5510           }
5511         if (IsScalarToVector)
5512           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5513       }
5514       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5515                          DAG.getConstant(Lane, MVT::i32));
5516     }
5517
5518     bool ReverseVEXT;
5519     unsigned Imm;
5520     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5521       if (ReverseVEXT)
5522         std::swap(V1, V2);
5523       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5524                          DAG.getConstant(Imm, MVT::i32));
5525     }
5526
5527     if (isVREVMask(ShuffleMask, VT, 64))
5528       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5529     if (isVREVMask(ShuffleMask, VT, 32))
5530       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5531     if (isVREVMask(ShuffleMask, VT, 16))
5532       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5533
5534     if (V2->getOpcode() == ISD::UNDEF &&
5535         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5536       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5537                          DAG.getConstant(Imm, MVT::i32));
5538     }
5539
5540     // Check for Neon shuffles that modify both input vectors in place.
5541     // If both results are used, i.e., if there are two shuffles with the same
5542     // source operands and with masks corresponding to both results of one of
5543     // these operations, DAG memoization will ensure that a single node is
5544     // used for both shuffles.
5545     unsigned WhichResult;
5546     if (isVTRNMask(ShuffleMask, VT, WhichResult))
5547       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5548                          V1, V2).getValue(WhichResult);
5549     if (isVUZPMask(ShuffleMask, VT, WhichResult))
5550       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5551                          V1, V2).getValue(WhichResult);
5552     if (isVZIPMask(ShuffleMask, VT, WhichResult))
5553       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5554                          V1, V2).getValue(WhichResult);
5555
5556     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5557       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5558                          V1, V1).getValue(WhichResult);
5559     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5560       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5561                          V1, V1).getValue(WhichResult);
5562     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5563       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5564                          V1, V1).getValue(WhichResult);
5565   }
5566
5567   // If the shuffle is not directly supported and it has 4 elements, use
5568   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5569   unsigned NumElts = VT.getVectorNumElements();
5570   if (NumElts == 4) {
5571     unsigned PFIndexes[4];
5572     for (unsigned i = 0; i != 4; ++i) {
5573       if (ShuffleMask[i] < 0)
5574         PFIndexes[i] = 8;
5575       else
5576         PFIndexes[i] = ShuffleMask[i];
5577     }
5578
5579     // Compute the index in the perfect shuffle table.
5580     unsigned PFTableIndex =
5581       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5582     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5583     unsigned Cost = (PFEntry >> 30);
5584
5585     if (Cost <= 4)
5586       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5587   }
5588
5589   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5590   if (EltSize >= 32) {
5591     // Do the expansion with floating-point types, since that is what the VFP
5592     // registers are defined to use, and since i64 is not legal.
5593     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5594     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5595     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5596     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5597     SmallVector<SDValue, 8> Ops;
5598     for (unsigned i = 0; i < NumElts; ++i) {
5599       if (ShuffleMask[i] < 0)
5600         Ops.push_back(DAG.getUNDEF(EltVT));
5601       else
5602         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5603                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
5604                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5605                                                   MVT::i32)));
5606     }
5607     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5608     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5609   }
5610
5611   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5612     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5613
5614   if (VT == MVT::v8i8) {
5615     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5616     if (NewOp.getNode())
5617       return NewOp;
5618   }
5619
5620   return SDValue();
5621 }
5622
5623 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5624   // INSERT_VECTOR_ELT is legal only for immediate indexes.
5625   SDValue Lane = Op.getOperand(2);
5626   if (!isa<ConstantSDNode>(Lane))
5627     return SDValue();
5628
5629   return Op;
5630 }
5631
5632 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5633   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5634   SDValue Lane = Op.getOperand(1);
5635   if (!isa<ConstantSDNode>(Lane))
5636     return SDValue();
5637
5638   SDValue Vec = Op.getOperand(0);
5639   if (Op.getValueType() == MVT::i32 &&
5640       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5641     SDLoc dl(Op);
5642     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5643   }
5644
5645   return Op;
5646 }
5647
5648 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5649   // The only time a CONCAT_VECTORS operation can have legal types is when
5650   // two 64-bit vectors are concatenated to a 128-bit vector.
5651   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5652          "unexpected CONCAT_VECTORS");
5653   SDLoc dl(Op);
5654   SDValue Val = DAG.getUNDEF(MVT::v2f64);
5655   SDValue Op0 = Op.getOperand(0);
5656   SDValue Op1 = Op.getOperand(1);
5657   if (Op0.getOpcode() != ISD::UNDEF)
5658     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5659                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5660                       DAG.getIntPtrConstant(0));
5661   if (Op1.getOpcode() != ISD::UNDEF)
5662     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5663                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5664                       DAG.getIntPtrConstant(1));
5665   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5666 }
5667
5668 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5669 /// element has been zero/sign-extended, depending on the isSigned parameter,
5670 /// from an integer type half its size.
5671 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5672                                    bool isSigned) {
5673   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5674   EVT VT = N->getValueType(0);
5675   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5676     SDNode *BVN = N->getOperand(0).getNode();
5677     if (BVN->getValueType(0) != MVT::v4i32 ||
5678         BVN->getOpcode() != ISD::BUILD_VECTOR)
5679       return false;
5680     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5681     unsigned HiElt = 1 - LoElt;
5682     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5683     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5684     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5685     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5686     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5687       return false;
5688     if (isSigned) {
5689       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5690           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5691         return true;
5692     } else {
5693       if (Hi0->isNullValue() && Hi1->isNullValue())
5694         return true;
5695     }
5696     return false;
5697   }
5698
5699   if (N->getOpcode() != ISD::BUILD_VECTOR)
5700     return false;
5701
5702   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5703     SDNode *Elt = N->getOperand(i).getNode();
5704     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5705       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5706       unsigned HalfSize = EltSize / 2;
5707       if (isSigned) {
5708         if (!isIntN(HalfSize, C->getSExtValue()))
5709           return false;
5710       } else {
5711         if (!isUIntN(HalfSize, C->getZExtValue()))
5712           return false;
5713       }
5714       continue;
5715     }
5716     return false;
5717   }
5718
5719   return true;
5720 }
5721
5722 /// isSignExtended - Check if a node is a vector value that is sign-extended
5723 /// or a constant BUILD_VECTOR with sign-extended elements.
5724 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5725   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5726     return true;
5727   if (isExtendedBUILD_VECTOR(N, DAG, true))
5728     return true;
5729   return false;
5730 }
5731
5732 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5733 /// or a constant BUILD_VECTOR with zero-extended elements.
5734 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5735   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5736     return true;
5737   if (isExtendedBUILD_VECTOR(N, DAG, false))
5738     return true;
5739   return false;
5740 }
5741
5742 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5743   if (OrigVT.getSizeInBits() >= 64)
5744     return OrigVT;
5745
5746   assert(OrigVT.isSimple() && "Expecting a simple value type");
5747
5748   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5749   switch (OrigSimpleTy) {
5750   default: llvm_unreachable("Unexpected Vector Type");
5751   case MVT::v2i8:
5752   case MVT::v2i16:
5753      return MVT::v2i32;
5754   case MVT::v4i8:
5755     return  MVT::v4i16;
5756   }
5757 }
5758
5759 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5760 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5761 /// We insert the required extension here to get the vector to fill a D register.
5762 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5763                                             const EVT &OrigTy,
5764                                             const EVT &ExtTy,
5765                                             unsigned ExtOpcode) {
5766   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5767   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5768   // 64-bits we need to insert a new extension so that it will be 64-bits.
5769   assert(ExtTy.is128BitVector() && "Unexpected extension size");
5770   if (OrigTy.getSizeInBits() >= 64)
5771     return N;
5772
5773   // Must extend size to at least 64 bits to be used as an operand for VMULL.
5774   EVT NewVT = getExtensionTo64Bits(OrigTy);
5775
5776   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5777 }
5778
5779 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5780 /// does not do any sign/zero extension. If the original vector is less
5781 /// than 64 bits, an appropriate extension will be added after the load to
5782 /// reach a total size of 64 bits. We have to add the extension separately
5783 /// because ARM does not have a sign/zero extending load for vectors.
5784 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5785   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5786
5787   // The load already has the right type.
5788   if (ExtendedTy == LD->getMemoryVT())
5789     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5790                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5791                 LD->isNonTemporal(), LD->isInvariant(),
5792                 LD->getAlignment());
5793
5794   // We need to create a zextload/sextload. We cannot just create a load
5795   // followed by a zext/zext node because LowerMUL is also run during normal
5796   // operation legalization where we can't create illegal types.
5797   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5798                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5799                         LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
5800                         LD->isNonTemporal(), LD->getAlignment());
5801 }
5802
5803 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5804 /// extending load, or BUILD_VECTOR with extended elements, return the
5805 /// unextended value. The unextended vector should be 64 bits so that it can
5806 /// be used as an operand to a VMULL instruction. If the original vector size
5807 /// before extension is less than 64 bits we add a an extension to resize
5808 /// the vector to 64 bits.
5809 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5810   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5811     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5812                                         N->getOperand(0)->getValueType(0),
5813                                         N->getValueType(0),
5814                                         N->getOpcode());
5815
5816   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5817     return SkipLoadExtensionForVMULL(LD, DAG);
5818
5819   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
5820   // have been legalized as a BITCAST from v4i32.
5821   if (N->getOpcode() == ISD::BITCAST) {
5822     SDNode *BVN = N->getOperand(0).getNode();
5823     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5824            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5825     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5826     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5827                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5828   }
5829   // Construct a new BUILD_VECTOR with elements truncated to half the size.
5830   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5831   EVT VT = N->getValueType(0);
5832   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5833   unsigned NumElts = VT.getVectorNumElements();
5834   MVT TruncVT = MVT::getIntegerVT(EltSize);
5835   SmallVector<SDValue, 8> Ops;
5836   for (unsigned i = 0; i != NumElts; ++i) {
5837     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5838     const APInt &CInt = C->getAPIntValue();
5839     // Element types smaller than 32 bits are not legal, so use i32 elements.
5840     // The values are implicitly truncated so sext vs. zext doesn't matter.
5841     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5842   }
5843   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5844                      MVT::getVectorVT(TruncVT, NumElts), Ops);
5845 }
5846
5847 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5848   unsigned Opcode = N->getOpcode();
5849   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5850     SDNode *N0 = N->getOperand(0).getNode();
5851     SDNode *N1 = N->getOperand(1).getNode();
5852     return N0->hasOneUse() && N1->hasOneUse() &&
5853       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5854   }
5855   return false;
5856 }
5857
5858 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5859   unsigned Opcode = N->getOpcode();
5860   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5861     SDNode *N0 = N->getOperand(0).getNode();
5862     SDNode *N1 = N->getOperand(1).getNode();
5863     return N0->hasOneUse() && N1->hasOneUse() &&
5864       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5865   }
5866   return false;
5867 }
5868
5869 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5870   // Multiplications are only custom-lowered for 128-bit vectors so that
5871   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
5872   EVT VT = Op.getValueType();
5873   assert(VT.is128BitVector() && VT.isInteger() &&
5874          "unexpected type for custom-lowering ISD::MUL");
5875   SDNode *N0 = Op.getOperand(0).getNode();
5876   SDNode *N1 = Op.getOperand(1).getNode();
5877   unsigned NewOpc = 0;
5878   bool isMLA = false;
5879   bool isN0SExt = isSignExtended(N0, DAG);
5880   bool isN1SExt = isSignExtended(N1, DAG);
5881   if (isN0SExt && isN1SExt)
5882     NewOpc = ARMISD::VMULLs;
5883   else {
5884     bool isN0ZExt = isZeroExtended(N0, DAG);
5885     bool isN1ZExt = isZeroExtended(N1, DAG);
5886     if (isN0ZExt && isN1ZExt)
5887       NewOpc = ARMISD::VMULLu;
5888     else if (isN1SExt || isN1ZExt) {
5889       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5890       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5891       if (isN1SExt && isAddSubSExt(N0, DAG)) {
5892         NewOpc = ARMISD::VMULLs;
5893         isMLA = true;
5894       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5895         NewOpc = ARMISD::VMULLu;
5896         isMLA = true;
5897       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5898         std::swap(N0, N1);
5899         NewOpc = ARMISD::VMULLu;
5900         isMLA = true;
5901       }
5902     }
5903
5904     if (!NewOpc) {
5905       if (VT == MVT::v2i64)
5906         // Fall through to expand this.  It is not legal.
5907         return SDValue();
5908       else
5909         // Other vector multiplications are legal.
5910         return Op;
5911     }
5912   }
5913
5914   // Legalize to a VMULL instruction.
5915   SDLoc DL(Op);
5916   SDValue Op0;
5917   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5918   if (!isMLA) {
5919     Op0 = SkipExtensionForVMULL(N0, DAG);
5920     assert(Op0.getValueType().is64BitVector() &&
5921            Op1.getValueType().is64BitVector() &&
5922            "unexpected types for extended operands to VMULL");
5923     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5924   }
5925
5926   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5927   // isel lowering to take advantage of no-stall back to back vmul + vmla.
5928   //   vmull q0, d4, d6
5929   //   vmlal q0, d5, d6
5930   // is faster than
5931   //   vaddl q0, d4, d5
5932   //   vmovl q1, d6
5933   //   vmul  q0, q0, q1
5934   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5935   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5936   EVT Op1VT = Op1.getValueType();
5937   return DAG.getNode(N0->getOpcode(), DL, VT,
5938                      DAG.getNode(NewOpc, DL, VT,
5939                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5940                      DAG.getNode(NewOpc, DL, VT,
5941                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5942 }
5943
5944 static SDValue
5945 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
5946   // Convert to float
5947   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5948   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5949   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5950   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5951   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5952   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5953   // Get reciprocal estimate.
5954   // float4 recip = vrecpeq_f32(yf);
5955   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5956                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5957   // Because char has a smaller range than uchar, we can actually get away
5958   // without any newton steps.  This requires that we use a weird bias
5959   // of 0xb000, however (again, this has been exhaustively tested).
5960   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5961   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5962   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5963   Y = DAG.getConstant(0xb000, MVT::i32);
5964   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5965   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5966   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5967   // Convert back to short.
5968   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5969   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5970   return X;
5971 }
5972
5973 static SDValue
5974 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
5975   SDValue N2;
5976   // Convert to float.
5977   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5978   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5979   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5980   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5981   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5982   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5983
5984   // Use reciprocal estimate and one refinement step.
5985   // float4 recip = vrecpeq_f32(yf);
5986   // recip *= vrecpsq_f32(yf, recip);
5987   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5988                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5989   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5990                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5991                    N1, N2);
5992   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5993   // Because short has a smaller range than ushort, we can actually get away
5994   // with only a single newton step.  This requires that we use a weird bias
5995   // of 89, however (again, this has been exhaustively tested).
5996   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5997   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5998   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5999   N1 = DAG.getConstant(0x89, MVT::i32);
6000   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6001   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6002   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6003   // Convert back to integer and return.
6004   // return vmovn_s32(vcvt_s32_f32(result));
6005   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6006   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6007   return N0;
6008 }
6009
6010 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6011   EVT VT = Op.getValueType();
6012   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6013          "unexpected type for custom-lowering ISD::SDIV");
6014
6015   SDLoc dl(Op);
6016   SDValue N0 = Op.getOperand(0);
6017   SDValue N1 = Op.getOperand(1);
6018   SDValue N2, N3;
6019
6020   if (VT == MVT::v8i8) {
6021     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6022     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6023
6024     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6025                      DAG.getIntPtrConstant(4));
6026     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6027                      DAG.getIntPtrConstant(4));
6028     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6029                      DAG.getIntPtrConstant(0));
6030     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6031                      DAG.getIntPtrConstant(0));
6032
6033     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6034     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6035
6036     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6037     N0 = LowerCONCAT_VECTORS(N0, DAG);
6038
6039     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6040     return N0;
6041   }
6042   return LowerSDIV_v4i16(N0, N1, dl, DAG);
6043 }
6044
6045 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6046   EVT VT = Op.getValueType();
6047   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6048          "unexpected type for custom-lowering ISD::UDIV");
6049
6050   SDLoc dl(Op);
6051   SDValue N0 = Op.getOperand(0);
6052   SDValue N1 = Op.getOperand(1);
6053   SDValue N2, N3;
6054
6055   if (VT == MVT::v8i8) {
6056     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6057     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6058
6059     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6060                      DAG.getIntPtrConstant(4));
6061     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6062                      DAG.getIntPtrConstant(4));
6063     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6064                      DAG.getIntPtrConstant(0));
6065     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6066                      DAG.getIntPtrConstant(0));
6067
6068     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6069     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6070
6071     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6072     N0 = LowerCONCAT_VECTORS(N0, DAG);
6073
6074     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6075                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
6076                      N0);
6077     return N0;
6078   }
6079
6080   // v4i16 sdiv ... Convert to float.
6081   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6082   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6083   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6084   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6085   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6086   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6087
6088   // Use reciprocal estimate and two refinement steps.
6089   // float4 recip = vrecpeq_f32(yf);
6090   // recip *= vrecpsq_f32(yf, recip);
6091   // recip *= vrecpsq_f32(yf, recip);
6092   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6093                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
6094   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6095                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6096                    BN1, N2);
6097   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6098   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6099                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6100                    BN1, N2);
6101   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6102   // Simply multiplying by the reciprocal estimate can leave us a few ulps
6103   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6104   // and that it will never cause us to return an answer too large).
6105   // float4 result = as_float4(as_int4(xf*recip) + 2);
6106   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6107   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6108   N1 = DAG.getConstant(2, MVT::i32);
6109   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6110   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6111   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6112   // Convert back to integer and return.
6113   // return vmovn_u32(vcvt_s32_f32(result));
6114   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6115   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6116   return N0;
6117 }
6118
6119 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6120   EVT VT = Op.getNode()->getValueType(0);
6121   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6122
6123   unsigned Opc;
6124   bool ExtraOp = false;
6125   switch (Op.getOpcode()) {
6126   default: llvm_unreachable("Invalid code");
6127   case ISD::ADDC: Opc = ARMISD::ADDC; break;
6128   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6129   case ISD::SUBC: Opc = ARMISD::SUBC; break;
6130   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6131   }
6132
6133   if (!ExtraOp)
6134     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6135                        Op.getOperand(1));
6136   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6137                      Op.getOperand(1), Op.getOperand(2));
6138 }
6139
6140 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6141   assert(Subtarget->isTargetDarwin());
6142
6143   // For iOS, we want to call an alternative entry point: __sincos_stret,
6144   // return values are passed via sret.
6145   SDLoc dl(Op);
6146   SDValue Arg = Op.getOperand(0);
6147   EVT ArgVT = Arg.getValueType();
6148   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6149
6150   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6151   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6152
6153   // Pair of floats / doubles used to pass the result.
6154   StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
6155
6156   // Create stack object for sret.
6157   const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
6158   const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
6159   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6160   SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
6161
6162   ArgListTy Args;
6163   ArgListEntry Entry;
6164
6165   Entry.Node = SRet;
6166   Entry.Ty = RetTy->getPointerTo();
6167   Entry.isSExt = false;
6168   Entry.isZExt = false;
6169   Entry.isSRet = true;
6170   Args.push_back(Entry);
6171
6172   Entry.Node = Arg;
6173   Entry.Ty = ArgTy;
6174   Entry.isSExt = false;
6175   Entry.isZExt = false;
6176   Args.push_back(Entry);
6177
6178   const char *LibcallName  = (ArgVT == MVT::f64)
6179   ? "__sincos_stret" : "__sincosf_stret";
6180   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
6181
6182   TargetLowering::CallLoweringInfo CLI(DAG);
6183   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6184     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6185                std::move(Args), 0)
6186     .setDiscardResult();
6187
6188   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6189
6190   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6191                                 MachinePointerInfo(), false, false, false, 0);
6192
6193   // Address of cos field.
6194   SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
6195                             DAG.getIntPtrConstant(ArgVT.getStoreSize()));
6196   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6197                                 MachinePointerInfo(), false, false, false, 0);
6198
6199   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6200   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6201                      LoadSin.getValue(0), LoadCos.getValue(0));
6202 }
6203
6204 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6205   // Monotonic load/store is legal for all targets
6206   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6207     return Op;
6208
6209   // Acquire/Release load/store is not legal for targets without a
6210   // dmb or equivalent available.
6211   return SDValue();
6212 }
6213
6214 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6215                                     SmallVectorImpl<SDValue> &Results,
6216                                     SelectionDAG &DAG,
6217                                     const ARMSubtarget *Subtarget) {
6218   SDLoc DL(N);
6219   SDValue Cycles32, OutChain;
6220
6221   if (Subtarget->hasPerfMon()) {
6222     // Under Power Management extensions, the cycle-count is:
6223     //    mrc p15, #0, <Rt>, c9, c13, #0
6224     SDValue Ops[] = { N->getOperand(0), // Chain
6225                       DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
6226                       DAG.getConstant(15, MVT::i32),
6227                       DAG.getConstant(0, MVT::i32),
6228                       DAG.getConstant(9, MVT::i32),
6229                       DAG.getConstant(13, MVT::i32),
6230                       DAG.getConstant(0, MVT::i32)
6231     };
6232
6233     Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6234                            DAG.getVTList(MVT::i32, MVT::Other), Ops);
6235     OutChain = Cycles32.getValue(1);
6236   } else {
6237     // Intrinsic is defined to return 0 on unsupported platforms. Technically
6238     // there are older ARM CPUs that have implementation-specific ways of
6239     // obtaining this information (FIXME!).
6240     Cycles32 = DAG.getConstant(0, MVT::i32);
6241     OutChain = DAG.getEntryNode();
6242   }
6243
6244
6245   SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6246                                  Cycles32, DAG.getConstant(0, MVT::i32));
6247   Results.push_back(Cycles64);
6248   Results.push_back(OutChain);
6249 }
6250
6251 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6252   switch (Op.getOpcode()) {
6253   default: llvm_unreachable("Don't know how to custom lower this!");
6254   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6255   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6256   case ISD::GlobalAddress:
6257     switch (Subtarget->getTargetTriple().getObjectFormat()) {
6258     default: llvm_unreachable("unknown object format");
6259     case Triple::COFF:
6260       return LowerGlobalAddressWindows(Op, DAG);
6261     case Triple::ELF:
6262       return LowerGlobalAddressELF(Op, DAG);
6263     case Triple::MachO:
6264       return LowerGlobalAddressDarwin(Op, DAG);
6265     }
6266   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6267   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6268   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6269   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6270   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6271   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6272   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6273   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6274   case ISD::SINT_TO_FP:
6275   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6276   case ISD::FP_TO_SINT:
6277   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6278   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6279   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6280   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6281   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6282   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6283   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6284   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6285                                                                Subtarget);
6286   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6287   case ISD::SHL:
6288   case ISD::SRL:
6289   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6290   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6291   case ISD::SRL_PARTS:
6292   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6293   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6294   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6295   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6296   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6297   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6298   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6299   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6300   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6301   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6302   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6303   case ISD::MUL:           return LowerMUL(Op, DAG);
6304   case ISD::SDIV:          return LowerSDIV(Op, DAG);
6305   case ISD::UDIV:          return LowerUDIV(Op, DAG);
6306   case ISD::ADDC:
6307   case ISD::ADDE:
6308   case ISD::SUBC:
6309   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6310   case ISD::SADDO:
6311   case ISD::UADDO:
6312   case ISD::SSUBO:
6313   case ISD::USUBO:
6314     return LowerXALUO(Op, DAG);
6315   case ISD::ATOMIC_LOAD:
6316   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6317   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6318   case ISD::SDIVREM:
6319   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6320   case ISD::DYNAMIC_STACKALLOC:
6321     if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6322       return LowerDYNAMIC_STACKALLOC(Op, DAG);
6323     llvm_unreachable("Don't know how to custom lower this!");
6324   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6325   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6326   }
6327 }
6328
6329 /// ReplaceNodeResults - Replace the results of node with an illegal result
6330 /// type with new values built out of custom code.
6331 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6332                                            SmallVectorImpl<SDValue>&Results,
6333                                            SelectionDAG &DAG) const {
6334   SDValue Res;
6335   switch (N->getOpcode()) {
6336   default:
6337     llvm_unreachable("Don't know how to custom expand this!");
6338   case ISD::BITCAST:
6339     Res = ExpandBITCAST(N, DAG);
6340     break;
6341   case ISD::SRL:
6342   case ISD::SRA:
6343     Res = Expand64BitShift(N, DAG, Subtarget);
6344     break;
6345   case ISD::READCYCLECOUNTER:
6346     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6347     return;
6348   }
6349   if (Res.getNode())
6350     Results.push_back(Res);
6351 }
6352
6353 //===----------------------------------------------------------------------===//
6354 //                           ARM Scheduler Hooks
6355 //===----------------------------------------------------------------------===//
6356
6357 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6358 /// registers the function context.
6359 void ARMTargetLowering::
6360 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6361                        MachineBasicBlock *DispatchBB, int FI) const {
6362   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6363   DebugLoc dl = MI->getDebugLoc();
6364   MachineFunction *MF = MBB->getParent();
6365   MachineRegisterInfo *MRI = &MF->getRegInfo();
6366   MachineConstantPool *MCP = MF->getConstantPool();
6367   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6368   const Function *F = MF->getFunction();
6369
6370   bool isThumb = Subtarget->isThumb();
6371   bool isThumb2 = Subtarget->isThumb2();
6372
6373   unsigned PCLabelId = AFI->createPICLabelUId();
6374   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6375   ARMConstantPoolValue *CPV =
6376     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6377   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6378
6379   const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
6380                                            : &ARM::GPRRegClass;
6381
6382   // Grab constant pool and fixed stack memory operands.
6383   MachineMemOperand *CPMMO =
6384     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6385                              MachineMemOperand::MOLoad, 4, 4);
6386
6387   MachineMemOperand *FIMMOSt =
6388     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6389                              MachineMemOperand::MOStore, 4, 4);
6390
6391   // Load the address of the dispatch MBB into the jump buffer.
6392   if (isThumb2) {
6393     // Incoming value: jbuf
6394     //   ldr.n  r5, LCPI1_1
6395     //   orr    r5, r5, #1
6396     //   add    r5, pc
6397     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6398     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6399     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6400                    .addConstantPoolIndex(CPI)
6401                    .addMemOperand(CPMMO));
6402     // Set the low bit because of thumb mode.
6403     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6404     AddDefaultCC(
6405       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6406                      .addReg(NewVReg1, RegState::Kill)
6407                      .addImm(0x01)));
6408     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6409     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6410       .addReg(NewVReg2, RegState::Kill)
6411       .addImm(PCLabelId);
6412     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6413                    .addReg(NewVReg3, RegState::Kill)
6414                    .addFrameIndex(FI)
6415                    .addImm(36)  // &jbuf[1] :: pc
6416                    .addMemOperand(FIMMOSt));
6417   } else if (isThumb) {
6418     // Incoming value: jbuf
6419     //   ldr.n  r1, LCPI1_4
6420     //   add    r1, pc
6421     //   mov    r2, #1
6422     //   orrs   r1, r2
6423     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6424     //   str    r1, [r2]
6425     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6426     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6427                    .addConstantPoolIndex(CPI)
6428                    .addMemOperand(CPMMO));
6429     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6430     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6431       .addReg(NewVReg1, RegState::Kill)
6432       .addImm(PCLabelId);
6433     // Set the low bit because of thumb mode.
6434     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6435     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6436                    .addReg(ARM::CPSR, RegState::Define)
6437                    .addImm(1));
6438     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6439     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6440                    .addReg(ARM::CPSR, RegState::Define)
6441                    .addReg(NewVReg2, RegState::Kill)
6442                    .addReg(NewVReg3, RegState::Kill));
6443     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6444     BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
6445             .addFrameIndex(FI)
6446             .addImm(36); // &jbuf[1] :: pc
6447     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6448                    .addReg(NewVReg4, RegState::Kill)
6449                    .addReg(NewVReg5, RegState::Kill)
6450                    .addImm(0)
6451                    .addMemOperand(FIMMOSt));
6452   } else {
6453     // Incoming value: jbuf
6454     //   ldr  r1, LCPI1_1
6455     //   add  r1, pc, r1
6456     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6457     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6458     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6459                    .addConstantPoolIndex(CPI)
6460                    .addImm(0)
6461                    .addMemOperand(CPMMO));
6462     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6463     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6464                    .addReg(NewVReg1, RegState::Kill)
6465                    .addImm(PCLabelId));
6466     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6467                    .addReg(NewVReg2, RegState::Kill)
6468                    .addFrameIndex(FI)
6469                    .addImm(36)  // &jbuf[1] :: pc
6470                    .addMemOperand(FIMMOSt));
6471   }
6472 }
6473
6474 MachineBasicBlock *ARMTargetLowering::
6475 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6476   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6477   DebugLoc dl = MI->getDebugLoc();
6478   MachineFunction *MF = MBB->getParent();
6479   MachineRegisterInfo *MRI = &MF->getRegInfo();
6480   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6481   MachineFrameInfo *MFI = MF->getFrameInfo();
6482   int FI = MFI->getFunctionContextIndex();
6483
6484   const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
6485                                                         : &ARM::GPRnopcRegClass;
6486
6487   // Get a mapping of the call site numbers to all of the landing pads they're
6488   // associated with.
6489   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6490   unsigned MaxCSNum = 0;
6491   MachineModuleInfo &MMI = MF->getMMI();
6492   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6493        ++BB) {
6494     if (!BB->isLandingPad()) continue;
6495
6496     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6497     // pad.
6498     for (MachineBasicBlock::iterator
6499            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6500       if (!II->isEHLabel()) continue;
6501
6502       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6503       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6504
6505       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6506       for (SmallVectorImpl<unsigned>::iterator
6507              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6508            CSI != CSE; ++CSI) {
6509         CallSiteNumToLPad[*CSI].push_back(BB);
6510         MaxCSNum = std::max(MaxCSNum, *CSI);
6511       }
6512       break;
6513     }
6514   }
6515
6516   // Get an ordered list of the machine basic blocks for the jump table.
6517   std::vector<MachineBasicBlock*> LPadList;
6518   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6519   LPadList.reserve(CallSiteNumToLPad.size());
6520   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6521     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6522     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6523            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6524       LPadList.push_back(*II);
6525       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6526     }
6527   }
6528
6529   assert(!LPadList.empty() &&
6530          "No landing pad destinations for the dispatch jump table!");
6531
6532   // Create the jump table and associated information.
6533   MachineJumpTableInfo *JTI =
6534     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6535   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6536   unsigned UId = AFI->createJumpTableUId();
6537   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6538
6539   // Create the MBBs for the dispatch code.
6540
6541   // Shove the dispatch's address into the return slot in the function context.
6542   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6543   DispatchBB->setIsLandingPad();
6544
6545   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6546   unsigned trap_opcode;
6547   if (Subtarget->isThumb())
6548     trap_opcode = ARM::tTRAP;
6549   else
6550     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6551
6552   BuildMI(TrapBB, dl, TII->get(trap_opcode));
6553   DispatchBB->addSuccessor(TrapBB);
6554
6555   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6556   DispatchBB->addSuccessor(DispContBB);
6557
6558   // Insert and MBBs.
6559   MF->insert(MF->end(), DispatchBB);
6560   MF->insert(MF->end(), DispContBB);
6561   MF->insert(MF->end(), TrapBB);
6562
6563   // Insert code into the entry block that creates and registers the function
6564   // context.
6565   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6566
6567   MachineMemOperand *FIMMOLd =
6568     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6569                              MachineMemOperand::MOLoad |
6570                              MachineMemOperand::MOVolatile, 4, 4);
6571
6572   MachineInstrBuilder MIB;
6573   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6574
6575   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6576   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6577
6578   // Add a register mask with no preserved registers.  This results in all
6579   // registers being marked as clobbered.
6580   MIB.addRegMask(RI.getNoPreservedMask());
6581
6582   unsigned NumLPads = LPadList.size();
6583   if (Subtarget->isThumb2()) {
6584     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6585     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6586                    .addFrameIndex(FI)
6587                    .addImm(4)
6588                    .addMemOperand(FIMMOLd));
6589
6590     if (NumLPads < 256) {
6591       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6592                      .addReg(NewVReg1)
6593                      .addImm(LPadList.size()));
6594     } else {
6595       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6596       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6597                      .addImm(NumLPads & 0xFFFF));
6598
6599       unsigned VReg2 = VReg1;
6600       if ((NumLPads & 0xFFFF0000) != 0) {
6601         VReg2 = MRI->createVirtualRegister(TRC);
6602         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6603                        .addReg(VReg1)
6604                        .addImm(NumLPads >> 16));
6605       }
6606
6607       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6608                      .addReg(NewVReg1)
6609                      .addReg(VReg2));
6610     }
6611
6612     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6613       .addMBB(TrapBB)
6614       .addImm(ARMCC::HI)
6615       .addReg(ARM::CPSR);
6616
6617     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6618     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6619                    .addJumpTableIndex(MJTI)
6620                    .addImm(UId));
6621
6622     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6623     AddDefaultCC(
6624       AddDefaultPred(
6625         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6626         .addReg(NewVReg3, RegState::Kill)
6627         .addReg(NewVReg1)
6628         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6629
6630     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6631       .addReg(NewVReg4, RegState::Kill)
6632       .addReg(NewVReg1)
6633       .addJumpTableIndex(MJTI)
6634       .addImm(UId);
6635   } else if (Subtarget->isThumb()) {
6636     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6637     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6638                    .addFrameIndex(FI)
6639                    .addImm(1)
6640                    .addMemOperand(FIMMOLd));
6641
6642     if (NumLPads < 256) {
6643       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6644                      .addReg(NewVReg1)
6645                      .addImm(NumLPads));
6646     } else {
6647       MachineConstantPool *ConstantPool = MF->getConstantPool();
6648       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6649       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6650
6651       // MachineConstantPool wants an explicit alignment.
6652       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6653       if (Align == 0)
6654         Align = getDataLayout()->getTypeAllocSize(C->getType());
6655       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6656
6657       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6658       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6659                      .addReg(VReg1, RegState::Define)
6660                      .addConstantPoolIndex(Idx));
6661       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6662                      .addReg(NewVReg1)
6663                      .addReg(VReg1));
6664     }
6665
6666     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6667       .addMBB(TrapBB)
6668       .addImm(ARMCC::HI)
6669       .addReg(ARM::CPSR);
6670
6671     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6672     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6673                    .addReg(ARM::CPSR, RegState::Define)
6674                    .addReg(NewVReg1)
6675                    .addImm(2));
6676
6677     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6678     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6679                    .addJumpTableIndex(MJTI)
6680                    .addImm(UId));
6681
6682     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6683     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6684                    .addReg(ARM::CPSR, RegState::Define)
6685                    .addReg(NewVReg2, RegState::Kill)
6686                    .addReg(NewVReg3));
6687
6688     MachineMemOperand *JTMMOLd =
6689       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6690                                MachineMemOperand::MOLoad, 4, 4);
6691
6692     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6693     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6694                    .addReg(NewVReg4, RegState::Kill)
6695                    .addImm(0)
6696                    .addMemOperand(JTMMOLd));
6697
6698     unsigned NewVReg6 = NewVReg5;
6699     if (RelocM == Reloc::PIC_) {
6700       NewVReg6 = MRI->createVirtualRegister(TRC);
6701       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6702                      .addReg(ARM::CPSR, RegState::Define)
6703                      .addReg(NewVReg5, RegState::Kill)
6704                      .addReg(NewVReg3));
6705     }
6706
6707     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6708       .addReg(NewVReg6, RegState::Kill)
6709       .addJumpTableIndex(MJTI)
6710       .addImm(UId);
6711   } else {
6712     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6713     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6714                    .addFrameIndex(FI)
6715                    .addImm(4)
6716                    .addMemOperand(FIMMOLd));
6717
6718     if (NumLPads < 256) {
6719       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6720                      .addReg(NewVReg1)
6721                      .addImm(NumLPads));
6722     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6723       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6724       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6725                      .addImm(NumLPads & 0xFFFF));
6726
6727       unsigned VReg2 = VReg1;
6728       if ((NumLPads & 0xFFFF0000) != 0) {
6729         VReg2 = MRI->createVirtualRegister(TRC);
6730         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6731                        .addReg(VReg1)
6732                        .addImm(NumLPads >> 16));
6733       }
6734
6735       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6736                      .addReg(NewVReg1)
6737                      .addReg(VReg2));
6738     } else {
6739       MachineConstantPool *ConstantPool = MF->getConstantPool();
6740       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6741       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6742
6743       // MachineConstantPool wants an explicit alignment.
6744       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6745       if (Align == 0)
6746         Align = getDataLayout()->getTypeAllocSize(C->getType());
6747       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6748
6749       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6750       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6751                      .addReg(VReg1, RegState::Define)
6752                      .addConstantPoolIndex(Idx)
6753                      .addImm(0));
6754       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6755                      .addReg(NewVReg1)
6756                      .addReg(VReg1, RegState::Kill));
6757     }
6758
6759     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6760       .addMBB(TrapBB)
6761       .addImm(ARMCC::HI)
6762       .addReg(ARM::CPSR);
6763
6764     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6765     AddDefaultCC(
6766       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6767                      .addReg(NewVReg1)
6768                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6769     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6770     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6771                    .addJumpTableIndex(MJTI)
6772                    .addImm(UId));
6773
6774     MachineMemOperand *JTMMOLd =
6775       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6776                                MachineMemOperand::MOLoad, 4, 4);
6777     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6778     AddDefaultPred(
6779       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6780       .addReg(NewVReg3, RegState::Kill)
6781       .addReg(NewVReg4)
6782       .addImm(0)
6783       .addMemOperand(JTMMOLd));
6784
6785     if (RelocM == Reloc::PIC_) {
6786       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6787         .addReg(NewVReg5, RegState::Kill)
6788         .addReg(NewVReg4)
6789         .addJumpTableIndex(MJTI)
6790         .addImm(UId);
6791     } else {
6792       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6793         .addReg(NewVReg5, RegState::Kill)
6794         .addJumpTableIndex(MJTI)
6795         .addImm(UId);
6796     }
6797   }
6798
6799   // Add the jump table entries as successors to the MBB.
6800   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6801   for (std::vector<MachineBasicBlock*>::iterator
6802          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6803     MachineBasicBlock *CurMBB = *I;
6804     if (SeenMBBs.insert(CurMBB).second)
6805       DispContBB->addSuccessor(CurMBB);
6806   }
6807
6808   // N.B. the order the invoke BBs are processed in doesn't matter here.
6809   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
6810   SmallVector<MachineBasicBlock*, 64> MBBLPads;
6811   for (MachineBasicBlock *BB : InvokeBBs) {
6812
6813     // Remove the landing pad successor from the invoke block and replace it
6814     // with the new dispatch block.
6815     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6816                                                   BB->succ_end());
6817     while (!Successors.empty()) {
6818       MachineBasicBlock *SMBB = Successors.pop_back_val();
6819       if (SMBB->isLandingPad()) {
6820         BB->removeSuccessor(SMBB);
6821         MBBLPads.push_back(SMBB);
6822       }
6823     }
6824
6825     BB->addSuccessor(DispatchBB);
6826
6827     // Find the invoke call and mark all of the callee-saved registers as
6828     // 'implicit defined' so that they're spilled. This prevents code from
6829     // moving instructions to before the EH block, where they will never be
6830     // executed.
6831     for (MachineBasicBlock::reverse_iterator
6832            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6833       if (!II->isCall()) continue;
6834
6835       DenseMap<unsigned, bool> DefRegs;
6836       for (MachineInstr::mop_iterator
6837              OI = II->operands_begin(), OE = II->operands_end();
6838            OI != OE; ++OI) {
6839         if (!OI->isReg()) continue;
6840         DefRegs[OI->getReg()] = true;
6841       }
6842
6843       MachineInstrBuilder MIB(*MF, &*II);
6844
6845       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6846         unsigned Reg = SavedRegs[i];
6847         if (Subtarget->isThumb2() &&
6848             !ARM::tGPRRegClass.contains(Reg) &&
6849             !ARM::hGPRRegClass.contains(Reg))
6850           continue;
6851         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6852           continue;
6853         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6854           continue;
6855         if (!DefRegs[Reg])
6856           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6857       }
6858
6859       break;
6860     }
6861   }
6862
6863   // Mark all former landing pads as non-landing pads. The dispatch is the only
6864   // landing pad now.
6865   for (SmallVectorImpl<MachineBasicBlock*>::iterator
6866          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6867     (*I)->setIsLandingPad(false);
6868
6869   // The instruction is gone now.
6870   MI->eraseFromParent();
6871
6872   return MBB;
6873 }
6874
6875 static
6876 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6877   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6878        E = MBB->succ_end(); I != E; ++I)
6879     if (*I != Succ)
6880       return *I;
6881   llvm_unreachable("Expecting a BB with two successors!");
6882 }
6883
6884 /// Return the load opcode for a given load size. If load size >= 8,
6885 /// neon opcode will be returned.
6886 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
6887   if (LdSize >= 8)
6888     return LdSize == 16 ? ARM::VLD1q32wb_fixed
6889                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
6890   if (IsThumb1)
6891     return LdSize == 4 ? ARM::tLDRi
6892                        : LdSize == 2 ? ARM::tLDRHi
6893                                      : LdSize == 1 ? ARM::tLDRBi : 0;
6894   if (IsThumb2)
6895     return LdSize == 4 ? ARM::t2LDR_POST
6896                        : LdSize == 2 ? ARM::t2LDRH_POST
6897                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
6898   return LdSize == 4 ? ARM::LDR_POST_IMM
6899                      : LdSize == 2 ? ARM::LDRH_POST
6900                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
6901 }
6902
6903 /// Return the store opcode for a given store size. If store size >= 8,
6904 /// neon opcode will be returned.
6905 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
6906   if (StSize >= 8)
6907     return StSize == 16 ? ARM::VST1q32wb_fixed
6908                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
6909   if (IsThumb1)
6910     return StSize == 4 ? ARM::tSTRi
6911                        : StSize == 2 ? ARM::tSTRHi
6912                                      : StSize == 1 ? ARM::tSTRBi : 0;
6913   if (IsThumb2)
6914     return StSize == 4 ? ARM::t2STR_POST
6915                        : StSize == 2 ? ARM::t2STRH_POST
6916                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
6917   return StSize == 4 ? ARM::STR_POST_IMM
6918                      : StSize == 2 ? ARM::STRH_POST
6919                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
6920 }
6921
6922 /// Emit a post-increment load operation with given size. The instructions
6923 /// will be added to BB at Pos.
6924 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
6925                        const TargetInstrInfo *TII, DebugLoc dl,
6926                        unsigned LdSize, unsigned Data, unsigned AddrIn,
6927                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6928   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
6929   assert(LdOpc != 0 && "Should have a load opcode");
6930   if (LdSize >= 8) {
6931     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6932                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6933                        .addImm(0));
6934   } else if (IsThumb1) {
6935     // load + update AddrIn
6936     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6937                        .addReg(AddrIn).addImm(0));
6938     MachineInstrBuilder MIB =
6939         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6940     MIB = AddDefaultT1CC(MIB);
6941     MIB.addReg(AddrIn).addImm(LdSize);
6942     AddDefaultPred(MIB);
6943   } else if (IsThumb2) {
6944     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6945                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6946                        .addImm(LdSize));
6947   } else { // arm
6948     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6949                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6950                        .addReg(0).addImm(LdSize));
6951   }
6952 }
6953
6954 /// Emit a post-increment store operation with given size. The instructions
6955 /// will be added to BB at Pos.
6956 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
6957                        const TargetInstrInfo *TII, DebugLoc dl,
6958                        unsigned StSize, unsigned Data, unsigned AddrIn,
6959                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6960   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
6961   assert(StOpc != 0 && "Should have a store opcode");
6962   if (StSize >= 8) {
6963     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6964                        .addReg(AddrIn).addImm(0).addReg(Data));
6965   } else if (IsThumb1) {
6966     // store + update AddrIn
6967     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
6968                        .addReg(AddrIn).addImm(0));
6969     MachineInstrBuilder MIB =
6970         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6971     MIB = AddDefaultT1CC(MIB);
6972     MIB.addReg(AddrIn).addImm(StSize);
6973     AddDefaultPred(MIB);
6974   } else if (IsThumb2) {
6975     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6976                        .addReg(Data).addReg(AddrIn).addImm(StSize));
6977   } else { // arm
6978     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6979                        .addReg(Data).addReg(AddrIn).addReg(0)
6980                        .addImm(StSize));
6981   }
6982 }
6983
6984 MachineBasicBlock *
6985 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
6986                                    MachineBasicBlock *BB) const {
6987   // This pseudo instruction has 3 operands: dst, src, size
6988   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
6989   // Otherwise, we will generate unrolled scalar copies.
6990   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6991   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6992   MachineFunction::iterator It = BB;
6993   ++It;
6994
6995   unsigned dest = MI->getOperand(0).getReg();
6996   unsigned src = MI->getOperand(1).getReg();
6997   unsigned SizeVal = MI->getOperand(2).getImm();
6998   unsigned Align = MI->getOperand(3).getImm();
6999   DebugLoc dl = MI->getDebugLoc();
7000
7001   MachineFunction *MF = BB->getParent();
7002   MachineRegisterInfo &MRI = MF->getRegInfo();
7003   unsigned UnitSize = 0;
7004   const TargetRegisterClass *TRC = nullptr;
7005   const TargetRegisterClass *VecTRC = nullptr;
7006
7007   bool IsThumb1 = Subtarget->isThumb1Only();
7008   bool IsThumb2 = Subtarget->isThumb2();
7009
7010   if (Align & 1) {
7011     UnitSize = 1;
7012   } else if (Align & 2) {
7013     UnitSize = 2;
7014   } else {
7015     // Check whether we can use NEON instructions.
7016     if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
7017         Subtarget->hasNEON()) {
7018       if ((Align % 16 == 0) && SizeVal >= 16)
7019         UnitSize = 16;
7020       else if ((Align % 8 == 0) && SizeVal >= 8)
7021         UnitSize = 8;
7022     }
7023     // Can't use NEON instructions.
7024     if (UnitSize == 0)
7025       UnitSize = 4;
7026   }
7027
7028   // Select the correct opcode and register class for unit size load/store
7029   bool IsNeon = UnitSize >= 8;
7030   TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
7031   if (IsNeon)
7032     VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
7033                             : UnitSize == 8 ? &ARM::DPRRegClass
7034                                             : nullptr;
7035
7036   unsigned BytesLeft = SizeVal % UnitSize;
7037   unsigned LoopSize = SizeVal - BytesLeft;
7038
7039   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7040     // Use LDR and STR to copy.
7041     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7042     // [destOut] = STR_POST(scratch, destIn, UnitSize)
7043     unsigned srcIn = src;
7044     unsigned destIn = dest;
7045     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7046       unsigned srcOut = MRI.createVirtualRegister(TRC);
7047       unsigned destOut = MRI.createVirtualRegister(TRC);
7048       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7049       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7050                  IsThumb1, IsThumb2);
7051       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7052                  IsThumb1, IsThumb2);
7053       srcIn = srcOut;
7054       destIn = destOut;
7055     }
7056
7057     // Handle the leftover bytes with LDRB and STRB.
7058     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7059     // [destOut] = STRB_POST(scratch, destIn, 1)
7060     for (unsigned i = 0; i < BytesLeft; i++) {
7061       unsigned srcOut = MRI.createVirtualRegister(TRC);
7062       unsigned destOut = MRI.createVirtualRegister(TRC);
7063       unsigned scratch = MRI.createVirtualRegister(TRC);
7064       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7065                  IsThumb1, IsThumb2);
7066       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7067                  IsThumb1, IsThumb2);
7068       srcIn = srcOut;
7069       destIn = destOut;
7070     }
7071     MI->eraseFromParent();   // The instruction is gone now.
7072     return BB;
7073   }
7074
7075   // Expand the pseudo op to a loop.
7076   // thisMBB:
7077   //   ...
7078   //   movw varEnd, # --> with thumb2
7079   //   movt varEnd, #
7080   //   ldrcp varEnd, idx --> without thumb2
7081   //   fallthrough --> loopMBB
7082   // loopMBB:
7083   //   PHI varPhi, varEnd, varLoop
7084   //   PHI srcPhi, src, srcLoop
7085   //   PHI destPhi, dst, destLoop
7086   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7087   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7088   //   subs varLoop, varPhi, #UnitSize
7089   //   bne loopMBB
7090   //   fallthrough --> exitMBB
7091   // exitMBB:
7092   //   epilogue to handle left-over bytes
7093   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7094   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7095   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7096   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7097   MF->insert(It, loopMBB);
7098   MF->insert(It, exitMBB);
7099
7100   // Transfer the remainder of BB and its successor edges to exitMBB.
7101   exitMBB->splice(exitMBB->begin(), BB,
7102                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7103   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7104
7105   // Load an immediate to varEnd.
7106   unsigned varEnd = MRI.createVirtualRegister(TRC);
7107   if (IsThumb2) {
7108     unsigned Vtmp = varEnd;
7109     if ((LoopSize & 0xFFFF0000) != 0)
7110       Vtmp = MRI.createVirtualRegister(TRC);
7111     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp)
7112                        .addImm(LoopSize & 0xFFFF));
7113
7114     if ((LoopSize & 0xFFFF0000) != 0)
7115       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7116                          .addReg(Vtmp).addImm(LoopSize >> 16));
7117   } else {
7118     MachineConstantPool *ConstantPool = MF->getConstantPool();
7119     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7120     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7121
7122     // MachineConstantPool wants an explicit alignment.
7123     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7124     if (Align == 0)
7125       Align = getDataLayout()->getTypeAllocSize(C->getType());
7126     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7127
7128     if (IsThumb1)
7129       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7130           varEnd, RegState::Define).addConstantPoolIndex(Idx));
7131     else
7132       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7133           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7134   }
7135   BB->addSuccessor(loopMBB);
7136
7137   // Generate the loop body:
7138   //   varPhi = PHI(varLoop, varEnd)
7139   //   srcPhi = PHI(srcLoop, src)
7140   //   destPhi = PHI(destLoop, dst)
7141   MachineBasicBlock *entryBB = BB;
7142   BB = loopMBB;
7143   unsigned varLoop = MRI.createVirtualRegister(TRC);
7144   unsigned varPhi = MRI.createVirtualRegister(TRC);
7145   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7146   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7147   unsigned destLoop = MRI.createVirtualRegister(TRC);
7148   unsigned destPhi = MRI.createVirtualRegister(TRC);
7149
7150   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7151     .addReg(varLoop).addMBB(loopMBB)
7152     .addReg(varEnd).addMBB(entryBB);
7153   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7154     .addReg(srcLoop).addMBB(loopMBB)
7155     .addReg(src).addMBB(entryBB);
7156   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7157     .addReg(destLoop).addMBB(loopMBB)
7158     .addReg(dest).addMBB(entryBB);
7159
7160   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7161   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7162   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7163   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7164              IsThumb1, IsThumb2);
7165   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7166              IsThumb1, IsThumb2);
7167
7168   // Decrement loop variable by UnitSize.
7169   if (IsThumb1) {
7170     MachineInstrBuilder MIB =
7171         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7172     MIB = AddDefaultT1CC(MIB);
7173     MIB.addReg(varPhi).addImm(UnitSize);
7174     AddDefaultPred(MIB);
7175   } else {
7176     MachineInstrBuilder MIB =
7177         BuildMI(*BB, BB->end(), dl,
7178                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7179     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7180     MIB->getOperand(5).setReg(ARM::CPSR);
7181     MIB->getOperand(5).setIsDef(true);
7182   }
7183   BuildMI(*BB, BB->end(), dl,
7184           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7185       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7186
7187   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7188   BB->addSuccessor(loopMBB);
7189   BB->addSuccessor(exitMBB);
7190
7191   // Add epilogue to handle BytesLeft.
7192   BB = exitMBB;
7193   MachineInstr *StartOfExit = exitMBB->begin();
7194
7195   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7196   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7197   unsigned srcIn = srcLoop;
7198   unsigned destIn = destLoop;
7199   for (unsigned i = 0; i < BytesLeft; i++) {
7200     unsigned srcOut = MRI.createVirtualRegister(TRC);
7201     unsigned destOut = MRI.createVirtualRegister(TRC);
7202     unsigned scratch = MRI.createVirtualRegister(TRC);
7203     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7204                IsThumb1, IsThumb2);
7205     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7206                IsThumb1, IsThumb2);
7207     srcIn = srcOut;
7208     destIn = destOut;
7209   }
7210
7211   MI->eraseFromParent();   // The instruction is gone now.
7212   return BB;
7213 }
7214
7215 MachineBasicBlock *
7216 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7217                                        MachineBasicBlock *MBB) const {
7218   const TargetMachine &TM = getTargetMachine();
7219   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
7220   DebugLoc DL = MI->getDebugLoc();
7221
7222   assert(Subtarget->isTargetWindows() &&
7223          "__chkstk is only supported on Windows");
7224   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7225
7226   // __chkstk takes the number of words to allocate on the stack in R4, and
7227   // returns the stack adjustment in number of bytes in R4.  This will not
7228   // clober any other registers (other than the obvious lr).
7229   //
7230   // Although, technically, IP should be considered a register which may be
7231   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
7232   // thumb-2 environment, so there is no interworking required.  As a result, we
7233   // do not expect a veneer to be emitted by the linker, clobbering IP.
7234   //
7235   // Each module receives its own copy of __chkstk, so no import thunk is
7236   // required, again, ensuring that IP is not clobbered.
7237   //
7238   // Finally, although some linkers may theoretically provide a trampoline for
7239   // out of range calls (which is quite common due to a 32M range limitation of
7240   // branches for Thumb), we can generate the long-call version via
7241   // -mcmodel=large, alleviating the need for the trampoline which may clobber
7242   // IP.
7243
7244   switch (TM.getCodeModel()) {
7245   case CodeModel::Small:
7246   case CodeModel::Medium:
7247   case CodeModel::Default:
7248   case CodeModel::Kernel:
7249     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7250       .addImm((unsigned)ARMCC::AL).addReg(0)
7251       .addExternalSymbol("__chkstk")
7252       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7253       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7254       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7255     break;
7256   case CodeModel::Large:
7257   case CodeModel::JITDefault: {
7258     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7259     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7260
7261     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7262       .addExternalSymbol("__chkstk");
7263     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7264       .addImm((unsigned)ARMCC::AL).addReg(0)
7265       .addReg(Reg, RegState::Kill)
7266       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7267       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7268       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7269     break;
7270   }
7271   }
7272
7273   AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7274                                       ARM::SP)
7275                               .addReg(ARM::SP).addReg(ARM::R4)));
7276
7277   MI->eraseFromParent();
7278   return MBB;
7279 }
7280
7281 MachineBasicBlock *
7282 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7283                                                MachineBasicBlock *BB) const {
7284   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7285   DebugLoc dl = MI->getDebugLoc();
7286   bool isThumb2 = Subtarget->isThumb2();
7287   switch (MI->getOpcode()) {
7288   default: {
7289     MI->dump();
7290     llvm_unreachable("Unexpected instr type to insert");
7291   }
7292   // The Thumb2 pre-indexed stores have the same MI operands, they just
7293   // define them differently in the .td files from the isel patterns, so
7294   // they need pseudos.
7295   case ARM::t2STR_preidx:
7296     MI->setDesc(TII->get(ARM::t2STR_PRE));
7297     return BB;
7298   case ARM::t2STRB_preidx:
7299     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7300     return BB;
7301   case ARM::t2STRH_preidx:
7302     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7303     return BB;
7304
7305   case ARM::STRi_preidx:
7306   case ARM::STRBi_preidx: {
7307     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7308       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7309     // Decode the offset.
7310     unsigned Offset = MI->getOperand(4).getImm();
7311     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7312     Offset = ARM_AM::getAM2Offset(Offset);
7313     if (isSub)
7314       Offset = -Offset;
7315
7316     MachineMemOperand *MMO = *MI->memoperands_begin();
7317     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7318       .addOperand(MI->getOperand(0))  // Rn_wb
7319       .addOperand(MI->getOperand(1))  // Rt
7320       .addOperand(MI->getOperand(2))  // Rn
7321       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7322       .addOperand(MI->getOperand(5))  // pred
7323       .addOperand(MI->getOperand(6))
7324       .addMemOperand(MMO);
7325     MI->eraseFromParent();
7326     return BB;
7327   }
7328   case ARM::STRr_preidx:
7329   case ARM::STRBr_preidx:
7330   case ARM::STRH_preidx: {
7331     unsigned NewOpc;
7332     switch (MI->getOpcode()) {
7333     default: llvm_unreachable("unexpected opcode!");
7334     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7335     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7336     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7337     }
7338     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7339     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7340       MIB.addOperand(MI->getOperand(i));
7341     MI->eraseFromParent();
7342     return BB;
7343   }
7344
7345   case ARM::tMOVCCr_pseudo: {
7346     // To "insert" a SELECT_CC instruction, we actually have to insert the
7347     // diamond control-flow pattern.  The incoming instruction knows the
7348     // destination vreg to set, the condition code register to branch on, the
7349     // true/false values to select between, and a branch opcode to use.
7350     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7351     MachineFunction::iterator It = BB;
7352     ++It;
7353
7354     //  thisMBB:
7355     //  ...
7356     //   TrueVal = ...
7357     //   cmpTY ccX, r1, r2
7358     //   bCC copy1MBB
7359     //   fallthrough --> copy0MBB
7360     MachineBasicBlock *thisMBB  = BB;
7361     MachineFunction *F = BB->getParent();
7362     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7363     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7364     F->insert(It, copy0MBB);
7365     F->insert(It, sinkMBB);
7366
7367     // Transfer the remainder of BB and its successor edges to sinkMBB.
7368     sinkMBB->splice(sinkMBB->begin(), BB,
7369                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7370     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7371
7372     BB->addSuccessor(copy0MBB);
7373     BB->addSuccessor(sinkMBB);
7374
7375     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7376       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7377
7378     //  copy0MBB:
7379     //   %FalseValue = ...
7380     //   # fallthrough to sinkMBB
7381     BB = copy0MBB;
7382
7383     // Update machine-CFG edges
7384     BB->addSuccessor(sinkMBB);
7385
7386     //  sinkMBB:
7387     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7388     //  ...
7389     BB = sinkMBB;
7390     BuildMI(*BB, BB->begin(), dl,
7391             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7392       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7393       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7394
7395     MI->eraseFromParent();   // The pseudo instruction is gone now.
7396     return BB;
7397   }
7398
7399   case ARM::BCCi64:
7400   case ARM::BCCZi64: {
7401     // If there is an unconditional branch to the other successor, remove it.
7402     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7403
7404     // Compare both parts that make up the double comparison separately for
7405     // equality.
7406     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7407
7408     unsigned LHS1 = MI->getOperand(1).getReg();
7409     unsigned LHS2 = MI->getOperand(2).getReg();
7410     if (RHSisZero) {
7411       AddDefaultPred(BuildMI(BB, dl,
7412                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7413                      .addReg(LHS1).addImm(0));
7414       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7415         .addReg(LHS2).addImm(0)
7416         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7417     } else {
7418       unsigned RHS1 = MI->getOperand(3).getReg();
7419       unsigned RHS2 = MI->getOperand(4).getReg();
7420       AddDefaultPred(BuildMI(BB, dl,
7421                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7422                      .addReg(LHS1).addReg(RHS1));
7423       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7424         .addReg(LHS2).addReg(RHS2)
7425         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7426     }
7427
7428     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7429     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7430     if (MI->getOperand(0).getImm() == ARMCC::NE)
7431       std::swap(destMBB, exitMBB);
7432
7433     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7434       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7435     if (isThumb2)
7436       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7437     else
7438       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7439
7440     MI->eraseFromParent();   // The pseudo instruction is gone now.
7441     return BB;
7442   }
7443
7444   case ARM::Int_eh_sjlj_setjmp:
7445   case ARM::Int_eh_sjlj_setjmp_nofp:
7446   case ARM::tInt_eh_sjlj_setjmp:
7447   case ARM::t2Int_eh_sjlj_setjmp:
7448   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7449     EmitSjLjDispatchBlock(MI, BB);
7450     return BB;
7451
7452   case ARM::ABS:
7453   case ARM::t2ABS: {
7454     // To insert an ABS instruction, we have to insert the
7455     // diamond control-flow pattern.  The incoming instruction knows the
7456     // source vreg to test against 0, the destination vreg to set,
7457     // the condition code register to branch on, the
7458     // true/false values to select between, and a branch opcode to use.
7459     // It transforms
7460     //     V1 = ABS V0
7461     // into
7462     //     V2 = MOVS V0
7463     //     BCC                      (branch to SinkBB if V0 >= 0)
7464     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7465     //     SinkBB: V1 = PHI(V2, V3)
7466     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7467     MachineFunction::iterator BBI = BB;
7468     ++BBI;
7469     MachineFunction *Fn = BB->getParent();
7470     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7471     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7472     Fn->insert(BBI, RSBBB);
7473     Fn->insert(BBI, SinkBB);
7474
7475     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7476     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7477     bool isThumb2 = Subtarget->isThumb2();
7478     MachineRegisterInfo &MRI = Fn->getRegInfo();
7479     // In Thumb mode S must not be specified if source register is the SP or
7480     // PC and if destination register is the SP, so restrict register class
7481     unsigned NewRsbDstReg =
7482       MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
7483
7484     // Transfer the remainder of BB and its successor edges to sinkMBB.
7485     SinkBB->splice(SinkBB->begin(), BB,
7486                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
7487     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7488
7489     BB->addSuccessor(RSBBB);
7490     BB->addSuccessor(SinkBB);
7491
7492     // fall through to SinkMBB
7493     RSBBB->addSuccessor(SinkBB);
7494
7495     // insert a cmp at the end of BB
7496     AddDefaultPred(BuildMI(BB, dl,
7497                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7498                    .addReg(ABSSrcReg).addImm(0));
7499
7500     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7501     BuildMI(BB, dl,
7502       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7503       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7504
7505     // insert rsbri in RSBBB
7506     // Note: BCC and rsbri will be converted into predicated rsbmi
7507     // by if-conversion pass
7508     BuildMI(*RSBBB, RSBBB->begin(), dl,
7509       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7510       .addReg(ABSSrcReg, RegState::Kill)
7511       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7512
7513     // insert PHI in SinkBB,
7514     // reuse ABSDstReg to not change uses of ABS instruction
7515     BuildMI(*SinkBB, SinkBB->begin(), dl,
7516       TII->get(ARM::PHI), ABSDstReg)
7517       .addReg(NewRsbDstReg).addMBB(RSBBB)
7518       .addReg(ABSSrcReg).addMBB(BB);
7519
7520     // remove ABS instruction
7521     MI->eraseFromParent();
7522
7523     // return last added BB
7524     return SinkBB;
7525   }
7526   case ARM::COPY_STRUCT_BYVAL_I32:
7527     ++NumLoopByVals;
7528     return EmitStructByval(MI, BB);
7529   case ARM::WIN__CHKSTK:
7530     return EmitLowered__chkstk(MI, BB);
7531   }
7532 }
7533
7534 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7535                                                       SDNode *Node) const {
7536   const MCInstrDesc *MCID = &MI->getDesc();
7537   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7538   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7539   // operand is still set to noreg. If needed, set the optional operand's
7540   // register to CPSR, and remove the redundant implicit def.
7541   //
7542   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7543
7544   // Rename pseudo opcodes.
7545   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7546   if (NewOpc) {
7547     const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
7548     MCID = &TII->get(NewOpc);
7549
7550     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7551            "converted opcode should be the same except for cc_out");
7552
7553     MI->setDesc(*MCID);
7554
7555     // Add the optional cc_out operand
7556     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7557   }
7558   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7559
7560   // Any ARM instruction that sets the 's' bit should specify an optional
7561   // "cc_out" operand in the last operand position.
7562   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7563     assert(!NewOpc && "Optional cc_out operand required");
7564     return;
7565   }
7566   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7567   // since we already have an optional CPSR def.
7568   bool definesCPSR = false;
7569   bool deadCPSR = false;
7570   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7571        i != e; ++i) {
7572     const MachineOperand &MO = MI->getOperand(i);
7573     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7574       definesCPSR = true;
7575       if (MO.isDead())
7576         deadCPSR = true;
7577       MI->RemoveOperand(i);
7578       break;
7579     }
7580   }
7581   if (!definesCPSR) {
7582     assert(!NewOpc && "Optional cc_out operand required");
7583     return;
7584   }
7585   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7586   if (deadCPSR) {
7587     assert(!MI->getOperand(ccOutIdx).getReg() &&
7588            "expect uninitialized optional cc_out operand");
7589     return;
7590   }
7591
7592   // If this instruction was defined with an optional CPSR def and its dag node
7593   // had a live implicit CPSR def, then activate the optional CPSR def.
7594   MachineOperand &MO = MI->getOperand(ccOutIdx);
7595   MO.setReg(ARM::CPSR);
7596   MO.setIsDef(true);
7597 }
7598
7599 //===----------------------------------------------------------------------===//
7600 //                           ARM Optimization Hooks
7601 //===----------------------------------------------------------------------===//
7602
7603 // Helper function that checks if N is a null or all ones constant.
7604 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7605   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7606   if (!C)
7607     return false;
7608   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7609 }
7610
7611 // Return true if N is conditionally 0 or all ones.
7612 // Detects these expressions where cc is an i1 value:
7613 //
7614 //   (select cc 0, y)   [AllOnes=0]
7615 //   (select cc y, 0)   [AllOnes=0]
7616 //   (zext cc)          [AllOnes=0]
7617 //   (sext cc)          [AllOnes=0/1]
7618 //   (select cc -1, y)  [AllOnes=1]
7619 //   (select cc y, -1)  [AllOnes=1]
7620 //
7621 // Invert is set when N is the null/all ones constant when CC is false.
7622 // OtherOp is set to the alternative value of N.
7623 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7624                                        SDValue &CC, bool &Invert,
7625                                        SDValue &OtherOp,
7626                                        SelectionDAG &DAG) {
7627   switch (N->getOpcode()) {
7628   default: return false;
7629   case ISD::SELECT: {
7630     CC = N->getOperand(0);
7631     SDValue N1 = N->getOperand(1);
7632     SDValue N2 = N->getOperand(2);
7633     if (isZeroOrAllOnes(N1, AllOnes)) {
7634       Invert = false;
7635       OtherOp = N2;
7636       return true;
7637     }
7638     if (isZeroOrAllOnes(N2, AllOnes)) {
7639       Invert = true;
7640       OtherOp = N1;
7641       return true;
7642     }
7643     return false;
7644   }
7645   case ISD::ZERO_EXTEND:
7646     // (zext cc) can never be the all ones value.
7647     if (AllOnes)
7648       return false;
7649     // Fall through.
7650   case ISD::SIGN_EXTEND: {
7651     EVT VT = N->getValueType(0);
7652     CC = N->getOperand(0);
7653     if (CC.getValueType() != MVT::i1)
7654       return false;
7655     Invert = !AllOnes;
7656     if (AllOnes)
7657       // When looking for an AllOnes constant, N is an sext, and the 'other'
7658       // value is 0.
7659       OtherOp = DAG.getConstant(0, VT);
7660     else if (N->getOpcode() == ISD::ZERO_EXTEND)
7661       // When looking for a 0 constant, N can be zext or sext.
7662       OtherOp = DAG.getConstant(1, VT);
7663     else
7664       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7665     return true;
7666   }
7667   }
7668 }
7669
7670 // Combine a constant select operand into its use:
7671 //
7672 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
7673 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
7674 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
7675 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
7676 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
7677 //
7678 // The transform is rejected if the select doesn't have a constant operand that
7679 // is null, or all ones when AllOnes is set.
7680 //
7681 // Also recognize sext/zext from i1:
7682 //
7683 //   (add (zext cc), x) -> (select cc (add x, 1), x)
7684 //   (add (sext cc), x) -> (select cc (add x, -1), x)
7685 //
7686 // These transformations eventually create predicated instructions.
7687 //
7688 // @param N       The node to transform.
7689 // @param Slct    The N operand that is a select.
7690 // @param OtherOp The other N operand (x above).
7691 // @param DCI     Context.
7692 // @param AllOnes Require the select constant to be all ones instead of null.
7693 // @returns The new node, or SDValue() on failure.
7694 static
7695 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7696                             TargetLowering::DAGCombinerInfo &DCI,
7697                             bool AllOnes = false) {
7698   SelectionDAG &DAG = DCI.DAG;
7699   EVT VT = N->getValueType(0);
7700   SDValue NonConstantVal;
7701   SDValue CCOp;
7702   bool SwapSelectOps;
7703   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7704                                   NonConstantVal, DAG))
7705     return SDValue();
7706
7707   // Slct is now know to be the desired identity constant when CC is true.
7708   SDValue TrueVal = OtherOp;
7709   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7710                                  OtherOp, NonConstantVal);
7711   // Unless SwapSelectOps says CC should be false.
7712   if (SwapSelectOps)
7713     std::swap(TrueVal, FalseVal);
7714
7715   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7716                      CCOp, TrueVal, FalseVal);
7717 }
7718
7719 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7720 static
7721 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7722                                        TargetLowering::DAGCombinerInfo &DCI) {
7723   SDValue N0 = N->getOperand(0);
7724   SDValue N1 = N->getOperand(1);
7725   if (N0.getNode()->hasOneUse()) {
7726     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7727     if (Result.getNode())
7728       return Result;
7729   }
7730   if (N1.getNode()->hasOneUse()) {
7731     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7732     if (Result.getNode())
7733       return Result;
7734   }
7735   return SDValue();
7736 }
7737
7738 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7739 // (only after legalization).
7740 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7741                                  TargetLowering::DAGCombinerInfo &DCI,
7742                                  const ARMSubtarget *Subtarget) {
7743
7744   // Only perform optimization if after legalize, and if NEON is available. We
7745   // also expected both operands to be BUILD_VECTORs.
7746   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7747       || N0.getOpcode() != ISD::BUILD_VECTOR
7748       || N1.getOpcode() != ISD::BUILD_VECTOR)
7749     return SDValue();
7750
7751   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7752   EVT VT = N->getValueType(0);
7753   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7754     return SDValue();
7755
7756   // Check that the vector operands are of the right form.
7757   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7758   // operands, where N is the size of the formed vector.
7759   // Each EXTRACT_VECTOR should have the same input vector and odd or even
7760   // index such that we have a pair wise add pattern.
7761
7762   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7763   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7764     return SDValue();
7765   SDValue Vec = N0->getOperand(0)->getOperand(0);
7766   SDNode *V = Vec.getNode();
7767   unsigned nextIndex = 0;
7768
7769   // For each operands to the ADD which are BUILD_VECTORs,
7770   // check to see if each of their operands are an EXTRACT_VECTOR with
7771   // the same vector and appropriate index.
7772   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7773     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7774         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7775
7776       SDValue ExtVec0 = N0->getOperand(i);
7777       SDValue ExtVec1 = N1->getOperand(i);
7778
7779       // First operand is the vector, verify its the same.
7780       if (V != ExtVec0->getOperand(0).getNode() ||
7781           V != ExtVec1->getOperand(0).getNode())
7782         return SDValue();
7783
7784       // Second is the constant, verify its correct.
7785       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7786       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7787
7788       // For the constant, we want to see all the even or all the odd.
7789       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7790           || C1->getZExtValue() != nextIndex+1)
7791         return SDValue();
7792
7793       // Increment index.
7794       nextIndex+=2;
7795     } else
7796       return SDValue();
7797   }
7798
7799   // Create VPADDL node.
7800   SelectionDAG &DAG = DCI.DAG;
7801   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7802
7803   // Build operand list.
7804   SmallVector<SDValue, 8> Ops;
7805   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7806                                 TLI.getPointerTy()));
7807
7808   // Input is the vector.
7809   Ops.push_back(Vec);
7810
7811   // Get widened type and narrowed type.
7812   MVT widenType;
7813   unsigned numElem = VT.getVectorNumElements();
7814   
7815   EVT inputLaneType = Vec.getValueType().getVectorElementType();
7816   switch (inputLaneType.getSimpleVT().SimpleTy) {
7817     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7818     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7819     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7820     default:
7821       llvm_unreachable("Invalid vector element type for padd optimization.");
7822   }
7823
7824   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), widenType, Ops);
7825   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
7826   return DAG.getNode(ExtOp, SDLoc(N), VT, tmp);
7827 }
7828
7829 static SDValue findMUL_LOHI(SDValue V) {
7830   if (V->getOpcode() == ISD::UMUL_LOHI ||
7831       V->getOpcode() == ISD::SMUL_LOHI)
7832     return V;
7833   return SDValue();
7834 }
7835
7836 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7837                                      TargetLowering::DAGCombinerInfo &DCI,
7838                                      const ARMSubtarget *Subtarget) {
7839
7840   if (Subtarget->isThumb1Only()) return SDValue();
7841
7842   // Only perform the checks after legalize when the pattern is available.
7843   if (DCI.isBeforeLegalize()) return SDValue();
7844
7845   // Look for multiply add opportunities.
7846   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7847   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7848   // a glue link from the first add to the second add.
7849   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7850   // a S/UMLAL instruction.
7851   //          loAdd   UMUL_LOHI
7852   //            \    / :lo    \ :hi
7853   //             \  /          \          [no multiline comment]
7854   //              ADDC         |  hiAdd
7855   //                 \ :glue  /  /
7856   //                  \      /  /
7857   //                    ADDE
7858   //
7859   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7860   SDValue AddcOp0 = AddcNode->getOperand(0);
7861   SDValue AddcOp1 = AddcNode->getOperand(1);
7862
7863   // Check if the two operands are from the same mul_lohi node.
7864   if (AddcOp0.getNode() == AddcOp1.getNode())
7865     return SDValue();
7866
7867   assert(AddcNode->getNumValues() == 2 &&
7868          AddcNode->getValueType(0) == MVT::i32 &&
7869          "Expect ADDC with two result values. First: i32");
7870
7871   // Check that we have a glued ADDC node.
7872   if (AddcNode->getValueType(1) != MVT::Glue)
7873     return SDValue();
7874
7875   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7876   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7877       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7878       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7879       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7880     return SDValue();
7881
7882   // Look for the glued ADDE.
7883   SDNode* AddeNode = AddcNode->getGluedUser();
7884   if (!AddeNode)
7885     return SDValue();
7886
7887   // Make sure it is really an ADDE.
7888   if (AddeNode->getOpcode() != ISD::ADDE)
7889     return SDValue();
7890
7891   assert(AddeNode->getNumOperands() == 3 &&
7892          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
7893          "ADDE node has the wrong inputs");
7894
7895   // Check for the triangle shape.
7896   SDValue AddeOp0 = AddeNode->getOperand(0);
7897   SDValue AddeOp1 = AddeNode->getOperand(1);
7898
7899   // Make sure that the ADDE operands are not coming from the same node.
7900   if (AddeOp0.getNode() == AddeOp1.getNode())
7901     return SDValue();
7902
7903   // Find the MUL_LOHI node walking up ADDE's operands.
7904   bool IsLeftOperandMUL = false;
7905   SDValue MULOp = findMUL_LOHI(AddeOp0);
7906   if (MULOp == SDValue())
7907    MULOp = findMUL_LOHI(AddeOp1);
7908   else
7909     IsLeftOperandMUL = true;
7910   if (MULOp == SDValue())
7911     return SDValue();
7912
7913   // Figure out the right opcode.
7914   unsigned Opc = MULOp->getOpcode();
7915   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
7916
7917   // Figure out the high and low input values to the MLAL node.
7918   SDValue* HiAdd = nullptr;
7919   SDValue* LoMul = nullptr;
7920   SDValue* LowAdd = nullptr;
7921
7922   // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
7923   if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
7924     return SDValue();
7925
7926   if (IsLeftOperandMUL)
7927     HiAdd = &AddeOp1;
7928   else
7929     HiAdd = &AddeOp0;
7930
7931
7932   // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
7933   // whose low result is fed to the ADDC we are checking.
7934
7935   if (AddcOp0 == MULOp.getValue(0)) {
7936     LoMul = &AddcOp0;
7937     LowAdd = &AddcOp1;
7938   }
7939   if (AddcOp1 == MULOp.getValue(0)) {
7940     LoMul = &AddcOp1;
7941     LowAdd = &AddcOp0;
7942   }
7943
7944   if (!LoMul)
7945     return SDValue();
7946
7947   // Create the merged node.
7948   SelectionDAG &DAG = DCI.DAG;
7949
7950   // Build operand list.
7951   SmallVector<SDValue, 8> Ops;
7952   Ops.push_back(LoMul->getOperand(0));
7953   Ops.push_back(LoMul->getOperand(1));
7954   Ops.push_back(*LowAdd);
7955   Ops.push_back(*HiAdd);
7956
7957   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
7958                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
7959
7960   // Replace the ADDs' nodes uses by the MLA node's values.
7961   SDValue HiMLALResult(MLALNode.getNode(), 1);
7962   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
7963
7964   SDValue LoMLALResult(MLALNode.getNode(), 0);
7965   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
7966
7967   // Return original node to notify the driver to stop replacing.
7968   SDValue resNode(AddcNode, 0);
7969   return resNode;
7970 }
7971
7972 /// PerformADDCCombine - Target-specific dag combine transform from
7973 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
7974 static SDValue PerformADDCCombine(SDNode *N,
7975                                  TargetLowering::DAGCombinerInfo &DCI,
7976                                  const ARMSubtarget *Subtarget) {
7977
7978   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
7979
7980 }
7981
7982 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
7983 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
7984 /// called with the default operands, and if that fails, with commuted
7985 /// operands.
7986 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
7987                                           TargetLowering::DAGCombinerInfo &DCI,
7988                                           const ARMSubtarget *Subtarget){
7989
7990   // Attempt to create vpaddl for this add.
7991   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
7992   if (Result.getNode())
7993     return Result;
7994
7995   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7996   if (N0.getNode()->hasOneUse()) {
7997     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
7998     if (Result.getNode()) return Result;
7999   }
8000   return SDValue();
8001 }
8002
8003 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8004 ///
8005 static SDValue PerformADDCombine(SDNode *N,
8006                                  TargetLowering::DAGCombinerInfo &DCI,
8007                                  const ARMSubtarget *Subtarget) {
8008   SDValue N0 = N->getOperand(0);
8009   SDValue N1 = N->getOperand(1);
8010
8011   // First try with the default operand order.
8012   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8013   if (Result.getNode())
8014     return Result;
8015
8016   // If that didn't work, try again with the operands commuted.
8017   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8018 }
8019
8020 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8021 ///
8022 static SDValue PerformSUBCombine(SDNode *N,
8023                                  TargetLowering::DAGCombinerInfo &DCI) {
8024   SDValue N0 = N->getOperand(0);
8025   SDValue N1 = N->getOperand(1);
8026
8027   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8028   if (N1.getNode()->hasOneUse()) {
8029     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8030     if (Result.getNode()) return Result;
8031   }
8032
8033   return SDValue();
8034 }
8035
8036 /// PerformVMULCombine
8037 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8038 /// special multiplier accumulator forwarding.
8039 ///   vmul d3, d0, d2
8040 ///   vmla d3, d1, d2
8041 /// is faster than
8042 ///   vadd d3, d0, d1
8043 ///   vmul d3, d3, d2
8044 //  However, for (A + B) * (A + B),
8045 //    vadd d2, d0, d1
8046 //    vmul d3, d0, d2
8047 //    vmla d3, d1, d2
8048 //  is slower than
8049 //    vadd d2, d0, d1
8050 //    vmul d3, d2, d2
8051 static SDValue PerformVMULCombine(SDNode *N,
8052                                   TargetLowering::DAGCombinerInfo &DCI,
8053                                   const ARMSubtarget *Subtarget) {
8054   if (!Subtarget->hasVMLxForwarding())
8055     return SDValue();
8056
8057   SelectionDAG &DAG = DCI.DAG;
8058   SDValue N0 = N->getOperand(0);
8059   SDValue N1 = N->getOperand(1);
8060   unsigned Opcode = N0.getOpcode();
8061   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8062       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8063     Opcode = N1.getOpcode();
8064     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8065         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8066       return SDValue();
8067     std::swap(N0, N1);
8068   }
8069
8070   if (N0 == N1)
8071     return SDValue();
8072
8073   EVT VT = N->getValueType(0);
8074   SDLoc DL(N);
8075   SDValue N00 = N0->getOperand(0);
8076   SDValue N01 = N0->getOperand(1);
8077   return DAG.getNode(Opcode, DL, VT,
8078                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8079                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8080 }
8081
8082 static SDValue PerformMULCombine(SDNode *N,
8083                                  TargetLowering::DAGCombinerInfo &DCI,
8084                                  const ARMSubtarget *Subtarget) {
8085   SelectionDAG &DAG = DCI.DAG;
8086
8087   if (Subtarget->isThumb1Only())
8088     return SDValue();
8089
8090   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8091     return SDValue();
8092
8093   EVT VT = N->getValueType(0);
8094   if (VT.is64BitVector() || VT.is128BitVector())
8095     return PerformVMULCombine(N, DCI, Subtarget);
8096   if (VT != MVT::i32)
8097     return SDValue();
8098
8099   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8100   if (!C)
8101     return SDValue();
8102
8103   int64_t MulAmt = C->getSExtValue();
8104   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8105
8106   ShiftAmt = ShiftAmt & (32 - 1);
8107   SDValue V = N->getOperand(0);
8108   SDLoc DL(N);
8109
8110   SDValue Res;
8111   MulAmt >>= ShiftAmt;
8112
8113   if (MulAmt >= 0) {
8114     if (isPowerOf2_32(MulAmt - 1)) {
8115       // (mul x, 2^N + 1) => (add (shl x, N), x)
8116       Res = DAG.getNode(ISD::ADD, DL, VT,
8117                         V,
8118                         DAG.getNode(ISD::SHL, DL, VT,
8119                                     V,
8120                                     DAG.getConstant(Log2_32(MulAmt - 1),
8121                                                     MVT::i32)));
8122     } else if (isPowerOf2_32(MulAmt + 1)) {
8123       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8124       Res = DAG.getNode(ISD::SUB, DL, VT,
8125                         DAG.getNode(ISD::SHL, DL, VT,
8126                                     V,
8127                                     DAG.getConstant(Log2_32(MulAmt + 1),
8128                                                     MVT::i32)),
8129                         V);
8130     } else
8131       return SDValue();
8132   } else {
8133     uint64_t MulAmtAbs = -MulAmt;
8134     if (isPowerOf2_32(MulAmtAbs + 1)) {
8135       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8136       Res = DAG.getNode(ISD::SUB, DL, VT,
8137                         V,
8138                         DAG.getNode(ISD::SHL, DL, VT,
8139                                     V,
8140                                     DAG.getConstant(Log2_32(MulAmtAbs + 1),
8141                                                     MVT::i32)));
8142     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8143       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8144       Res = DAG.getNode(ISD::ADD, DL, VT,
8145                         V,
8146                         DAG.getNode(ISD::SHL, DL, VT,
8147                                     V,
8148                                     DAG.getConstant(Log2_32(MulAmtAbs-1),
8149                                                     MVT::i32)));
8150       Res = DAG.getNode(ISD::SUB, DL, VT,
8151                         DAG.getConstant(0, MVT::i32),Res);
8152
8153     } else
8154       return SDValue();
8155   }
8156
8157   if (ShiftAmt != 0)
8158     Res = DAG.getNode(ISD::SHL, DL, VT,
8159                       Res, DAG.getConstant(ShiftAmt, MVT::i32));
8160
8161   // Do not add new nodes to DAG combiner worklist.
8162   DCI.CombineTo(N, Res, false);
8163   return SDValue();
8164 }
8165
8166 static SDValue PerformANDCombine(SDNode *N,
8167                                  TargetLowering::DAGCombinerInfo &DCI,
8168                                  const ARMSubtarget *Subtarget) {
8169
8170   // Attempt to use immediate-form VBIC
8171   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8172   SDLoc dl(N);
8173   EVT VT = N->getValueType(0);
8174   SelectionDAG &DAG = DCI.DAG;
8175
8176   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8177     return SDValue();
8178
8179   APInt SplatBits, SplatUndef;
8180   unsigned SplatBitSize;
8181   bool HasAnyUndefs;
8182   if (BVN &&
8183       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8184     if (SplatBitSize <= 64) {
8185       EVT VbicVT;
8186       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8187                                       SplatUndef.getZExtValue(), SplatBitSize,
8188                                       DAG, VbicVT, VT.is128BitVector(),
8189                                       OtherModImm);
8190       if (Val.getNode()) {
8191         SDValue Input =
8192           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8193         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8194         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8195       }
8196     }
8197   }
8198
8199   if (!Subtarget->isThumb1Only()) {
8200     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8201     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8202     if (Result.getNode())
8203       return Result;
8204   }
8205
8206   return SDValue();
8207 }
8208
8209 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8210 static SDValue PerformORCombine(SDNode *N,
8211                                 TargetLowering::DAGCombinerInfo &DCI,
8212                                 const ARMSubtarget *Subtarget) {
8213   // Attempt to use immediate-form VORR
8214   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8215   SDLoc dl(N);
8216   EVT VT = N->getValueType(0);
8217   SelectionDAG &DAG = DCI.DAG;
8218
8219   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8220     return SDValue();
8221
8222   APInt SplatBits, SplatUndef;
8223   unsigned SplatBitSize;
8224   bool HasAnyUndefs;
8225   if (BVN && Subtarget->hasNEON() &&
8226       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8227     if (SplatBitSize <= 64) {
8228       EVT VorrVT;
8229       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8230                                       SplatUndef.getZExtValue(), SplatBitSize,
8231                                       DAG, VorrVT, VT.is128BitVector(),
8232                                       OtherModImm);
8233       if (Val.getNode()) {
8234         SDValue Input =
8235           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8236         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8237         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8238       }
8239     }
8240   }
8241
8242   if (!Subtarget->isThumb1Only()) {
8243     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8244     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8245     if (Result.getNode())
8246       return Result;
8247   }
8248
8249   // The code below optimizes (or (and X, Y), Z).
8250   // The AND operand needs to have a single user to make these optimizations
8251   // profitable.
8252   SDValue N0 = N->getOperand(0);
8253   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8254     return SDValue();
8255   SDValue N1 = N->getOperand(1);
8256
8257   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8258   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8259       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8260     APInt SplatUndef;
8261     unsigned SplatBitSize;
8262     bool HasAnyUndefs;
8263
8264     APInt SplatBits0, SplatBits1;
8265     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8266     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8267     // Ensure that the second operand of both ands are constants
8268     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8269                                       HasAnyUndefs) && !HasAnyUndefs) {
8270         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8271                                           HasAnyUndefs) && !HasAnyUndefs) {
8272             // Ensure that the bit width of the constants are the same and that
8273             // the splat arguments are logical inverses as per the pattern we
8274             // are trying to simplify.
8275             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8276                 SplatBits0 == ~SplatBits1) {
8277                 // Canonicalize the vector type to make instruction selection
8278                 // simpler.
8279                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8280                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8281                                              N0->getOperand(1),
8282                                              N0->getOperand(0),
8283                                              N1->getOperand(0));
8284                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8285             }
8286         }
8287     }
8288   }
8289
8290   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8291   // reasonable.
8292
8293   // BFI is only available on V6T2+
8294   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8295     return SDValue();
8296
8297   SDLoc DL(N);
8298   // 1) or (and A, mask), val => ARMbfi A, val, mask
8299   //      iff (val & mask) == val
8300   //
8301   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8302   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8303   //          && mask == ~mask2
8304   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8305   //          && ~mask == mask2
8306   //  (i.e., copy a bitfield value into another bitfield of the same width)
8307
8308   if (VT != MVT::i32)
8309     return SDValue();
8310
8311   SDValue N00 = N0.getOperand(0);
8312
8313   // The value and the mask need to be constants so we can verify this is
8314   // actually a bitfield set. If the mask is 0xffff, we can do better
8315   // via a movt instruction, so don't use BFI in that case.
8316   SDValue MaskOp = N0.getOperand(1);
8317   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8318   if (!MaskC)
8319     return SDValue();
8320   unsigned Mask = MaskC->getZExtValue();
8321   if (Mask == 0xffff)
8322     return SDValue();
8323   SDValue Res;
8324   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8325   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8326   if (N1C) {
8327     unsigned Val = N1C->getZExtValue();
8328     if ((Val & ~Mask) != Val)
8329       return SDValue();
8330
8331     if (ARM::isBitFieldInvertedMask(Mask)) {
8332       Val >>= countTrailingZeros(~Mask);
8333
8334       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8335                         DAG.getConstant(Val, MVT::i32),
8336                         DAG.getConstant(Mask, MVT::i32));
8337
8338       // Do not add new nodes to DAG combiner worklist.
8339       DCI.CombineTo(N, Res, false);
8340       return SDValue();
8341     }
8342   } else if (N1.getOpcode() == ISD::AND) {
8343     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8344     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8345     if (!N11C)
8346       return SDValue();
8347     unsigned Mask2 = N11C->getZExtValue();
8348
8349     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8350     // as is to match.
8351     if (ARM::isBitFieldInvertedMask(Mask) &&
8352         (Mask == ~Mask2)) {
8353       // The pack halfword instruction works better for masks that fit it,
8354       // so use that when it's available.
8355       if (Subtarget->hasT2ExtractPack() &&
8356           (Mask == 0xffff || Mask == 0xffff0000))
8357         return SDValue();
8358       // 2a
8359       unsigned amt = countTrailingZeros(Mask2);
8360       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8361                         DAG.getConstant(amt, MVT::i32));
8362       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8363                         DAG.getConstant(Mask, MVT::i32));
8364       // Do not add new nodes to DAG combiner worklist.
8365       DCI.CombineTo(N, Res, false);
8366       return SDValue();
8367     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8368                (~Mask == Mask2)) {
8369       // The pack halfword instruction works better for masks that fit it,
8370       // so use that when it's available.
8371       if (Subtarget->hasT2ExtractPack() &&
8372           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8373         return SDValue();
8374       // 2b
8375       unsigned lsb = countTrailingZeros(Mask);
8376       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8377                         DAG.getConstant(lsb, MVT::i32));
8378       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8379                         DAG.getConstant(Mask2, MVT::i32));
8380       // Do not add new nodes to DAG combiner worklist.
8381       DCI.CombineTo(N, Res, false);
8382       return SDValue();
8383     }
8384   }
8385
8386   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8387       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8388       ARM::isBitFieldInvertedMask(~Mask)) {
8389     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8390     // where lsb(mask) == #shamt and masked bits of B are known zero.
8391     SDValue ShAmt = N00.getOperand(1);
8392     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8393     unsigned LSB = countTrailingZeros(Mask);
8394     if (ShAmtC != LSB)
8395       return SDValue();
8396
8397     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8398                       DAG.getConstant(~Mask, MVT::i32));
8399
8400     // Do not add new nodes to DAG combiner worklist.
8401     DCI.CombineTo(N, Res, false);
8402   }
8403
8404   return SDValue();
8405 }
8406
8407 static SDValue PerformXORCombine(SDNode *N,
8408                                  TargetLowering::DAGCombinerInfo &DCI,
8409                                  const ARMSubtarget *Subtarget) {
8410   EVT VT = N->getValueType(0);
8411   SelectionDAG &DAG = DCI.DAG;
8412
8413   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8414     return SDValue();
8415
8416   if (!Subtarget->isThumb1Only()) {
8417     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8418     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8419     if (Result.getNode())
8420       return Result;
8421   }
8422
8423   return SDValue();
8424 }
8425
8426 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8427 /// the bits being cleared by the AND are not demanded by the BFI.
8428 static SDValue PerformBFICombine(SDNode *N,
8429                                  TargetLowering::DAGCombinerInfo &DCI) {
8430   SDValue N1 = N->getOperand(1);
8431   if (N1.getOpcode() == ISD::AND) {
8432     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8433     if (!N11C)
8434       return SDValue();
8435     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8436     unsigned LSB = countTrailingZeros(~InvMask);
8437     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8438     assert(Width <
8439                static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
8440            "undefined behavior");
8441     unsigned Mask = (1u << Width) - 1;
8442     unsigned Mask2 = N11C->getZExtValue();
8443     if ((Mask & (~Mask2)) == 0)
8444       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8445                              N->getOperand(0), N1.getOperand(0),
8446                              N->getOperand(2));
8447   }
8448   return SDValue();
8449 }
8450
8451 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8452 /// ARMISD::VMOVRRD.
8453 static SDValue PerformVMOVRRDCombine(SDNode *N,
8454                                      TargetLowering::DAGCombinerInfo &DCI,
8455                                      const ARMSubtarget *Subtarget) {
8456   // vmovrrd(vmovdrr x, y) -> x,y
8457   SDValue InDouble = N->getOperand(0);
8458   if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
8459     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8460
8461   // vmovrrd(load f64) -> (load i32), (load i32)
8462   SDNode *InNode = InDouble.getNode();
8463   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8464       InNode->getValueType(0) == MVT::f64 &&
8465       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8466       !cast<LoadSDNode>(InNode)->isVolatile()) {
8467     // TODO: Should this be done for non-FrameIndex operands?
8468     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8469
8470     SelectionDAG &DAG = DCI.DAG;
8471     SDLoc DL(LD);
8472     SDValue BasePtr = LD->getBasePtr();
8473     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8474                                  LD->getPointerInfo(), LD->isVolatile(),
8475                                  LD->isNonTemporal(), LD->isInvariant(),
8476                                  LD->getAlignment());
8477
8478     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8479                                     DAG.getConstant(4, MVT::i32));
8480     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8481                                  LD->getPointerInfo(), LD->isVolatile(),
8482                                  LD->isNonTemporal(), LD->isInvariant(),
8483                                  std::min(4U, LD->getAlignment() / 2));
8484
8485     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8486     if (DCI.DAG.getTargetLoweringInfo().isBigEndian())
8487       std::swap (NewLD1, NewLD2);
8488     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8489     return Result;
8490   }
8491
8492   return SDValue();
8493 }
8494
8495 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8496 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8497 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8498   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8499   SDValue Op0 = N->getOperand(0);
8500   SDValue Op1 = N->getOperand(1);
8501   if (Op0.getOpcode() == ISD::BITCAST)
8502     Op0 = Op0.getOperand(0);
8503   if (Op1.getOpcode() == ISD::BITCAST)
8504     Op1 = Op1.getOperand(0);
8505   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8506       Op0.getNode() == Op1.getNode() &&
8507       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8508     return DAG.getNode(ISD::BITCAST, SDLoc(N),
8509                        N->getValueType(0), Op0.getOperand(0));
8510   return SDValue();
8511 }
8512
8513 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8514 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8515 /// i64 vector to have f64 elements, since the value can then be loaded
8516 /// directly into a VFP register.
8517 static bool hasNormalLoadOperand(SDNode *N) {
8518   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8519   for (unsigned i = 0; i < NumElts; ++i) {
8520     SDNode *Elt = N->getOperand(i).getNode();
8521     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8522       return true;
8523   }
8524   return false;
8525 }
8526
8527 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8528 /// ISD::BUILD_VECTOR.
8529 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8530                                           TargetLowering::DAGCombinerInfo &DCI,
8531                                           const ARMSubtarget *Subtarget) {
8532   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8533   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
8534   // into a pair of GPRs, which is fine when the value is used as a scalar,
8535   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8536   SelectionDAG &DAG = DCI.DAG;
8537   if (N->getNumOperands() == 2) {
8538     SDValue RV = PerformVMOVDRRCombine(N, DAG);
8539     if (RV.getNode())
8540       return RV;
8541   }
8542
8543   // Load i64 elements as f64 values so that type legalization does not split
8544   // them up into i32 values.
8545   EVT VT = N->getValueType(0);
8546   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8547     return SDValue();
8548   SDLoc dl(N);
8549   SmallVector<SDValue, 8> Ops;
8550   unsigned NumElts = VT.getVectorNumElements();
8551   for (unsigned i = 0; i < NumElts; ++i) {
8552     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8553     Ops.push_back(V);
8554     // Make the DAGCombiner fold the bitcast.
8555     DCI.AddToWorklist(V.getNode());
8556   }
8557   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8558   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8559   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8560 }
8561
8562 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8563 static SDValue
8564 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8565   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8566   // At that time, we may have inserted bitcasts from integer to float.
8567   // If these bitcasts have survived DAGCombine, change the lowering of this
8568   // BUILD_VECTOR in something more vector friendly, i.e., that does not
8569   // force to use floating point types.
8570
8571   // Make sure we can change the type of the vector.
8572   // This is possible iff:
8573   // 1. The vector is only used in a bitcast to a integer type. I.e.,
8574   //    1.1. Vector is used only once.
8575   //    1.2. Use is a bit convert to an integer type.
8576   // 2. The size of its operands are 32-bits (64-bits are not legal).
8577   EVT VT = N->getValueType(0);
8578   EVT EltVT = VT.getVectorElementType();
8579
8580   // Check 1.1. and 2.
8581   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8582     return SDValue();
8583
8584   // By construction, the input type must be float.
8585   assert(EltVT == MVT::f32 && "Unexpected type!");
8586
8587   // Check 1.2.
8588   SDNode *Use = *N->use_begin();
8589   if (Use->getOpcode() != ISD::BITCAST ||
8590       Use->getValueType(0).isFloatingPoint())
8591     return SDValue();
8592
8593   // Check profitability.
8594   // Model is, if more than half of the relevant operands are bitcast from
8595   // i32, turn the build_vector into a sequence of insert_vector_elt.
8596   // Relevant operands are everything that is not statically
8597   // (i.e., at compile time) bitcasted.
8598   unsigned NumOfBitCastedElts = 0;
8599   unsigned NumElts = VT.getVectorNumElements();
8600   unsigned NumOfRelevantElts = NumElts;
8601   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8602     SDValue Elt = N->getOperand(Idx);
8603     if (Elt->getOpcode() == ISD::BITCAST) {
8604       // Assume only bit cast to i32 will go away.
8605       if (Elt->getOperand(0).getValueType() == MVT::i32)
8606         ++NumOfBitCastedElts;
8607     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8608       // Constants are statically casted, thus do not count them as
8609       // relevant operands.
8610       --NumOfRelevantElts;
8611   }
8612
8613   // Check if more than half of the elements require a non-free bitcast.
8614   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8615     return SDValue();
8616
8617   SelectionDAG &DAG = DCI.DAG;
8618   // Create the new vector type.
8619   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8620   // Check if the type is legal.
8621   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8622   if (!TLI.isTypeLegal(VecVT))
8623     return SDValue();
8624
8625   // Combine:
8626   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8627   // => BITCAST INSERT_VECTOR_ELT
8628   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8629   //                      (BITCAST EN), N.
8630   SDValue Vec = DAG.getUNDEF(VecVT);
8631   SDLoc dl(N);
8632   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8633     SDValue V = N->getOperand(Idx);
8634     if (V.getOpcode() == ISD::UNDEF)
8635       continue;
8636     if (V.getOpcode() == ISD::BITCAST &&
8637         V->getOperand(0).getValueType() == MVT::i32)
8638       // Fold obvious case.
8639       V = V.getOperand(0);
8640     else {
8641       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
8642       // Make the DAGCombiner fold the bitcasts.
8643       DCI.AddToWorklist(V.getNode());
8644     }
8645     SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
8646     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8647   }
8648   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8649   // Make the DAGCombiner fold the bitcasts.
8650   DCI.AddToWorklist(Vec.getNode());
8651   return Vec;
8652 }
8653
8654 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8655 /// ISD::INSERT_VECTOR_ELT.
8656 static SDValue PerformInsertEltCombine(SDNode *N,
8657                                        TargetLowering::DAGCombinerInfo &DCI) {
8658   // Bitcast an i64 load inserted into a vector to f64.
8659   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8660   EVT VT = N->getValueType(0);
8661   SDNode *Elt = N->getOperand(1).getNode();
8662   if (VT.getVectorElementType() != MVT::i64 ||
8663       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8664     return SDValue();
8665
8666   SelectionDAG &DAG = DCI.DAG;
8667   SDLoc dl(N);
8668   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8669                                  VT.getVectorNumElements());
8670   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8671   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8672   // Make the DAGCombiner fold the bitcasts.
8673   DCI.AddToWorklist(Vec.getNode());
8674   DCI.AddToWorklist(V.getNode());
8675   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8676                                Vec, V, N->getOperand(2));
8677   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8678 }
8679
8680 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8681 /// ISD::VECTOR_SHUFFLE.
8682 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8683   // The LLVM shufflevector instruction does not require the shuffle mask
8684   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8685   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
8686   // operands do not match the mask length, they are extended by concatenating
8687   // them with undef vectors.  That is probably the right thing for other
8688   // targets, but for NEON it is better to concatenate two double-register
8689   // size vector operands into a single quad-register size vector.  Do that
8690   // transformation here:
8691   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
8692   //   shuffle(concat(v1, v2), undef)
8693   SDValue Op0 = N->getOperand(0);
8694   SDValue Op1 = N->getOperand(1);
8695   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8696       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8697       Op0.getNumOperands() != 2 ||
8698       Op1.getNumOperands() != 2)
8699     return SDValue();
8700   SDValue Concat0Op1 = Op0.getOperand(1);
8701   SDValue Concat1Op1 = Op1.getOperand(1);
8702   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8703       Concat1Op1.getOpcode() != ISD::UNDEF)
8704     return SDValue();
8705   // Skip the transformation if any of the types are illegal.
8706   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8707   EVT VT = N->getValueType(0);
8708   if (!TLI.isTypeLegal(VT) ||
8709       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8710       !TLI.isTypeLegal(Concat1Op1.getValueType()))
8711     return SDValue();
8712
8713   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
8714                                   Op0.getOperand(0), Op1.getOperand(0));
8715   // Translate the shuffle mask.
8716   SmallVector<int, 16> NewMask;
8717   unsigned NumElts = VT.getVectorNumElements();
8718   unsigned HalfElts = NumElts/2;
8719   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8720   for (unsigned n = 0; n < NumElts; ++n) {
8721     int MaskElt = SVN->getMaskElt(n);
8722     int NewElt = -1;
8723     if (MaskElt < (int)HalfElts)
8724       NewElt = MaskElt;
8725     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8726       NewElt = HalfElts + MaskElt - NumElts;
8727     NewMask.push_back(NewElt);
8728   }
8729   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
8730                               DAG.getUNDEF(VT), NewMask.data());
8731 }
8732
8733 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
8734 /// NEON load/store intrinsics, and generic vector load/stores, to merge
8735 /// base address updates.
8736 /// For generic load/stores, the memory type is assumed to be a vector.
8737 /// The caller is assumed to have checked legality.
8738 static SDValue CombineBaseUpdate(SDNode *N,
8739                                  TargetLowering::DAGCombinerInfo &DCI) {
8740   SelectionDAG &DAG = DCI.DAG;
8741   const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8742                             N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8743   const bool isStore = N->getOpcode() == ISD::STORE;
8744   const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
8745   SDValue Addr = N->getOperand(AddrOpIdx);
8746   MemSDNode *MemN = cast<MemSDNode>(N);
8747
8748   // Search for a use of the address operand that is an increment.
8749   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8750          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8751     SDNode *User = *UI;
8752     if (User->getOpcode() != ISD::ADD ||
8753         UI.getUse().getResNo() != Addr.getResNo())
8754       continue;
8755
8756     // Check that the add is independent of the load/store.  Otherwise, folding
8757     // it would create a cycle.
8758     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8759       continue;
8760
8761     // Find the new opcode for the updating load/store.
8762     bool isLoadOp = true;
8763     bool isLaneOp = false;
8764     unsigned NewOpc = 0;
8765     unsigned NumVecs = 0;
8766     if (isIntrinsic) {
8767       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8768       switch (IntNo) {
8769       default: llvm_unreachable("unexpected intrinsic for Neon base update");
8770       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
8771         NumVecs = 1; break;
8772       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
8773         NumVecs = 2; break;
8774       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
8775         NumVecs = 3; break;
8776       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
8777         NumVecs = 4; break;
8778       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8779         NumVecs = 2; isLaneOp = true; break;
8780       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8781         NumVecs = 3; isLaneOp = true; break;
8782       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8783         NumVecs = 4; isLaneOp = true; break;
8784       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
8785         NumVecs = 1; isLoadOp = false; break;
8786       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
8787         NumVecs = 2; isLoadOp = false; break;
8788       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
8789         NumVecs = 3; isLoadOp = false; break;
8790       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
8791         NumVecs = 4; isLoadOp = false; break;
8792       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8793         NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
8794       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8795         NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
8796       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8797         NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
8798       }
8799     } else {
8800       isLaneOp = true;
8801       switch (N->getOpcode()) {
8802       default: llvm_unreachable("unexpected opcode for Neon base update");
8803       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8804       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8805       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8806       case ISD::LOAD:       NewOpc = ARMISD::VLD1_UPD;
8807         NumVecs = 1; isLaneOp = false; break;
8808       case ISD::STORE:      NewOpc = ARMISD::VST1_UPD;
8809         NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
8810       }
8811     }
8812
8813     // Find the size of memory referenced by the load/store.
8814     EVT VecTy;
8815     if (isLoadOp) {
8816       VecTy = N->getValueType(0);
8817     } else if (isIntrinsic) {
8818       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8819     } else {
8820       assert(isStore && "Node has to be a load, a store, or an intrinsic!");
8821       VecTy = N->getOperand(1).getValueType();
8822     }
8823
8824     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8825     if (isLaneOp)
8826       NumBytes /= VecTy.getVectorNumElements();
8827
8828     // If the increment is a constant, it must match the memory ref size.
8829     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8830     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8831       uint64_t IncVal = CInc->getZExtValue();
8832       if (IncVal != NumBytes)
8833         continue;
8834     } else if (NumBytes >= 3 * 16) {
8835       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8836       // separate instructions that make it harder to use a non-constant update.
8837       continue;
8838     }
8839
8840     // OK, we found an ADD we can fold into the base update.
8841     // Now, create a _UPD node, taking care of not breaking alignment.
8842
8843     EVT AlignedVecTy = VecTy;
8844     unsigned Alignment = MemN->getAlignment();
8845
8846     // If this is a less-than-standard-aligned load/store, change the type to
8847     // match the standard alignment.
8848     // The alignment is overlooked when selecting _UPD variants; and it's
8849     // easier to introduce bitcasts here than fix that.
8850     // There are 3 ways to get to this base-update combine:
8851     // - intrinsics: they are assumed to be properly aligned (to the standard
8852     //   alignment of the memory type), so we don't need to do anything.
8853     // - ARMISD::VLDx nodes: they are only generated from the aforementioned
8854     //   intrinsics, so, likewise, there's nothing to do.
8855     // - generic load/store instructions: the alignment is specified as an
8856     //   explicit operand, rather than implicitly as the standard alignment
8857     //   of the memory type (like the intrisics).  We need to change the
8858     //   memory type to match the explicit alignment.  That way, we don't
8859     //   generate non-standard-aligned ARMISD::VLDx nodes.
8860     if (isa<LSBaseSDNode>(N)) {
8861       if (Alignment == 0)
8862         Alignment = 1;
8863       if (Alignment < VecTy.getScalarSizeInBits() / 8) {
8864         MVT EltTy = MVT::getIntegerVT(Alignment * 8);
8865         assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
8866         assert(!isLaneOp && "Unexpected generic load/store lane.");
8867         unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
8868         AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
8869       }
8870       // Don't set an explicit alignment on regular load/stores that we want
8871       // to transform to VLD/VST 1_UPD nodes.
8872       // This matches the behavior of regular load/stores, which only get an
8873       // explicit alignment if the MMO alignment is larger than the standard
8874       // alignment of the memory type.
8875       // Intrinsics, however, always get an explicit alignment, set to the
8876       // alignment of the MMO.
8877       Alignment = 1;
8878     }
8879
8880     // Create the new updating load/store node.
8881     // First, create an SDVTList for the new updating node's results.
8882     EVT Tys[6];
8883     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
8884     unsigned n;
8885     for (n = 0; n < NumResultVecs; ++n)
8886       Tys[n] = AlignedVecTy;
8887     Tys[n++] = MVT::i32;
8888     Tys[n] = MVT::Other;
8889     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
8890
8891     // Then, gather the new node's operands.
8892     SmallVector<SDValue, 8> Ops;
8893     Ops.push_back(N->getOperand(0)); // incoming chain
8894     Ops.push_back(N->getOperand(AddrOpIdx));
8895     Ops.push_back(Inc);
8896
8897     if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
8898       // Try to match the intrinsic's signature
8899       Ops.push_back(StN->getValue());
8900     } else {
8901       // Loads (and of course intrinsics) match the intrinsics' signature,
8902       // so just add all but the alignment operand.
8903       for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
8904         Ops.push_back(N->getOperand(i));
8905     }
8906
8907     // For all node types, the alignment operand is always the last one.
8908     Ops.push_back(DAG.getConstant(Alignment, MVT::i32));
8909
8910     // If this is a non-standard-aligned STORE, the penultimate operand is the
8911     // stored value.  Bitcast it to the aligned type.
8912     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
8913       SDValue &StVal = Ops[Ops.size()-2];
8914       StVal = DAG.getNode(ISD::BITCAST, SDLoc(N), AlignedVecTy, StVal);
8915     }
8916
8917     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
8918                                            Ops, AlignedVecTy,
8919                                            MemN->getMemOperand());
8920
8921     // Update the uses.
8922     SmallVector<SDValue, 5> NewResults;
8923     for (unsigned i = 0; i < NumResultVecs; ++i)
8924       NewResults.push_back(SDValue(UpdN.getNode(), i));
8925
8926     // If this is an non-standard-aligned LOAD, the first result is the loaded
8927     // value.  Bitcast it to the expected result type.
8928     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
8929       SDValue &LdVal = NewResults[0];
8930       LdVal = DAG.getNode(ISD::BITCAST, SDLoc(N), VecTy, LdVal);
8931     }
8932
8933     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8934     DCI.CombineTo(N, NewResults);
8935     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8936
8937     break;
8938   }
8939   return SDValue();
8940 }
8941
8942 static SDValue PerformVLDCombine(SDNode *N,
8943                                  TargetLowering::DAGCombinerInfo &DCI) {
8944   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8945     return SDValue();
8946
8947   return CombineBaseUpdate(N, DCI);
8948 }
8949
8950 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
8951 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
8952 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
8953 /// return true.
8954 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8955   SelectionDAG &DAG = DCI.DAG;
8956   EVT VT = N->getValueType(0);
8957   // vldN-dup instructions only support 64-bit vectors for N > 1.
8958   if (!VT.is64BitVector())
8959     return false;
8960
8961   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
8962   SDNode *VLD = N->getOperand(0).getNode();
8963   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
8964     return false;
8965   unsigned NumVecs = 0;
8966   unsigned NewOpc = 0;
8967   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
8968   if (IntNo == Intrinsic::arm_neon_vld2lane) {
8969     NumVecs = 2;
8970     NewOpc = ARMISD::VLD2DUP;
8971   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
8972     NumVecs = 3;
8973     NewOpc = ARMISD::VLD3DUP;
8974   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
8975     NumVecs = 4;
8976     NewOpc = ARMISD::VLD4DUP;
8977   } else {
8978     return false;
8979   }
8980
8981   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
8982   // numbers match the load.
8983   unsigned VLDLaneNo =
8984     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
8985   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8986        UI != UE; ++UI) {
8987     // Ignore uses of the chain result.
8988     if (UI.getUse().getResNo() == NumVecs)
8989       continue;
8990     SDNode *User = *UI;
8991     if (User->getOpcode() != ARMISD::VDUPLANE ||
8992         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
8993       return false;
8994   }
8995
8996   // Create the vldN-dup node.
8997   EVT Tys[5];
8998   unsigned n;
8999   for (n = 0; n < NumVecs; ++n)
9000     Tys[n] = VT;
9001   Tys[n] = MVT::Other;
9002   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9003   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9004   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9005   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9006                                            Ops, VLDMemInt->getMemoryVT(),
9007                                            VLDMemInt->getMemOperand());
9008
9009   // Update the uses.
9010   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9011        UI != UE; ++UI) {
9012     unsigned ResNo = UI.getUse().getResNo();
9013     // Ignore uses of the chain result.
9014     if (ResNo == NumVecs)
9015       continue;
9016     SDNode *User = *UI;
9017     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9018   }
9019
9020   // Now the vldN-lane intrinsic is dead except for its chain result.
9021   // Update uses of the chain.
9022   std::vector<SDValue> VLDDupResults;
9023   for (unsigned n = 0; n < NumVecs; ++n)
9024     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9025   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9026   DCI.CombineTo(VLD, VLDDupResults);
9027
9028   return true;
9029 }
9030
9031 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9032 /// ARMISD::VDUPLANE.
9033 static SDValue PerformVDUPLANECombine(SDNode *N,
9034                                       TargetLowering::DAGCombinerInfo &DCI) {
9035   SDValue Op = N->getOperand(0);
9036
9037   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9038   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9039   if (CombineVLDDUP(N, DCI))
9040     return SDValue(N, 0);
9041
9042   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9043   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9044   while (Op.getOpcode() == ISD::BITCAST)
9045     Op = Op.getOperand(0);
9046   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9047     return SDValue();
9048
9049   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9050   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9051   // The canonical VMOV for a zero vector uses a 32-bit element size.
9052   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9053   unsigned EltBits;
9054   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9055     EltSize = 8;
9056   EVT VT = N->getValueType(0);
9057   if (EltSize > VT.getVectorElementType().getSizeInBits())
9058     return SDValue();
9059
9060   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9061 }
9062
9063 static SDValue PerformLOADCombine(SDNode *N,
9064                                   TargetLowering::DAGCombinerInfo &DCI) {
9065   EVT VT = N->getValueType(0);
9066
9067   // If this is a legal vector load, try to combine it into a VLD1_UPD.
9068   if (ISD::isNormalLoad(N) && VT.isVector() &&
9069       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9070     return CombineBaseUpdate(N, DCI);
9071
9072   return SDValue();
9073 }
9074
9075 /// PerformSTORECombine - Target-specific dag combine xforms for
9076 /// ISD::STORE.
9077 static SDValue PerformSTORECombine(SDNode *N,
9078                                    TargetLowering::DAGCombinerInfo &DCI) {
9079   StoreSDNode *St = cast<StoreSDNode>(N);
9080   if (St->isVolatile())
9081     return SDValue();
9082
9083   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
9084   // pack all of the elements in one place.  Next, store to memory in fewer
9085   // chunks.
9086   SDValue StVal = St->getValue();
9087   EVT VT = StVal.getValueType();
9088   if (St->isTruncatingStore() && VT.isVector()) {
9089     SelectionDAG &DAG = DCI.DAG;
9090     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9091     EVT StVT = St->getMemoryVT();
9092     unsigned NumElems = VT.getVectorNumElements();
9093     assert(StVT != VT && "Cannot truncate to the same type");
9094     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
9095     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
9096
9097     // From, To sizes and ElemCount must be pow of two
9098     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
9099
9100     // We are going to use the original vector elt for storing.
9101     // Accumulated smaller vector elements must be a multiple of the store size.
9102     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
9103
9104     unsigned SizeRatio  = FromEltSz / ToEltSz;
9105     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
9106
9107     // Create a type on which we perform the shuffle.
9108     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9109                                      NumElems*SizeRatio);
9110     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9111
9112     SDLoc DL(St);
9113     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9114     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9115     for (unsigned i = 0; i < NumElems; ++i)
9116       ShuffleVec[i] = TLI.isBigEndian() ? (i+1) * SizeRatio - 1 : i * SizeRatio;
9117
9118     // Can't shuffle using an illegal type.
9119     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9120
9121     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9122                                 DAG.getUNDEF(WideVec.getValueType()),
9123                                 ShuffleVec.data());
9124     // At this point all of the data is stored at the bottom of the
9125     // register. We now need to save it to mem.
9126
9127     // Find the largest store unit
9128     MVT StoreType = MVT::i8;
9129     for (MVT Tp : MVT::integer_valuetypes()) {
9130       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9131         StoreType = Tp;
9132     }
9133     // Didn't find a legal store type.
9134     if (!TLI.isTypeLegal(StoreType))
9135       return SDValue();
9136
9137     // Bitcast the original vector into a vector of store-size units
9138     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9139             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9140     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9141     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9142     SmallVector<SDValue, 8> Chains;
9143     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
9144                                         TLI.getPointerTy());
9145     SDValue BasePtr = St->getBasePtr();
9146
9147     // Perform one or more big stores into memory.
9148     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9149     for (unsigned I = 0; I < E; I++) {
9150       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9151                                    StoreType, ShuffWide,
9152                                    DAG.getIntPtrConstant(I));
9153       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9154                                 St->getPointerInfo(), St->isVolatile(),
9155                                 St->isNonTemporal(), St->getAlignment());
9156       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9157                             Increment);
9158       Chains.push_back(Ch);
9159     }
9160     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
9161   }
9162
9163   if (!ISD::isNormalStore(St))
9164     return SDValue();
9165
9166   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9167   // ARM stores of arguments in the same cache line.
9168   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9169       StVal.getNode()->hasOneUse()) {
9170     SelectionDAG  &DAG = DCI.DAG;
9171     bool isBigEndian = DAG.getTargetLoweringInfo().isBigEndian();
9172     SDLoc DL(St);
9173     SDValue BasePtr = St->getBasePtr();
9174     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9175                                   StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
9176                                   BasePtr, St->getPointerInfo(), St->isVolatile(),
9177                                   St->isNonTemporal(), St->getAlignment());
9178
9179     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9180                                     DAG.getConstant(4, MVT::i32));
9181     return DAG.getStore(NewST1.getValue(0), DL,
9182                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
9183                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9184                         St->isNonTemporal(),
9185                         std::min(4U, St->getAlignment() / 2));
9186   }
9187
9188   if (StVal.getValueType() == MVT::i64 &&
9189       StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9190
9191     // Bitcast an i64 store extracted from a vector to f64.
9192     // Otherwise, the i64 value will be legalized to a pair of i32 values.
9193     SelectionDAG &DAG = DCI.DAG;
9194     SDLoc dl(StVal);
9195     SDValue IntVec = StVal.getOperand(0);
9196     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9197                                    IntVec.getValueType().getVectorNumElements());
9198     SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9199     SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9200                                  Vec, StVal.getOperand(1));
9201     dl = SDLoc(N);
9202     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9203     // Make the DAGCombiner fold the bitcasts.
9204     DCI.AddToWorklist(Vec.getNode());
9205     DCI.AddToWorklist(ExtElt.getNode());
9206     DCI.AddToWorklist(V.getNode());
9207     return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9208                         St->getPointerInfo(), St->isVolatile(),
9209                         St->isNonTemporal(), St->getAlignment(),
9210                         St->getAAInfo());
9211   }
9212
9213   // If this is a legal vector store, try to combine it into a VST1_UPD.
9214   if (ISD::isNormalStore(N) && VT.isVector() &&
9215       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9216     return CombineBaseUpdate(N, DCI);
9217
9218   return SDValue();
9219 }
9220
9221 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9222 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9223 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9224 {
9225   integerPart cN;
9226   integerPart c0 = 0;
9227   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9228        I != E; I++) {
9229     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9230     if (!C)
9231       return false;
9232
9233     bool isExact;
9234     APFloat APF = C->getValueAPF();
9235     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9236         != APFloat::opOK || !isExact)
9237       return false;
9238
9239     c0 = (I == 0) ? cN : c0;
9240     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9241       return false;
9242   }
9243   C = c0;
9244   return true;
9245 }
9246
9247 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9248 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9249 /// when the VMUL has a constant operand that is a power of 2.
9250 ///
9251 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9252 ///  vmul.f32        d16, d17, d16
9253 ///  vcvt.s32.f32    d16, d16
9254 /// becomes:
9255 ///  vcvt.s32.f32    d16, d16, #3
9256 static SDValue PerformVCVTCombine(SDNode *N,
9257                                   TargetLowering::DAGCombinerInfo &DCI,
9258                                   const ARMSubtarget *Subtarget) {
9259   SelectionDAG &DAG = DCI.DAG;
9260   SDValue Op = N->getOperand(0);
9261
9262   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9263       Op.getOpcode() != ISD::FMUL)
9264     return SDValue();
9265
9266   uint64_t C;
9267   SDValue N0 = Op->getOperand(0);
9268   SDValue ConstVec = Op->getOperand(1);
9269   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9270
9271   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9272       !isConstVecPow2(ConstVec, isSigned, C))
9273     return SDValue();
9274
9275   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9276   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9277   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9278   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32 ||
9279       NumLanes > 4) {
9280     // These instructions only exist converting from f32 to i32. We can handle
9281     // smaller integers by generating an extra truncate, but larger ones would
9282     // be lossy. We also can't handle more then 4 lanes, since these intructions
9283     // only support v2i32/v4i32 types.
9284     return SDValue();
9285   }
9286
9287   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9288     Intrinsic::arm_neon_vcvtfp2fxu;
9289   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9290                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9291                                  DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9292                                  DAG.getConstant(Log2_64(C), MVT::i32));
9293
9294   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9295     FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9296
9297   return FixConv;
9298 }
9299
9300 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9301 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9302 /// when the VDIV has a constant operand that is a power of 2.
9303 ///
9304 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9305 ///  vcvt.f32.s32    d16, d16
9306 ///  vdiv.f32        d16, d17, d16
9307 /// becomes:
9308 ///  vcvt.f32.s32    d16, d16, #3
9309 static SDValue PerformVDIVCombine(SDNode *N,
9310                                   TargetLowering::DAGCombinerInfo &DCI,
9311                                   const ARMSubtarget *Subtarget) {
9312   SelectionDAG &DAG = DCI.DAG;
9313   SDValue Op = N->getOperand(0);
9314   unsigned OpOpcode = Op.getNode()->getOpcode();
9315
9316   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9317       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9318     return SDValue();
9319
9320   uint64_t C;
9321   SDValue ConstVec = N->getOperand(1);
9322   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9323
9324   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9325       !isConstVecPow2(ConstVec, isSigned, C))
9326     return SDValue();
9327
9328   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9329   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9330   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9331     // These instructions only exist converting from i32 to f32. We can handle
9332     // smaller integers by generating an extra extend, but larger ones would
9333     // be lossy.
9334     return SDValue();
9335   }
9336
9337   SDValue ConvInput = Op.getOperand(0);
9338   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9339   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9340     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9341                             SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9342                             ConvInput);
9343
9344   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9345     Intrinsic::arm_neon_vcvtfxu2fp;
9346   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9347                      Op.getValueType(),
9348                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
9349                      ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9350 }
9351
9352 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9353 /// operand of a vector shift operation, where all the elements of the
9354 /// build_vector must have the same constant integer value.
9355 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9356   // Ignore bit_converts.
9357   while (Op.getOpcode() == ISD::BITCAST)
9358     Op = Op.getOperand(0);
9359   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9360   APInt SplatBits, SplatUndef;
9361   unsigned SplatBitSize;
9362   bool HasAnyUndefs;
9363   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9364                                       HasAnyUndefs, ElementBits) ||
9365       SplatBitSize > ElementBits)
9366     return false;
9367   Cnt = SplatBits.getSExtValue();
9368   return true;
9369 }
9370
9371 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9372 /// operand of a vector shift left operation.  That value must be in the range:
9373 ///   0 <= Value < ElementBits for a left shift; or
9374 ///   0 <= Value <= ElementBits for a long left shift.
9375 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9376   assert(VT.isVector() && "vector shift count is not a vector type");
9377   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9378   if (! getVShiftImm(Op, ElementBits, Cnt))
9379     return false;
9380   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9381 }
9382
9383 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9384 /// operand of a vector shift right operation.  For a shift opcode, the value
9385 /// is positive, but for an intrinsic the value count must be negative. The
9386 /// absolute value must be in the range:
9387 ///   1 <= |Value| <= ElementBits for a right shift; or
9388 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9389 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9390                          int64_t &Cnt) {
9391   assert(VT.isVector() && "vector shift count is not a vector type");
9392   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9393   if (! getVShiftImm(Op, ElementBits, Cnt))
9394     return false;
9395   if (isIntrinsic)
9396     Cnt = -Cnt;
9397   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9398 }
9399
9400 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9401 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9402   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9403   switch (IntNo) {
9404   default:
9405     // Don't do anything for most intrinsics.
9406     break;
9407
9408   // Vector shifts: check for immediate versions and lower them.
9409   // Note: This is done during DAG combining instead of DAG legalizing because
9410   // the build_vectors for 64-bit vector element shift counts are generally
9411   // not legal, and it is hard to see their values after they get legalized to
9412   // loads from a constant pool.
9413   case Intrinsic::arm_neon_vshifts:
9414   case Intrinsic::arm_neon_vshiftu:
9415   case Intrinsic::arm_neon_vrshifts:
9416   case Intrinsic::arm_neon_vrshiftu:
9417   case Intrinsic::arm_neon_vrshiftn:
9418   case Intrinsic::arm_neon_vqshifts:
9419   case Intrinsic::arm_neon_vqshiftu:
9420   case Intrinsic::arm_neon_vqshiftsu:
9421   case Intrinsic::arm_neon_vqshiftns:
9422   case Intrinsic::arm_neon_vqshiftnu:
9423   case Intrinsic::arm_neon_vqshiftnsu:
9424   case Intrinsic::arm_neon_vqrshiftns:
9425   case Intrinsic::arm_neon_vqrshiftnu:
9426   case Intrinsic::arm_neon_vqrshiftnsu: {
9427     EVT VT = N->getOperand(1).getValueType();
9428     int64_t Cnt;
9429     unsigned VShiftOpc = 0;
9430
9431     switch (IntNo) {
9432     case Intrinsic::arm_neon_vshifts:
9433     case Intrinsic::arm_neon_vshiftu:
9434       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9435         VShiftOpc = ARMISD::VSHL;
9436         break;
9437       }
9438       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9439         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9440                      ARMISD::VSHRs : ARMISD::VSHRu);
9441         break;
9442       }
9443       return SDValue();
9444
9445     case Intrinsic::arm_neon_vrshifts:
9446     case Intrinsic::arm_neon_vrshiftu:
9447       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9448         break;
9449       return SDValue();
9450
9451     case Intrinsic::arm_neon_vqshifts:
9452     case Intrinsic::arm_neon_vqshiftu:
9453       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9454         break;
9455       return SDValue();
9456
9457     case Intrinsic::arm_neon_vqshiftsu:
9458       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9459         break;
9460       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9461
9462     case Intrinsic::arm_neon_vrshiftn:
9463     case Intrinsic::arm_neon_vqshiftns:
9464     case Intrinsic::arm_neon_vqshiftnu:
9465     case Intrinsic::arm_neon_vqshiftnsu:
9466     case Intrinsic::arm_neon_vqrshiftns:
9467     case Intrinsic::arm_neon_vqrshiftnu:
9468     case Intrinsic::arm_neon_vqrshiftnsu:
9469       // Narrowing shifts require an immediate right shift.
9470       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9471         break;
9472       llvm_unreachable("invalid shift count for narrowing vector shift "
9473                        "intrinsic");
9474
9475     default:
9476       llvm_unreachable("unhandled vector shift");
9477     }
9478
9479     switch (IntNo) {
9480     case Intrinsic::arm_neon_vshifts:
9481     case Intrinsic::arm_neon_vshiftu:
9482       // Opcode already set above.
9483       break;
9484     case Intrinsic::arm_neon_vrshifts:
9485       VShiftOpc = ARMISD::VRSHRs; break;
9486     case Intrinsic::arm_neon_vrshiftu:
9487       VShiftOpc = ARMISD::VRSHRu; break;
9488     case Intrinsic::arm_neon_vrshiftn:
9489       VShiftOpc = ARMISD::VRSHRN; break;
9490     case Intrinsic::arm_neon_vqshifts:
9491       VShiftOpc = ARMISD::VQSHLs; break;
9492     case Intrinsic::arm_neon_vqshiftu:
9493       VShiftOpc = ARMISD::VQSHLu; break;
9494     case Intrinsic::arm_neon_vqshiftsu:
9495       VShiftOpc = ARMISD::VQSHLsu; break;
9496     case Intrinsic::arm_neon_vqshiftns:
9497       VShiftOpc = ARMISD::VQSHRNs; break;
9498     case Intrinsic::arm_neon_vqshiftnu:
9499       VShiftOpc = ARMISD::VQSHRNu; break;
9500     case Intrinsic::arm_neon_vqshiftnsu:
9501       VShiftOpc = ARMISD::VQSHRNsu; break;
9502     case Intrinsic::arm_neon_vqrshiftns:
9503       VShiftOpc = ARMISD::VQRSHRNs; break;
9504     case Intrinsic::arm_neon_vqrshiftnu:
9505       VShiftOpc = ARMISD::VQRSHRNu; break;
9506     case Intrinsic::arm_neon_vqrshiftnsu:
9507       VShiftOpc = ARMISD::VQRSHRNsu; break;
9508     }
9509
9510     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9511                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9512   }
9513
9514   case Intrinsic::arm_neon_vshiftins: {
9515     EVT VT = N->getOperand(1).getValueType();
9516     int64_t Cnt;
9517     unsigned VShiftOpc = 0;
9518
9519     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9520       VShiftOpc = ARMISD::VSLI;
9521     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9522       VShiftOpc = ARMISD::VSRI;
9523     else {
9524       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9525     }
9526
9527     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9528                        N->getOperand(1), N->getOperand(2),
9529                        DAG.getConstant(Cnt, MVT::i32));
9530   }
9531
9532   case Intrinsic::arm_neon_vqrshifts:
9533   case Intrinsic::arm_neon_vqrshiftu:
9534     // No immediate versions of these to check for.
9535     break;
9536   }
9537
9538   return SDValue();
9539 }
9540
9541 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9542 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9543 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9544 /// vector element shift counts are generally not legal, and it is hard to see
9545 /// their values after they get legalized to loads from a constant pool.
9546 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9547                                    const ARMSubtarget *ST) {
9548   EVT VT = N->getValueType(0);
9549   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9550     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9551     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9552     SDValue N1 = N->getOperand(1);
9553     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9554       SDValue N0 = N->getOperand(0);
9555       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9556           DAG.MaskedValueIsZero(N0.getOperand(0),
9557                                 APInt::getHighBitsSet(32, 16)))
9558         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9559     }
9560   }
9561
9562   // Nothing to be done for scalar shifts.
9563   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9564   if (!VT.isVector() || !TLI.isTypeLegal(VT))
9565     return SDValue();
9566
9567   assert(ST->hasNEON() && "unexpected vector shift");
9568   int64_t Cnt;
9569
9570   switch (N->getOpcode()) {
9571   default: llvm_unreachable("unexpected shift opcode");
9572
9573   case ISD::SHL:
9574     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9575       return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9576                          DAG.getConstant(Cnt, MVT::i32));
9577     break;
9578
9579   case ISD::SRA:
9580   case ISD::SRL:
9581     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9582       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9583                             ARMISD::VSHRs : ARMISD::VSHRu);
9584       return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9585                          DAG.getConstant(Cnt, MVT::i32));
9586     }
9587   }
9588   return SDValue();
9589 }
9590
9591 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9592 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9593 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9594                                     const ARMSubtarget *ST) {
9595   SDValue N0 = N->getOperand(0);
9596
9597   // Check for sign- and zero-extensions of vector extract operations of 8-
9598   // and 16-bit vector elements.  NEON supports these directly.  They are
9599   // handled during DAG combining because type legalization will promote them
9600   // to 32-bit types and it is messy to recognize the operations after that.
9601   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9602     SDValue Vec = N0.getOperand(0);
9603     SDValue Lane = N0.getOperand(1);
9604     EVT VT = N->getValueType(0);
9605     EVT EltVT = N0.getValueType();
9606     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9607
9608     if (VT == MVT::i32 &&
9609         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9610         TLI.isTypeLegal(Vec.getValueType()) &&
9611         isa<ConstantSDNode>(Lane)) {
9612
9613       unsigned Opc = 0;
9614       switch (N->getOpcode()) {
9615       default: llvm_unreachable("unexpected opcode");
9616       case ISD::SIGN_EXTEND:
9617         Opc = ARMISD::VGETLANEs;
9618         break;
9619       case ISD::ZERO_EXTEND:
9620       case ISD::ANY_EXTEND:
9621         Opc = ARMISD::VGETLANEu;
9622         break;
9623       }
9624       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9625     }
9626   }
9627
9628   return SDValue();
9629 }
9630
9631 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9632 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9633 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9634                                        const ARMSubtarget *ST) {
9635   // If the target supports NEON, try to use vmax/vmin instructions for f32
9636   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
9637   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
9638   // a NaN; only do the transformation when it matches that behavior.
9639
9640   // For now only do this when using NEON for FP operations; if using VFP, it
9641   // is not obvious that the benefit outweighs the cost of switching to the
9642   // NEON pipeline.
9643   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9644       N->getValueType(0) != MVT::f32)
9645     return SDValue();
9646
9647   SDValue CondLHS = N->getOperand(0);
9648   SDValue CondRHS = N->getOperand(1);
9649   SDValue LHS = N->getOperand(2);
9650   SDValue RHS = N->getOperand(3);
9651   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9652
9653   unsigned Opcode = 0;
9654   bool IsReversed;
9655   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9656     IsReversed = false; // x CC y ? x : y
9657   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9658     IsReversed = true ; // x CC y ? y : x
9659   } else {
9660     return SDValue();
9661   }
9662
9663   bool IsUnordered;
9664   switch (CC) {
9665   default: break;
9666   case ISD::SETOLT:
9667   case ISD::SETOLE:
9668   case ISD::SETLT:
9669   case ISD::SETLE:
9670   case ISD::SETULT:
9671   case ISD::SETULE:
9672     // If LHS is NaN, an ordered comparison will be false and the result will
9673     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
9674     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9675     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9676     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9677       break;
9678     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9679     // will return -0, so vmin can only be used for unsafe math or if one of
9680     // the operands is known to be nonzero.
9681     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9682         !DAG.getTarget().Options.UnsafeFPMath &&
9683         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9684       break;
9685     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9686     break;
9687
9688   case ISD::SETOGT:
9689   case ISD::SETOGE:
9690   case ISD::SETGT:
9691   case ISD::SETGE:
9692   case ISD::SETUGT:
9693   case ISD::SETUGE:
9694     // If LHS is NaN, an ordered comparison will be false and the result will
9695     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
9696     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9697     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9698     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9699       break;
9700     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9701     // will return +0, so vmax can only be used for unsafe math or if one of
9702     // the operands is known to be nonzero.
9703     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9704         !DAG.getTarget().Options.UnsafeFPMath &&
9705         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9706       break;
9707     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9708     break;
9709   }
9710
9711   if (!Opcode)
9712     return SDValue();
9713   return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9714 }
9715
9716 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9717 SDValue
9718 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9719   SDValue Cmp = N->getOperand(4);
9720   if (Cmp.getOpcode() != ARMISD::CMPZ)
9721     // Only looking at EQ and NE cases.
9722     return SDValue();
9723
9724   EVT VT = N->getValueType(0);
9725   SDLoc dl(N);
9726   SDValue LHS = Cmp.getOperand(0);
9727   SDValue RHS = Cmp.getOperand(1);
9728   SDValue FalseVal = N->getOperand(0);
9729   SDValue TrueVal = N->getOperand(1);
9730   SDValue ARMcc = N->getOperand(2);
9731   ARMCC::CondCodes CC =
9732     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9733
9734   // Simplify
9735   //   mov     r1, r0
9736   //   cmp     r1, x
9737   //   mov     r0, y
9738   //   moveq   r0, x
9739   // to
9740   //   cmp     r0, x
9741   //   movne   r0, y
9742   //
9743   //   mov     r1, r0
9744   //   cmp     r1, x
9745   //   mov     r0, x
9746   //   movne   r0, y
9747   // to
9748   //   cmp     r0, x
9749   //   movne   r0, y
9750   /// FIXME: Turn this into a target neutral optimization?
9751   SDValue Res;
9752   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9753     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9754                       N->getOperand(3), Cmp);
9755   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9756     SDValue ARMcc;
9757     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9758     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9759                       N->getOperand(3), NewCmp);
9760   }
9761
9762   if (Res.getNode()) {
9763     APInt KnownZero, KnownOne;
9764     DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
9765     // Capture demanded bits information that would be otherwise lost.
9766     if (KnownZero == 0xfffffffe)
9767       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9768                         DAG.getValueType(MVT::i1));
9769     else if (KnownZero == 0xffffff00)
9770       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9771                         DAG.getValueType(MVT::i8));
9772     else if (KnownZero == 0xffff0000)
9773       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9774                         DAG.getValueType(MVT::i16));
9775   }
9776
9777   return Res;
9778 }
9779
9780 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9781                                              DAGCombinerInfo &DCI) const {
9782   switch (N->getOpcode()) {
9783   default: break;
9784   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
9785   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
9786   case ISD::SUB:        return PerformSUBCombine(N, DCI);
9787   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
9788   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
9789   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
9790   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
9791   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
9792   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
9793   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9794   case ISD::STORE:      return PerformSTORECombine(N, DCI);
9795   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
9796   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9797   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9798   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9799   case ISD::FP_TO_SINT:
9800   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9801   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
9802   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9803   case ISD::SHL:
9804   case ISD::SRA:
9805   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
9806   case ISD::SIGN_EXTEND:
9807   case ISD::ZERO_EXTEND:
9808   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9809   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9810   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9811   case ISD::LOAD:       return PerformLOADCombine(N, DCI);
9812   case ARMISD::VLD2DUP:
9813   case ARMISD::VLD3DUP:
9814   case ARMISD::VLD4DUP:
9815     return PerformVLDCombine(N, DCI);
9816   case ARMISD::BUILD_VECTOR:
9817     return PerformARMBUILD_VECTORCombine(N, DCI);
9818   case ISD::INTRINSIC_VOID:
9819   case ISD::INTRINSIC_W_CHAIN:
9820     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9821     case Intrinsic::arm_neon_vld1:
9822     case Intrinsic::arm_neon_vld2:
9823     case Intrinsic::arm_neon_vld3:
9824     case Intrinsic::arm_neon_vld4:
9825     case Intrinsic::arm_neon_vld2lane:
9826     case Intrinsic::arm_neon_vld3lane:
9827     case Intrinsic::arm_neon_vld4lane:
9828     case Intrinsic::arm_neon_vst1:
9829     case Intrinsic::arm_neon_vst2:
9830     case Intrinsic::arm_neon_vst3:
9831     case Intrinsic::arm_neon_vst4:
9832     case Intrinsic::arm_neon_vst2lane:
9833     case Intrinsic::arm_neon_vst3lane:
9834     case Intrinsic::arm_neon_vst4lane:
9835       return PerformVLDCombine(N, DCI);
9836     default: break;
9837     }
9838     break;
9839   }
9840   return SDValue();
9841 }
9842
9843 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9844                                                           EVT VT) const {
9845   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9846 }
9847
9848 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
9849                                                        unsigned,
9850                                                        unsigned,
9851                                                        bool *Fast) const {
9852   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9853   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9854
9855   switch (VT.getSimpleVT().SimpleTy) {
9856   default:
9857     return false;
9858   case MVT::i8:
9859   case MVT::i16:
9860   case MVT::i32: {
9861     // Unaligned access can use (for example) LRDB, LRDH, LDR
9862     if (AllowsUnaligned) {
9863       if (Fast)
9864         *Fast = Subtarget->hasV7Ops();
9865       return true;
9866     }
9867     return false;
9868   }
9869   case MVT::f64:
9870   case MVT::v2f64: {
9871     // For any little-endian targets with neon, we can support unaligned ld/st
9872     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9873     // A big-endian target may also explicitly support unaligned accesses
9874     if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9875       if (Fast)
9876         *Fast = true;
9877       return true;
9878     }
9879     return false;
9880   }
9881   }
9882 }
9883
9884 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9885                        unsigned AlignCheck) {
9886   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9887           (DstAlign == 0 || DstAlign % AlignCheck == 0));
9888 }
9889
9890 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9891                                            unsigned DstAlign, unsigned SrcAlign,
9892                                            bool IsMemset, bool ZeroMemset,
9893                                            bool MemcpyStrSrc,
9894                                            MachineFunction &MF) const {
9895   const Function *F = MF.getFunction();
9896
9897   // See if we can use NEON instructions for this...
9898   if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
9899       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
9900     bool Fast;
9901     if (Size >= 16 &&
9902         (memOpAlign(SrcAlign, DstAlign, 16) ||
9903          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
9904       return MVT::v2f64;
9905     } else if (Size >= 8 &&
9906                (memOpAlign(SrcAlign, DstAlign, 8) ||
9907                 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
9908                  Fast))) {
9909       return MVT::f64;
9910     }
9911   }
9912
9913   // Lowering to i32/i16 if the size permits.
9914   if (Size >= 4)
9915     return MVT::i32;
9916   else if (Size >= 2)
9917     return MVT::i16;
9918
9919   // Let the target-independent logic figure it out.
9920   return MVT::Other;
9921 }
9922
9923 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9924   if (Val.getOpcode() != ISD::LOAD)
9925     return false;
9926
9927   EVT VT1 = Val.getValueType();
9928   if (!VT1.isSimple() || !VT1.isInteger() ||
9929       !VT2.isSimple() || !VT2.isInteger())
9930     return false;
9931
9932   switch (VT1.getSimpleVT().SimpleTy) {
9933   default: break;
9934   case MVT::i1:
9935   case MVT::i8:
9936   case MVT::i16:
9937     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
9938     return true;
9939   }
9940
9941   return false;
9942 }
9943
9944 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
9945   EVT VT = ExtVal.getValueType();
9946
9947   if (!isTypeLegal(VT))
9948     return false;
9949
9950   // Don't create a loadext if we can fold the extension into a wide/long
9951   // instruction.
9952   // If there's more than one user instruction, the loadext is desirable no
9953   // matter what.  There can be two uses by the same instruction.
9954   if (ExtVal->use_empty() ||
9955       !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
9956     return true;
9957
9958   SDNode *U = *ExtVal->use_begin();
9959   if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
9960        U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
9961     return false;
9962
9963   return true;
9964 }
9965
9966 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
9967   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9968     return false;
9969
9970   if (!isTypeLegal(EVT::getEVT(Ty1)))
9971     return false;
9972
9973   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
9974
9975   // Assuming the caller doesn't have a zeroext or signext return parameter,
9976   // truncation all the way down to i1 is valid.
9977   return true;
9978 }
9979
9980
9981 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9982   if (V < 0)
9983     return false;
9984
9985   unsigned Scale = 1;
9986   switch (VT.getSimpleVT().SimpleTy) {
9987   default: return false;
9988   case MVT::i1:
9989   case MVT::i8:
9990     // Scale == 1;
9991     break;
9992   case MVT::i16:
9993     // Scale == 2;
9994     Scale = 2;
9995     break;
9996   case MVT::i32:
9997     // Scale == 4;
9998     Scale = 4;
9999     break;
10000   }
10001
10002   if ((V & (Scale - 1)) != 0)
10003     return false;
10004   V /= Scale;
10005   return V == (V & ((1LL << 5) - 1));
10006 }
10007
10008 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10009                                       const ARMSubtarget *Subtarget) {
10010   bool isNeg = false;
10011   if (V < 0) {
10012     isNeg = true;
10013     V = - V;
10014   }
10015
10016   switch (VT.getSimpleVT().SimpleTy) {
10017   default: return false;
10018   case MVT::i1:
10019   case MVT::i8:
10020   case MVT::i16:
10021   case MVT::i32:
10022     // + imm12 or - imm8
10023     if (isNeg)
10024       return V == (V & ((1LL << 8) - 1));
10025     return V == (V & ((1LL << 12) - 1));
10026   case MVT::f32:
10027   case MVT::f64:
10028     // Same as ARM mode. FIXME: NEON?
10029     if (!Subtarget->hasVFP2())
10030       return false;
10031     if ((V & 3) != 0)
10032       return false;
10033     V >>= 2;
10034     return V == (V & ((1LL << 8) - 1));
10035   }
10036 }
10037
10038 /// isLegalAddressImmediate - Return true if the integer value can be used
10039 /// as the offset of the target addressing mode for load / store of the
10040 /// given type.
10041 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10042                                     const ARMSubtarget *Subtarget) {
10043   if (V == 0)
10044     return true;
10045
10046   if (!VT.isSimple())
10047     return false;
10048
10049   if (Subtarget->isThumb1Only())
10050     return isLegalT1AddressImmediate(V, VT);
10051   else if (Subtarget->isThumb2())
10052     return isLegalT2AddressImmediate(V, VT, Subtarget);
10053
10054   // ARM mode.
10055   if (V < 0)
10056     V = - V;
10057   switch (VT.getSimpleVT().SimpleTy) {
10058   default: return false;
10059   case MVT::i1:
10060   case MVT::i8:
10061   case MVT::i32:
10062     // +- imm12
10063     return V == (V & ((1LL << 12) - 1));
10064   case MVT::i16:
10065     // +- imm8
10066     return V == (V & ((1LL << 8) - 1));
10067   case MVT::f32:
10068   case MVT::f64:
10069     if (!Subtarget->hasVFP2()) // FIXME: NEON?
10070       return false;
10071     if ((V & 3) != 0)
10072       return false;
10073     V >>= 2;
10074     return V == (V & ((1LL << 8) - 1));
10075   }
10076 }
10077
10078 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10079                                                       EVT VT) const {
10080   int Scale = AM.Scale;
10081   if (Scale < 0)
10082     return false;
10083
10084   switch (VT.getSimpleVT().SimpleTy) {
10085   default: return false;
10086   case MVT::i1:
10087   case MVT::i8:
10088   case MVT::i16:
10089   case MVT::i32:
10090     if (Scale == 1)
10091       return true;
10092     // r + r << imm
10093     Scale = Scale & ~1;
10094     return Scale == 2 || Scale == 4 || Scale == 8;
10095   case MVT::i64:
10096     // r + r
10097     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10098       return true;
10099     return false;
10100   case MVT::isVoid:
10101     // Note, we allow "void" uses (basically, uses that aren't loads or
10102     // stores), because arm allows folding a scale into many arithmetic
10103     // operations.  This should be made more precise and revisited later.
10104
10105     // Allow r << imm, but the imm has to be a multiple of two.
10106     if (Scale & 1) return false;
10107     return isPowerOf2_32(Scale);
10108   }
10109 }
10110
10111 /// isLegalAddressingMode - Return true if the addressing mode represented
10112 /// by AM is legal for this target, for a load/store of the specified type.
10113 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10114                                               Type *Ty) const {
10115   EVT VT = getValueType(Ty, true);
10116   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10117     return false;
10118
10119   // Can never fold addr of global into load/store.
10120   if (AM.BaseGV)
10121     return false;
10122
10123   switch (AM.Scale) {
10124   case 0:  // no scale reg, must be "r+i" or "r", or "i".
10125     break;
10126   case 1:
10127     if (Subtarget->isThumb1Only())
10128       return false;
10129     // FALL THROUGH.
10130   default:
10131     // ARM doesn't support any R+R*scale+imm addr modes.
10132     if (AM.BaseOffs)
10133       return false;
10134
10135     if (!VT.isSimple())
10136       return false;
10137
10138     if (Subtarget->isThumb2())
10139       return isLegalT2ScaledAddressingMode(AM, VT);
10140
10141     int Scale = AM.Scale;
10142     switch (VT.getSimpleVT().SimpleTy) {
10143     default: return false;
10144     case MVT::i1:
10145     case MVT::i8:
10146     case MVT::i32:
10147       if (Scale < 0) Scale = -Scale;
10148       if (Scale == 1)
10149         return true;
10150       // r + r << imm
10151       return isPowerOf2_32(Scale & ~1);
10152     case MVT::i16:
10153     case MVT::i64:
10154       // r + r
10155       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10156         return true;
10157       return false;
10158
10159     case MVT::isVoid:
10160       // Note, we allow "void" uses (basically, uses that aren't loads or
10161       // stores), because arm allows folding a scale into many arithmetic
10162       // operations.  This should be made more precise and revisited later.
10163
10164       // Allow r << imm, but the imm has to be a multiple of two.
10165       if (Scale & 1) return false;
10166       return isPowerOf2_32(Scale);
10167     }
10168   }
10169   return true;
10170 }
10171
10172 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10173 /// icmp immediate, that is the target has icmp instructions which can compare
10174 /// a register against the immediate without having to materialize the
10175 /// immediate into a register.
10176 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10177   // Thumb2 and ARM modes can use cmn for negative immediates.
10178   if (!Subtarget->isThumb())
10179     return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
10180   if (Subtarget->isThumb2())
10181     return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
10182   // Thumb1 doesn't have cmn, and only 8-bit immediates.
10183   return Imm >= 0 && Imm <= 255;
10184 }
10185
10186 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10187 /// *or sub* immediate, that is the target has add or sub instructions which can
10188 /// add a register with the immediate without having to materialize the
10189 /// immediate into a register.
10190 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10191   // Same encoding for add/sub, just flip the sign.
10192   int64_t AbsImm = std::abs(Imm);
10193   if (!Subtarget->isThumb())
10194     return ARM_AM::getSOImmVal(AbsImm) != -1;
10195   if (Subtarget->isThumb2())
10196     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10197   // Thumb1 only has 8-bit unsigned immediate.
10198   return AbsImm >= 0 && AbsImm <= 255;
10199 }
10200
10201 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10202                                       bool isSEXTLoad, SDValue &Base,
10203                                       SDValue &Offset, bool &isInc,
10204                                       SelectionDAG &DAG) {
10205   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10206     return false;
10207
10208   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10209     // AddressingMode 3
10210     Base = Ptr->getOperand(0);
10211     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10212       int RHSC = (int)RHS->getZExtValue();
10213       if (RHSC < 0 && RHSC > -256) {
10214         assert(Ptr->getOpcode() == ISD::ADD);
10215         isInc = false;
10216         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10217         return true;
10218       }
10219     }
10220     isInc = (Ptr->getOpcode() == ISD::ADD);
10221     Offset = Ptr->getOperand(1);
10222     return true;
10223   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10224     // AddressingMode 2
10225     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10226       int RHSC = (int)RHS->getZExtValue();
10227       if (RHSC < 0 && RHSC > -0x1000) {
10228         assert(Ptr->getOpcode() == ISD::ADD);
10229         isInc = false;
10230         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10231         Base = Ptr->getOperand(0);
10232         return true;
10233       }
10234     }
10235
10236     if (Ptr->getOpcode() == ISD::ADD) {
10237       isInc = true;
10238       ARM_AM::ShiftOpc ShOpcVal=
10239         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10240       if (ShOpcVal != ARM_AM::no_shift) {
10241         Base = Ptr->getOperand(1);
10242         Offset = Ptr->getOperand(0);
10243       } else {
10244         Base = Ptr->getOperand(0);
10245         Offset = Ptr->getOperand(1);
10246       }
10247       return true;
10248     }
10249
10250     isInc = (Ptr->getOpcode() == ISD::ADD);
10251     Base = Ptr->getOperand(0);
10252     Offset = Ptr->getOperand(1);
10253     return true;
10254   }
10255
10256   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10257   return false;
10258 }
10259
10260 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10261                                      bool isSEXTLoad, SDValue &Base,
10262                                      SDValue &Offset, bool &isInc,
10263                                      SelectionDAG &DAG) {
10264   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10265     return false;
10266
10267   Base = Ptr->getOperand(0);
10268   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10269     int RHSC = (int)RHS->getZExtValue();
10270     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10271       assert(Ptr->getOpcode() == ISD::ADD);
10272       isInc = false;
10273       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10274       return true;
10275     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10276       isInc = Ptr->getOpcode() == ISD::ADD;
10277       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10278       return true;
10279     }
10280   }
10281
10282   return false;
10283 }
10284
10285 /// getPreIndexedAddressParts - returns true by value, base pointer and
10286 /// offset pointer and addressing mode by reference if the node's address
10287 /// can be legally represented as pre-indexed load / store address.
10288 bool
10289 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10290                                              SDValue &Offset,
10291                                              ISD::MemIndexedMode &AM,
10292                                              SelectionDAG &DAG) const {
10293   if (Subtarget->isThumb1Only())
10294     return false;
10295
10296   EVT VT;
10297   SDValue Ptr;
10298   bool isSEXTLoad = false;
10299   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10300     Ptr = LD->getBasePtr();
10301     VT  = LD->getMemoryVT();
10302     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10303   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10304     Ptr = ST->getBasePtr();
10305     VT  = ST->getMemoryVT();
10306   } else
10307     return false;
10308
10309   bool isInc;
10310   bool isLegal = false;
10311   if (Subtarget->isThumb2())
10312     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10313                                        Offset, isInc, DAG);
10314   else
10315     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10316                                         Offset, isInc, DAG);
10317   if (!isLegal)
10318     return false;
10319
10320   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10321   return true;
10322 }
10323
10324 /// getPostIndexedAddressParts - returns true by value, base pointer and
10325 /// offset pointer and addressing mode by reference if this node can be
10326 /// combined with a load / store to form a post-indexed load / store.
10327 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10328                                                    SDValue &Base,
10329                                                    SDValue &Offset,
10330                                                    ISD::MemIndexedMode &AM,
10331                                                    SelectionDAG &DAG) const {
10332   if (Subtarget->isThumb1Only())
10333     return false;
10334
10335   EVT VT;
10336   SDValue Ptr;
10337   bool isSEXTLoad = false;
10338   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10339     VT  = LD->getMemoryVT();
10340     Ptr = LD->getBasePtr();
10341     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10342   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10343     VT  = ST->getMemoryVT();
10344     Ptr = ST->getBasePtr();
10345   } else
10346     return false;
10347
10348   bool isInc;
10349   bool isLegal = false;
10350   if (Subtarget->isThumb2())
10351     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10352                                        isInc, DAG);
10353   else
10354     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10355                                         isInc, DAG);
10356   if (!isLegal)
10357     return false;
10358
10359   if (Ptr != Base) {
10360     // Swap base ptr and offset to catch more post-index load / store when
10361     // it's legal. In Thumb2 mode, offset must be an immediate.
10362     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10363         !Subtarget->isThumb2())
10364       std::swap(Base, Offset);
10365
10366     // Post-indexed load / store update the base pointer.
10367     if (Ptr != Base)
10368       return false;
10369   }
10370
10371   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10372   return true;
10373 }
10374
10375 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10376                                                       APInt &KnownZero,
10377                                                       APInt &KnownOne,
10378                                                       const SelectionDAG &DAG,
10379                                                       unsigned Depth) const {
10380   unsigned BitWidth = KnownOne.getBitWidth();
10381   KnownZero = KnownOne = APInt(BitWidth, 0);
10382   switch (Op.getOpcode()) {
10383   default: break;
10384   case ARMISD::ADDC:
10385   case ARMISD::ADDE:
10386   case ARMISD::SUBC:
10387   case ARMISD::SUBE:
10388     // These nodes' second result is a boolean
10389     if (Op.getResNo() == 0)
10390       break;
10391     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10392     break;
10393   case ARMISD::CMOV: {
10394     // Bits are known zero/one if known on the LHS and RHS.
10395     DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10396     if (KnownZero == 0 && KnownOne == 0) return;
10397
10398     APInt KnownZeroRHS, KnownOneRHS;
10399     DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10400     KnownZero &= KnownZeroRHS;
10401     KnownOne  &= KnownOneRHS;
10402     return;
10403   }
10404   case ISD::INTRINSIC_W_CHAIN: {
10405     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10406     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10407     switch (IntID) {
10408     default: return;
10409     case Intrinsic::arm_ldaex:
10410     case Intrinsic::arm_ldrex: {
10411       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10412       unsigned MemBits = VT.getScalarType().getSizeInBits();
10413       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10414       return;
10415     }
10416     }
10417   }
10418   }
10419 }
10420
10421 //===----------------------------------------------------------------------===//
10422 //                           ARM Inline Assembly Support
10423 //===----------------------------------------------------------------------===//
10424
10425 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10426   // Looking for "rev" which is V6+.
10427   if (!Subtarget->hasV6Ops())
10428     return false;
10429
10430   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10431   std::string AsmStr = IA->getAsmString();
10432   SmallVector<StringRef, 4> AsmPieces;
10433   SplitString(AsmStr, AsmPieces, ";\n");
10434
10435   switch (AsmPieces.size()) {
10436   default: return false;
10437   case 1:
10438     AsmStr = AsmPieces[0];
10439     AsmPieces.clear();
10440     SplitString(AsmStr, AsmPieces, " \t,");
10441
10442     // rev $0, $1
10443     if (AsmPieces.size() == 3 &&
10444         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10445         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10446       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10447       if (Ty && Ty->getBitWidth() == 32)
10448         return IntrinsicLowering::LowerToByteSwap(CI);
10449     }
10450     break;
10451   }
10452
10453   return false;
10454 }
10455
10456 /// getConstraintType - Given a constraint letter, return the type of
10457 /// constraint it is for this target.
10458 ARMTargetLowering::ConstraintType
10459 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10460   if (Constraint.size() == 1) {
10461     switch (Constraint[0]) {
10462     default:  break;
10463     case 'l': return C_RegisterClass;
10464     case 'w': return C_RegisterClass;
10465     case 'h': return C_RegisterClass;
10466     case 'x': return C_RegisterClass;
10467     case 't': return C_RegisterClass;
10468     case 'j': return C_Other; // Constant for movw.
10469       // An address with a single base register. Due to the way we
10470       // currently handle addresses it is the same as an 'r' memory constraint.
10471     case 'Q': return C_Memory;
10472     }
10473   } else if (Constraint.size() == 2) {
10474     switch (Constraint[0]) {
10475     default: break;
10476     // All 'U+' constraints are addresses.
10477     case 'U': return C_Memory;
10478     }
10479   }
10480   return TargetLowering::getConstraintType(Constraint);
10481 }
10482
10483 /// Examine constraint type and operand type and determine a weight value.
10484 /// This object must already have been set up with the operand type
10485 /// and the current alternative constraint selected.
10486 TargetLowering::ConstraintWeight
10487 ARMTargetLowering::getSingleConstraintMatchWeight(
10488     AsmOperandInfo &info, const char *constraint) const {
10489   ConstraintWeight weight = CW_Invalid;
10490   Value *CallOperandVal = info.CallOperandVal;
10491     // If we don't have a value, we can't do a match,
10492     // but allow it at the lowest weight.
10493   if (!CallOperandVal)
10494     return CW_Default;
10495   Type *type = CallOperandVal->getType();
10496   // Look at the constraint type.
10497   switch (*constraint) {
10498   default:
10499     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10500     break;
10501   case 'l':
10502     if (type->isIntegerTy()) {
10503       if (Subtarget->isThumb())
10504         weight = CW_SpecificReg;
10505       else
10506         weight = CW_Register;
10507     }
10508     break;
10509   case 'w':
10510     if (type->isFloatingPointTy())
10511       weight = CW_Register;
10512     break;
10513   }
10514   return weight;
10515 }
10516
10517 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10518 RCPair
10519 ARMTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
10520                                                 const std::string &Constraint,
10521                                                 MVT VT) const {
10522   if (Constraint.size() == 1) {
10523     // GCC ARM Constraint Letters
10524     switch (Constraint[0]) {
10525     case 'l': // Low regs or general regs.
10526       if (Subtarget->isThumb())
10527         return RCPair(0U, &ARM::tGPRRegClass);
10528       return RCPair(0U, &ARM::GPRRegClass);
10529     case 'h': // High regs or no regs.
10530       if (Subtarget->isThumb())
10531         return RCPair(0U, &ARM::hGPRRegClass);
10532       break;
10533     case 'r':
10534       if (Subtarget->isThumb1Only())
10535         return RCPair(0U, &ARM::tGPRRegClass);
10536       return RCPair(0U, &ARM::GPRRegClass);
10537     case 'w':
10538       if (VT == MVT::Other)
10539         break;
10540       if (VT == MVT::f32)
10541         return RCPair(0U, &ARM::SPRRegClass);
10542       if (VT.getSizeInBits() == 64)
10543         return RCPair(0U, &ARM::DPRRegClass);
10544       if (VT.getSizeInBits() == 128)
10545         return RCPair(0U, &ARM::QPRRegClass);
10546       break;
10547     case 'x':
10548       if (VT == MVT::Other)
10549         break;
10550       if (VT == MVT::f32)
10551         return RCPair(0U, &ARM::SPR_8RegClass);
10552       if (VT.getSizeInBits() == 64)
10553         return RCPair(0U, &ARM::DPR_8RegClass);
10554       if (VT.getSizeInBits() == 128)
10555         return RCPair(0U, &ARM::QPR_8RegClass);
10556       break;
10557     case 't':
10558       if (VT == MVT::f32)
10559         return RCPair(0U, &ARM::SPRRegClass);
10560       break;
10561     }
10562   }
10563   if (StringRef("{cc}").equals_lower(Constraint))
10564     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10565
10566   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10567 }
10568
10569 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10570 /// vector.  If it is invalid, don't add anything to Ops.
10571 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10572                                                      std::string &Constraint,
10573                                                      std::vector<SDValue>&Ops,
10574                                                      SelectionDAG &DAG) const {
10575   SDValue Result;
10576
10577   // Currently only support length 1 constraints.
10578   if (Constraint.length() != 1) return;
10579
10580   char ConstraintLetter = Constraint[0];
10581   switch (ConstraintLetter) {
10582   default: break;
10583   case 'j':
10584   case 'I': case 'J': case 'K': case 'L':
10585   case 'M': case 'N': case 'O':
10586     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10587     if (!C)
10588       return;
10589
10590     int64_t CVal64 = C->getSExtValue();
10591     int CVal = (int) CVal64;
10592     // None of these constraints allow values larger than 32 bits.  Check
10593     // that the value fits in an int.
10594     if (CVal != CVal64)
10595       return;
10596
10597     switch (ConstraintLetter) {
10598       case 'j':
10599         // Constant suitable for movw, must be between 0 and
10600         // 65535.
10601         if (Subtarget->hasV6T2Ops())
10602           if (CVal >= 0 && CVal <= 65535)
10603             break;
10604         return;
10605       case 'I':
10606         if (Subtarget->isThumb1Only()) {
10607           // This must be a constant between 0 and 255, for ADD
10608           // immediates.
10609           if (CVal >= 0 && CVal <= 255)
10610             break;
10611         } else if (Subtarget->isThumb2()) {
10612           // A constant that can be used as an immediate value in a
10613           // data-processing instruction.
10614           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10615             break;
10616         } else {
10617           // A constant that can be used as an immediate value in a
10618           // data-processing instruction.
10619           if (ARM_AM::getSOImmVal(CVal) != -1)
10620             break;
10621         }
10622         return;
10623
10624       case 'J':
10625         if (Subtarget->isThumb()) {  // FIXME thumb2
10626           // This must be a constant between -255 and -1, for negated ADD
10627           // immediates. This can be used in GCC with an "n" modifier that
10628           // prints the negated value, for use with SUB instructions. It is
10629           // not useful otherwise but is implemented for compatibility.
10630           if (CVal >= -255 && CVal <= -1)
10631             break;
10632         } else {
10633           // This must be a constant between -4095 and 4095. It is not clear
10634           // what this constraint is intended for. Implemented for
10635           // compatibility with GCC.
10636           if (CVal >= -4095 && CVal <= 4095)
10637             break;
10638         }
10639         return;
10640
10641       case 'K':
10642         if (Subtarget->isThumb1Only()) {
10643           // A 32-bit value where only one byte has a nonzero value. Exclude
10644           // zero to match GCC. This constraint is used by GCC internally for
10645           // constants that can be loaded with a move/shift combination.
10646           // It is not useful otherwise but is implemented for compatibility.
10647           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10648             break;
10649         } else if (Subtarget->isThumb2()) {
10650           // A constant whose bitwise inverse can be used as an immediate
10651           // value in a data-processing instruction. This can be used in GCC
10652           // with a "B" modifier that prints the inverted value, for use with
10653           // BIC and MVN instructions. It is not useful otherwise but is
10654           // implemented for compatibility.
10655           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10656             break;
10657         } else {
10658           // A constant whose bitwise inverse can be used as an immediate
10659           // value in a data-processing instruction. This can be used in GCC
10660           // with a "B" modifier that prints the inverted value, for use with
10661           // BIC and MVN instructions. It is not useful otherwise but is
10662           // implemented for compatibility.
10663           if (ARM_AM::getSOImmVal(~CVal) != -1)
10664             break;
10665         }
10666         return;
10667
10668       case 'L':
10669         if (Subtarget->isThumb1Only()) {
10670           // This must be a constant between -7 and 7,
10671           // for 3-operand ADD/SUB immediate instructions.
10672           if (CVal >= -7 && CVal < 7)
10673             break;
10674         } else if (Subtarget->isThumb2()) {
10675           // A constant whose negation can be used as an immediate value in a
10676           // data-processing instruction. This can be used in GCC with an "n"
10677           // modifier that prints the negated value, for use with SUB
10678           // instructions. It is not useful otherwise but is implemented for
10679           // compatibility.
10680           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10681             break;
10682         } else {
10683           // A constant whose negation can be used as an immediate value in a
10684           // data-processing instruction. This can be used in GCC with an "n"
10685           // modifier that prints the negated value, for use with SUB
10686           // instructions. It is not useful otherwise but is implemented for
10687           // compatibility.
10688           if (ARM_AM::getSOImmVal(-CVal) != -1)
10689             break;
10690         }
10691         return;
10692
10693       case 'M':
10694         if (Subtarget->isThumb()) { // FIXME thumb2
10695           // This must be a multiple of 4 between 0 and 1020, for
10696           // ADD sp + immediate.
10697           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10698             break;
10699         } else {
10700           // A power of two or a constant between 0 and 32.  This is used in
10701           // GCC for the shift amount on shifted register operands, but it is
10702           // useful in general for any shift amounts.
10703           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10704             break;
10705         }
10706         return;
10707
10708       case 'N':
10709         if (Subtarget->isThumb()) {  // FIXME thumb2
10710           // This must be a constant between 0 and 31, for shift amounts.
10711           if (CVal >= 0 && CVal <= 31)
10712             break;
10713         }
10714         return;
10715
10716       case 'O':
10717         if (Subtarget->isThumb()) {  // FIXME thumb2
10718           // This must be a multiple of 4 between -508 and 508, for
10719           // ADD/SUB sp = sp + immediate.
10720           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10721             break;
10722         }
10723         return;
10724     }
10725     Result = DAG.getTargetConstant(CVal, Op.getValueType());
10726     break;
10727   }
10728
10729   if (Result.getNode()) {
10730     Ops.push_back(Result);
10731     return;
10732   }
10733   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10734 }
10735
10736 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10737   assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10738   unsigned Opcode = Op->getOpcode();
10739   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10740          "Invalid opcode for Div/Rem lowering");
10741   bool isSigned = (Opcode == ISD::SDIVREM);
10742   EVT VT = Op->getValueType(0);
10743   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10744
10745   RTLIB::Libcall LC;
10746   switch (VT.getSimpleVT().SimpleTy) {
10747   default: llvm_unreachable("Unexpected request for libcall!");
10748   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
10749   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10750   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10751   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10752   }
10753
10754   SDValue InChain = DAG.getEntryNode();
10755
10756   TargetLowering::ArgListTy Args;
10757   TargetLowering::ArgListEntry Entry;
10758   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
10759     EVT ArgVT = Op->getOperand(i).getValueType();
10760     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10761     Entry.Node = Op->getOperand(i);
10762     Entry.Ty = ArgTy;
10763     Entry.isSExt = isSigned;
10764     Entry.isZExt = !isSigned;
10765     Args.push_back(Entry);
10766   }
10767
10768   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
10769                                          getPointerTy());
10770
10771   Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
10772
10773   SDLoc dl(Op);
10774   TargetLowering::CallLoweringInfo CLI(DAG);
10775   CLI.setDebugLoc(dl).setChain(InChain)
10776     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
10777     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
10778
10779   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
10780   return CallInfo.first;
10781 }
10782
10783 SDValue
10784 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
10785   assert(Subtarget->isTargetWindows() && "unsupported target platform");
10786   SDLoc DL(Op);
10787
10788   // Get the inputs.
10789   SDValue Chain = Op.getOperand(0);
10790   SDValue Size  = Op.getOperand(1);
10791
10792   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
10793                               DAG.getConstant(2, MVT::i32));
10794
10795   SDValue Flag;
10796   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
10797   Flag = Chain.getValue(1);
10798
10799   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10800   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
10801
10802   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
10803   Chain = NewSP.getValue(1);
10804
10805   SDValue Ops[2] = { NewSP, Chain };
10806   return DAG.getMergeValues(Ops, DL);
10807 }
10808
10809 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
10810   assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
10811          "Unexpected type for custom-lowering FP_EXTEND");
10812
10813   RTLIB::Libcall LC;
10814   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
10815
10816   SDValue SrcVal = Op.getOperand(0);
10817   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
10818                      /*isSigned*/ false, SDLoc(Op)).first;
10819 }
10820
10821 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
10822   assert(Op.getOperand(0).getValueType() == MVT::f64 &&
10823          Subtarget->isFPOnlySP() &&
10824          "Unexpected type for custom-lowering FP_ROUND");
10825
10826   RTLIB::Libcall LC;
10827   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
10828
10829   SDValue SrcVal = Op.getOperand(0);
10830   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
10831                      /*isSigned*/ false, SDLoc(Op)).first;
10832 }
10833
10834 bool
10835 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10836   // The ARM target isn't yet aware of offsets.
10837   return false;
10838 }
10839
10840 bool ARM::isBitFieldInvertedMask(unsigned v) {
10841   if (v == 0xffffffff)
10842     return false;
10843
10844   // there can be 1's on either or both "outsides", all the "inside"
10845   // bits must be 0's
10846   return isShiftedMask_32(~v);
10847 }
10848
10849 /// isFPImmLegal - Returns true if the target can instruction select the
10850 /// specified FP immediate natively. If false, the legalizer will
10851 /// materialize the FP immediate as a load from a constant pool.
10852 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10853   if (!Subtarget->hasVFP3())
10854     return false;
10855   if (VT == MVT::f32)
10856     return ARM_AM::getFP32Imm(Imm) != -1;
10857   if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
10858     return ARM_AM::getFP64Imm(Imm) != -1;
10859   return false;
10860 }
10861
10862 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10863 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
10864 /// specified in the intrinsic calls.
10865 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10866                                            const CallInst &I,
10867                                            unsigned Intrinsic) const {
10868   switch (Intrinsic) {
10869   case Intrinsic::arm_neon_vld1:
10870   case Intrinsic::arm_neon_vld2:
10871   case Intrinsic::arm_neon_vld3:
10872   case Intrinsic::arm_neon_vld4:
10873   case Intrinsic::arm_neon_vld2lane:
10874   case Intrinsic::arm_neon_vld3lane:
10875   case Intrinsic::arm_neon_vld4lane: {
10876     Info.opc = ISD::INTRINSIC_W_CHAIN;
10877     // Conservatively set memVT to the entire set of vectors loaded.
10878     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10879     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10880     Info.ptrVal = I.getArgOperand(0);
10881     Info.offset = 0;
10882     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10883     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10884     Info.vol = false; // volatile loads with NEON intrinsics not supported
10885     Info.readMem = true;
10886     Info.writeMem = false;
10887     return true;
10888   }
10889   case Intrinsic::arm_neon_vst1:
10890   case Intrinsic::arm_neon_vst2:
10891   case Intrinsic::arm_neon_vst3:
10892   case Intrinsic::arm_neon_vst4:
10893   case Intrinsic::arm_neon_vst2lane:
10894   case Intrinsic::arm_neon_vst3lane:
10895   case Intrinsic::arm_neon_vst4lane: {
10896     Info.opc = ISD::INTRINSIC_VOID;
10897     // Conservatively set memVT to the entire set of vectors stored.
10898     unsigned NumElts = 0;
10899     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10900       Type *ArgTy = I.getArgOperand(ArgI)->getType();
10901       if (!ArgTy->isVectorTy())
10902         break;
10903       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10904     }
10905     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10906     Info.ptrVal = I.getArgOperand(0);
10907     Info.offset = 0;
10908     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10909     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10910     Info.vol = false; // volatile stores with NEON intrinsics not supported
10911     Info.readMem = false;
10912     Info.writeMem = true;
10913     return true;
10914   }
10915   case Intrinsic::arm_ldaex:
10916   case Intrinsic::arm_ldrex: {
10917     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
10918     Info.opc = ISD::INTRINSIC_W_CHAIN;
10919     Info.memVT = MVT::getVT(PtrTy->getElementType());
10920     Info.ptrVal = I.getArgOperand(0);
10921     Info.offset = 0;
10922     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10923     Info.vol = true;
10924     Info.readMem = true;
10925     Info.writeMem = false;
10926     return true;
10927   }
10928   case Intrinsic::arm_stlex:
10929   case Intrinsic::arm_strex: {
10930     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
10931     Info.opc = ISD::INTRINSIC_W_CHAIN;
10932     Info.memVT = MVT::getVT(PtrTy->getElementType());
10933     Info.ptrVal = I.getArgOperand(1);
10934     Info.offset = 0;
10935     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10936     Info.vol = true;
10937     Info.readMem = false;
10938     Info.writeMem = true;
10939     return true;
10940   }
10941   case Intrinsic::arm_stlexd:
10942   case Intrinsic::arm_strexd: {
10943     Info.opc = ISD::INTRINSIC_W_CHAIN;
10944     Info.memVT = MVT::i64;
10945     Info.ptrVal = I.getArgOperand(2);
10946     Info.offset = 0;
10947     Info.align = 8;
10948     Info.vol = true;
10949     Info.readMem = false;
10950     Info.writeMem = true;
10951     return true;
10952   }
10953   case Intrinsic::arm_ldaexd:
10954   case Intrinsic::arm_ldrexd: {
10955     Info.opc = ISD::INTRINSIC_W_CHAIN;
10956     Info.memVT = MVT::i64;
10957     Info.ptrVal = I.getArgOperand(0);
10958     Info.offset = 0;
10959     Info.align = 8;
10960     Info.vol = true;
10961     Info.readMem = true;
10962     Info.writeMem = false;
10963     return true;
10964   }
10965   default:
10966     break;
10967   }
10968
10969   return false;
10970 }
10971
10972 /// \brief Returns true if it is beneficial to convert a load of a constant
10973 /// to just the constant itself.
10974 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
10975                                                           Type *Ty) const {
10976   assert(Ty->isIntegerTy());
10977
10978   unsigned Bits = Ty->getPrimitiveSizeInBits();
10979   if (Bits == 0 || Bits > 32)
10980     return false;
10981   return true;
10982 }
10983
10984 bool ARMTargetLowering::hasLoadLinkedStoreConditional() const { return true; }
10985
10986 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
10987                                         ARM_MB::MemBOpt Domain) const {
10988   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10989
10990   // First, if the target has no DMB, see what fallback we can use.
10991   if (!Subtarget->hasDataBarrier()) {
10992     // Some ARMv6 cpus can support data barriers with an mcr instruction.
10993     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
10994     // here.
10995     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
10996       Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
10997       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
10998                         Builder.getInt32(0), Builder.getInt32(7),
10999                         Builder.getInt32(10), Builder.getInt32(5)};
11000       return Builder.CreateCall(MCR, args);
11001     } else {
11002       // Instead of using barriers, atomic accesses on these subtargets use
11003       // libcalls.
11004       llvm_unreachable("makeDMB on a target so old that it has no barriers");
11005     }
11006   } else {
11007     Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
11008     // Only a full system barrier exists in the M-class architectures.
11009     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
11010     Constant *CDomain = Builder.getInt32(Domain);
11011     return Builder.CreateCall(DMB, CDomain);
11012   }
11013 }
11014
11015 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11016 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11017                                          AtomicOrdering Ord, bool IsStore,
11018                                          bool IsLoad) const {
11019   if (!getInsertFencesForAtomic())
11020     return nullptr;
11021
11022   switch (Ord) {
11023   case NotAtomic:
11024   case Unordered:
11025     llvm_unreachable("Invalid fence: unordered/non-atomic");
11026   case Monotonic:
11027   case Acquire:
11028     return nullptr; // Nothing to do
11029   case SequentiallyConsistent:
11030     if (!IsStore)
11031       return nullptr; // Nothing to do
11032     /*FALLTHROUGH*/
11033   case Release:
11034   case AcquireRelease:
11035     if (Subtarget->isSwift())
11036       return makeDMB(Builder, ARM_MB::ISHST);
11037     // FIXME: add a comment with a link to documentation justifying this.
11038     else
11039       return makeDMB(Builder, ARM_MB::ISH);
11040   }
11041   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
11042 }
11043
11044 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11045                                           AtomicOrdering Ord, bool IsStore,
11046                                           bool IsLoad) const {
11047   if (!getInsertFencesForAtomic())
11048     return nullptr;
11049
11050   switch (Ord) {
11051   case NotAtomic:
11052   case Unordered:
11053     llvm_unreachable("Invalid fence: unordered/not-atomic");
11054   case Monotonic:
11055   case Release:
11056     return nullptr; // Nothing to do
11057   case Acquire:
11058   case AcquireRelease:
11059   case SequentiallyConsistent:
11060     return makeDMB(Builder, ARM_MB::ISH);
11061   }
11062   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
11063 }
11064
11065 // Loads and stores less than 64-bits are already atomic; ones above that
11066 // are doomed anyway, so defer to the default libcall and blame the OS when
11067 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11068 // anything for those.
11069 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11070   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11071   return (Size == 64) && !Subtarget->isMClass();
11072 }
11073
11074 // Loads and stores less than 64-bits are already atomic; ones above that
11075 // are doomed anyway, so defer to the default libcall and blame the OS when
11076 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11077 // anything for those.
11078 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
11079 // guarantee, see DDI0406C ARM architecture reference manual,
11080 // sections A8.8.72-74 LDRD)
11081 bool ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11082   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11083   return (Size == 64) && !Subtarget->isMClass();
11084 }
11085
11086 // For the real atomic operations, we have ldrex/strex up to 32 bits,
11087 // and up to 64 bits on the non-M profiles
11088 TargetLoweringBase::AtomicRMWExpansionKind
11089 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11090   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11091   return (Size <= (Subtarget->isMClass() ? 32U : 64U))
11092              ? AtomicRMWExpansionKind::LLSC
11093              : AtomicRMWExpansionKind::None;
11094 }
11095
11096 // This has so far only been implemented for MachO.
11097 bool ARMTargetLowering::useLoadStackGuardNode() const {
11098   return Subtarget->isTargetMachO();
11099 }
11100
11101 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
11102                                                   unsigned &Cost) const {
11103   // If we do not have NEON, vector types are not natively supported.
11104   if (!Subtarget->hasNEON())
11105     return false;
11106
11107   // Floating point values and vector values map to the same register file.
11108   // Therefore, althought we could do a store extract of a vector type, this is
11109   // better to leave at float as we have more freedom in the addressing mode for
11110   // those.
11111   if (VectorTy->isFPOrFPVectorTy())
11112     return false;
11113
11114   // If the index is unknown at compile time, this is very expensive to lower
11115   // and it is not possible to combine the store with the extract.
11116   if (!isa<ConstantInt>(Idx))
11117     return false;
11118
11119   assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
11120   unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
11121   // We can do a store + vector extract on any vector that fits perfectly in a D
11122   // or Q register.
11123   if (BitWidth == 64 || BitWidth == 128) {
11124     Cost = 0;
11125     return true;
11126   }
11127   return false;
11128 }
11129
11130 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11131                                          AtomicOrdering Ord) const {
11132   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11133   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11134   bool IsAcquire = isAtLeastAcquire(Ord);
11135
11136   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
11137   // intrinsic must return {i32, i32} and we have to recombine them into a
11138   // single i64 here.
11139   if (ValTy->getPrimitiveSizeInBits() == 64) {
11140     Intrinsic::ID Int =
11141         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
11142     Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
11143
11144     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11145     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
11146
11147     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11148     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11149     if (!Subtarget->isLittle())
11150       std::swap (Lo, Hi);
11151     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11152     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11153     return Builder.CreateOr(
11154         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
11155   }
11156
11157   Type *Tys[] = { Addr->getType() };
11158   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
11159   Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
11160
11161   return Builder.CreateTruncOrBitCast(
11162       Builder.CreateCall(Ldrex, Addr),
11163       cast<PointerType>(Addr->getType())->getElementType());
11164 }
11165
11166 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
11167                                                Value *Addr,
11168                                                AtomicOrdering Ord) const {
11169   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11170   bool IsRelease = isAtLeastRelease(Ord);
11171
11172   // Since the intrinsics must have legal type, the i64 intrinsics take two
11173   // parameters: "i32, i32". We must marshal Val into the appropriate form
11174   // before the call.
11175   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
11176     Intrinsic::ID Int =
11177         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
11178     Function *Strex = Intrinsic::getDeclaration(M, Int);
11179     Type *Int32Ty = Type::getInt32Ty(M->getContext());
11180
11181     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
11182     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
11183     if (!Subtarget->isLittle())
11184       std::swap (Lo, Hi);
11185     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11186     return Builder.CreateCall3(Strex, Lo, Hi, Addr);
11187   }
11188
11189   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
11190   Type *Tys[] = { Addr->getType() };
11191   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
11192
11193   return Builder.CreateCall2(
11194       Strex, Builder.CreateZExtOrBitCast(
11195                  Val, Strex->getFunctionType()->getParamType(0)),
11196       Addr);
11197 }
11198
11199 enum HABaseType {
11200   HA_UNKNOWN = 0,
11201   HA_FLOAT,
11202   HA_DOUBLE,
11203   HA_VECT64,
11204   HA_VECT128
11205 };
11206
11207 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
11208                                    uint64_t &Members) {
11209   if (const StructType *ST = dyn_cast<StructType>(Ty)) {
11210     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
11211       uint64_t SubMembers = 0;
11212       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
11213         return false;
11214       Members += SubMembers;
11215     }
11216   } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
11217     uint64_t SubMembers = 0;
11218     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
11219       return false;
11220     Members += SubMembers * AT->getNumElements();
11221   } else if (Ty->isFloatTy()) {
11222     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
11223       return false;
11224     Members = 1;
11225     Base = HA_FLOAT;
11226   } else if (Ty->isDoubleTy()) {
11227     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
11228       return false;
11229     Members = 1;
11230     Base = HA_DOUBLE;
11231   } else if (const VectorType *VT = dyn_cast<VectorType>(Ty)) {
11232     Members = 1;
11233     switch (Base) {
11234     case HA_FLOAT:
11235     case HA_DOUBLE:
11236       return false;
11237     case HA_VECT64:
11238       return VT->getBitWidth() == 64;
11239     case HA_VECT128:
11240       return VT->getBitWidth() == 128;
11241     case HA_UNKNOWN:
11242       switch (VT->getBitWidth()) {
11243       case 64:
11244         Base = HA_VECT64;
11245         return true;
11246       case 128:
11247         Base = HA_VECT128;
11248         return true;
11249       default:
11250         return false;
11251       }
11252     }
11253   }
11254
11255   return (Members > 0 && Members <= 4);
11256 }
11257
11258 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
11259 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
11260 /// passing according to AAPCS rules.
11261 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
11262     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11263   if (getEffectiveCallingConv(CallConv, isVarArg) !=
11264       CallingConv::ARM_AAPCS_VFP)
11265     return false;
11266
11267   HABaseType Base = HA_UNKNOWN;
11268   uint64_t Members = 0;
11269   bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
11270   DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
11271
11272   bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
11273   return IsHA || IsIntArray;
11274 }