ScheduleDAGInstrs: In functions with tail calls PseudoSourceValues are not non-aliasi...
[oota-llvm.git] / lib / Target / ARM / ARMISelLowering.cpp
1 //===-- ARMISelLowering.cpp - ARM DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that ARM uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "ARMISelLowering.h"
16 #include "ARMCallingConv.h"
17 #include "ARMConstantPoolValue.h"
18 #include "ARMMachineFunctionInfo.h"
19 #include "ARMPerfectShuffle.h"
20 #include "ARMSubtarget.h"
21 #include "ARMTargetMachine.h"
22 #include "ARMTargetObjectFile.h"
23 #include "MCTargetDesc/ARMAddressingModes.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/ADT/StringSwitch.h"
27 #include "llvm/CodeGen/CallingConvLower.h"
28 #include "llvm/CodeGen/IntrinsicLowering.h"
29 #include "llvm/CodeGen/MachineBasicBlock.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineJumpTableInfo.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/SelectionDAG.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/GlobalValue.h"
41 #include "llvm/IR/IRBuilder.h"
42 #include "llvm/IR/Instruction.h"
43 #include "llvm/IR/Instructions.h"
44 #include "llvm/IR/IntrinsicInst.h"
45 #include "llvm/IR/Intrinsics.h"
46 #include "llvm/IR/Type.h"
47 #include "llvm/MC/MCSectionMachO.h"
48 #include "llvm/Support/CommandLine.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Support/raw_ostream.h"
53 #include "llvm/Target/TargetOptions.h"
54 #include <utility>
55 using namespace llvm;
56
57 #define DEBUG_TYPE "arm-isel"
58
59 STATISTIC(NumTailCalls, "Number of tail calls");
60 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
61 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
62
63 cl::opt<bool>
64 EnableARMLongCalls("arm-long-calls", cl::Hidden,
65   cl::desc("Generate calls via indirect call instructions"),
66   cl::init(false));
67
68 static cl::opt<bool>
69 ARMInterworking("arm-interworking", cl::Hidden,
70   cl::desc("Enable / disable ARM interworking (for debugging only)"),
71   cl::init(true));
72
73 namespace {
74   class ARMCCState : public CCState {
75   public:
76     ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
77                SmallVectorImpl<CCValAssign> &locs, LLVMContext &C,
78                ParmContext PC)
79         : CCState(CC, isVarArg, MF, locs, C) {
80       assert(((PC == Call) || (PC == Prologue)) &&
81              "ARMCCState users must specify whether their context is call"
82              "or prologue generation.");
83       CallOrPrologue = PC;
84     }
85   };
86 }
87
88 // The APCS parameter registers.
89 static const MCPhysReg GPRArgRegs[] = {
90   ARM::R0, ARM::R1, ARM::R2, ARM::R3
91 };
92
93 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
94                                        MVT PromotedBitwiseVT) {
95   if (VT != PromotedLdStVT) {
96     setOperationAction(ISD::LOAD, VT, Promote);
97     AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
98
99     setOperationAction(ISD::STORE, VT, Promote);
100     AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
101   }
102
103   MVT ElemTy = VT.getVectorElementType();
104   if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
105     setOperationAction(ISD::SETCC, VT, Custom);
106   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
107   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
108   if (ElemTy == MVT::i32) {
109     setOperationAction(ISD::SINT_TO_FP, VT, Custom);
110     setOperationAction(ISD::UINT_TO_FP, VT, Custom);
111     setOperationAction(ISD::FP_TO_SINT, VT, Custom);
112     setOperationAction(ISD::FP_TO_UINT, VT, Custom);
113   } else {
114     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
115     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
116     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
117     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
118   }
119   setOperationAction(ISD::BUILD_VECTOR,      VT, Custom);
120   setOperationAction(ISD::VECTOR_SHUFFLE,    VT, Custom);
121   setOperationAction(ISD::CONCAT_VECTORS,    VT, Legal);
122   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
123   setOperationAction(ISD::SELECT,            VT, Expand);
124   setOperationAction(ISD::SELECT_CC,         VT, Expand);
125   setOperationAction(ISD::VSELECT,           VT, Expand);
126   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
127   if (VT.isInteger()) {
128     setOperationAction(ISD::SHL, VT, Custom);
129     setOperationAction(ISD::SRA, VT, Custom);
130     setOperationAction(ISD::SRL, VT, Custom);
131   }
132
133   // Promote all bit-wise operations.
134   if (VT.isInteger() && VT != PromotedBitwiseVT) {
135     setOperationAction(ISD::AND, VT, Promote);
136     AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
137     setOperationAction(ISD::OR,  VT, Promote);
138     AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
139     setOperationAction(ISD::XOR, VT, Promote);
140     AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
141   }
142
143   // Neon does not support vector divide/remainder operations.
144   setOperationAction(ISD::SDIV, VT, Expand);
145   setOperationAction(ISD::UDIV, VT, Expand);
146   setOperationAction(ISD::FDIV, VT, Expand);
147   setOperationAction(ISD::SREM, VT, Expand);
148   setOperationAction(ISD::UREM, VT, Expand);
149   setOperationAction(ISD::FREM, VT, Expand);
150 }
151
152 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
153   addRegisterClass(VT, &ARM::DPRRegClass);
154   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
155 }
156
157 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
158   addRegisterClass(VT, &ARM::DPairRegClass);
159   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
160 }
161
162 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM,
163                                      const ARMSubtarget &STI)
164     : TargetLowering(TM), Subtarget(&STI) {
165   RegInfo = Subtarget->getRegisterInfo();
166   Itins = Subtarget->getInstrItineraryData();
167
168   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
169
170   if (Subtarget->isTargetMachO()) {
171     // Uses VFP for Thumb libfuncs if available.
172     if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
173         Subtarget->hasARMOps() && !TM.Options.UseSoftFloat) {
174       // Single-precision floating-point arithmetic.
175       setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
176       setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
177       setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
178       setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
179
180       // Double-precision floating-point arithmetic.
181       setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
182       setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
183       setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
184       setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
185
186       // Single-precision comparisons.
187       setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
188       setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
189       setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
190       setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
191       setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
192       setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
193       setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
194       setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
195
196       setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
197       setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
198       setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
199       setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
200       setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
201       setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
202       setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
203       setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
204
205       // Double-precision comparisons.
206       setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
207       setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
208       setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
209       setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
210       setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
211       setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
212       setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
213       setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
214
215       setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
216       setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
217       setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
218       setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
219       setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
220       setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
221       setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
222       setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
223
224       // Floating-point to integer conversions.
225       // i64 conversions are done via library routines even when generating VFP
226       // instructions, so use the same ones.
227       setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
228       setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
229       setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
230       setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
231
232       // Conversions between floating types.
233       setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
234       setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
235
236       // Integer to floating-point conversions.
237       // i64 conversions are done via library routines even when generating VFP
238       // instructions, so use the same ones.
239       // FIXME: There appears to be some naming inconsistency in ARM libgcc:
240       // e.g., __floatunsidf vs. __floatunssidfvfp.
241       setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
242       setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
243       setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
244       setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
245     }
246   }
247
248   // These libcalls are not available in 32-bit.
249   setLibcallName(RTLIB::SHL_I128, nullptr);
250   setLibcallName(RTLIB::SRL_I128, nullptr);
251   setLibcallName(RTLIB::SRA_I128, nullptr);
252
253   if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO() &&
254       !Subtarget->isTargetWindows()) {
255     static const struct {
256       const RTLIB::Libcall Op;
257       const char * const Name;
258       const CallingConv::ID CC;
259       const ISD::CondCode Cond;
260     } LibraryCalls[] = {
261       // Double-precision floating-point arithmetic helper functions
262       // RTABI chapter 4.1.2, Table 2
263       { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
264       { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
265       { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
266       { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
267
268       // Double-precision floating-point comparison helper functions
269       // RTABI chapter 4.1.2, Table 3
270       { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
271       { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
272       { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
273       { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
274       { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
275       { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
276       { RTLIB::UO_F64,  "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
277       { RTLIB::O_F64,   "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
278
279       // Single-precision floating-point arithmetic helper functions
280       // RTABI chapter 4.1.2, Table 4
281       { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
282       { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
283       { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
284       { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
285
286       // Single-precision floating-point comparison helper functions
287       // RTABI chapter 4.1.2, Table 5
288       { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
289       { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
290       { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
291       { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
292       { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
293       { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
294       { RTLIB::UO_F32,  "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
295       { RTLIB::O_F32,   "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
296
297       // Floating-point to integer conversions.
298       // RTABI chapter 4.1.2, Table 6
299       { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
300       { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
301       { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
302       { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
303       { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
304       { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
305       { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
306       { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
307
308       // Conversions between floating types.
309       // RTABI chapter 4.1.2, Table 7
310       { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
311       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
312       { RTLIB::FPEXT_F32_F64,   "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
313
314       // Integer to floating-point conversions.
315       // RTABI chapter 4.1.2, Table 8
316       { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
317       { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
318       { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
319       { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
320       { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
321       { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
322       { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
323       { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
324
325       // Long long helper functions
326       // RTABI chapter 4.2, Table 9
327       { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
328       { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
329       { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
330       { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
331
332       // Integer division functions
333       // RTABI chapter 4.3.1
334       { RTLIB::SDIV_I8,  "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
335       { RTLIB::SDIV_I16, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
336       { RTLIB::SDIV_I32, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
337       { RTLIB::SDIV_I64, "__aeabi_ldivmod",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
338       { RTLIB::UDIV_I8,  "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
339       { RTLIB::UDIV_I16, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
340       { RTLIB::UDIV_I32, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
341       { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
342
343       // Memory operations
344       // RTABI chapter 4.3.4
345       { RTLIB::MEMCPY,  "__aeabi_memcpy",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
346       { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
347       { RTLIB::MEMSET,  "__aeabi_memset",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
348     };
349
350     for (const auto &LC : LibraryCalls) {
351       setLibcallName(LC.Op, LC.Name);
352       setLibcallCallingConv(LC.Op, LC.CC);
353       if (LC.Cond != ISD::SETCC_INVALID)
354         setCmpLibcallCC(LC.Op, LC.Cond);
355     }
356   }
357
358   if (Subtarget->isTargetWindows()) {
359     static const struct {
360       const RTLIB::Libcall Op;
361       const char * const Name;
362       const CallingConv::ID CC;
363     } LibraryCalls[] = {
364       { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
365       { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
366       { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
367       { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
368       { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
369       { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
370       { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
371       { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
372     };
373
374     for (const auto &LC : LibraryCalls) {
375       setLibcallName(LC.Op, LC.Name);
376       setLibcallCallingConv(LC.Op, LC.CC);
377     }
378   }
379
380   // Use divmod compiler-rt calls for iOS 5.0 and later.
381   if (Subtarget->getTargetTriple().isiOS() &&
382       !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
383     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
384     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
385   }
386
387   // The half <-> float conversion functions are always soft-float, but are
388   // needed for some targets which use a hard-float calling convention by
389   // default.
390   if (Subtarget->isAAPCS_ABI()) {
391     setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
392     setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
393     setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
394   } else {
395     setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
396     setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
397     setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
398   }
399
400   if (Subtarget->isThumb1Only())
401     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
402   else
403     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
404   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
405       !Subtarget->isThumb1Only()) {
406     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
407     addRegisterClass(MVT::f64, &ARM::DPRRegClass);
408   }
409
410   for (MVT VT : MVT::vector_valuetypes()) {
411     for (MVT InnerVT : MVT::vector_valuetypes()) {
412       setTruncStoreAction(VT, InnerVT, Expand);
413       setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
414       setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
415       setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
416     }
417
418     setOperationAction(ISD::MULHS, VT, Expand);
419     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
420     setOperationAction(ISD::MULHU, VT, Expand);
421     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
422
423     setOperationAction(ISD::BSWAP, VT, Expand);
424   }
425
426   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
427   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
428
429   if (Subtarget->hasNEON()) {
430     addDRTypeForNEON(MVT::v2f32);
431     addDRTypeForNEON(MVT::v8i8);
432     addDRTypeForNEON(MVT::v4i16);
433     addDRTypeForNEON(MVT::v2i32);
434     addDRTypeForNEON(MVT::v1i64);
435
436     addQRTypeForNEON(MVT::v4f32);
437     addQRTypeForNEON(MVT::v2f64);
438     addQRTypeForNEON(MVT::v16i8);
439     addQRTypeForNEON(MVT::v8i16);
440     addQRTypeForNEON(MVT::v4i32);
441     addQRTypeForNEON(MVT::v2i64);
442
443     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
444     // neither Neon nor VFP support any arithmetic operations on it.
445     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
446     // supported for v4f32.
447     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
448     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
449     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
450     // FIXME: Code duplication: FDIV and FREM are expanded always, see
451     // ARMTargetLowering::addTypeForNEON method for details.
452     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
453     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
454     // FIXME: Create unittest.
455     // In another words, find a way when "copysign" appears in DAG with vector
456     // operands.
457     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
458     // FIXME: Code duplication: SETCC has custom operation action, see
459     // ARMTargetLowering::addTypeForNEON method for details.
460     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
461     // FIXME: Create unittest for FNEG and for FABS.
462     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
463     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
464     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
465     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
466     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
467     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
468     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
469     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
470     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
471     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
472     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
473     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
474     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
475     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
476     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
477     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
478     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
479     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
480     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
481
482     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
483     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
484     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
485     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
486     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
487     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
488     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
489     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
490     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
491     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
492     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
493     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
494     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
495     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
496     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
497
498     // Mark v2f32 intrinsics.
499     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
500     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
501     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
502     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
503     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
504     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
505     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
506     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
507     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
508     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
509     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
510     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
511     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
512     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
513     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
514
515     // Neon does not support some operations on v1i64 and v2i64 types.
516     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
517     // Custom handling for some quad-vector types to detect VMULL.
518     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
519     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
520     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
521     // Custom handling for some vector types to avoid expensive expansions
522     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
523     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
524     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
525     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
526     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
527     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
528     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
529     // a destination type that is wider than the source, and nor does
530     // it have a FP_TO_[SU]INT instruction with a narrower destination than
531     // source.
532     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
533     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
534     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
535     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
536
537     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
538     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
539
540     // NEON does not have single instruction CTPOP for vectors with element
541     // types wider than 8-bits.  However, custom lowering can leverage the
542     // v8i8/v16i8 vcnt instruction.
543     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
544     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
545     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
546     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
547
548     // NEON only has FMA instructions as of VFP4.
549     if (!Subtarget->hasVFP4()) {
550       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
551       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
552     }
553
554     setTargetDAGCombine(ISD::INTRINSIC_VOID);
555     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
556     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
557     setTargetDAGCombine(ISD::SHL);
558     setTargetDAGCombine(ISD::SRL);
559     setTargetDAGCombine(ISD::SRA);
560     setTargetDAGCombine(ISD::SIGN_EXTEND);
561     setTargetDAGCombine(ISD::ZERO_EXTEND);
562     setTargetDAGCombine(ISD::ANY_EXTEND);
563     setTargetDAGCombine(ISD::SELECT_CC);
564     setTargetDAGCombine(ISD::BUILD_VECTOR);
565     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
566     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
567     setTargetDAGCombine(ISD::STORE);
568     setTargetDAGCombine(ISD::FP_TO_SINT);
569     setTargetDAGCombine(ISD::FP_TO_UINT);
570     setTargetDAGCombine(ISD::FDIV);
571     setTargetDAGCombine(ISD::LOAD);
572
573     // It is legal to extload from v4i8 to v4i16 or v4i32.
574     for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
575                    MVT::v2i32}) {
576       for (MVT VT : MVT::integer_vector_valuetypes()) {
577         setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
578         setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
579         setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
580       }
581     }
582   }
583
584   // ARM and Thumb2 support UMLAL/SMLAL.
585   if (!Subtarget->isThumb1Only())
586     setTargetDAGCombine(ISD::ADDC);
587
588   if (Subtarget->isFPOnlySP()) {
589     // When targetting a floating-point unit with only single-precision
590     // operations, f64 is legal for the few double-precision instructions which
591     // are present However, no double-precision operations other than moves,
592     // loads and stores are provided by the hardware.
593     setOperationAction(ISD::FADD,       MVT::f64, Expand);
594     setOperationAction(ISD::FSUB,       MVT::f64, Expand);
595     setOperationAction(ISD::FMUL,       MVT::f64, Expand);
596     setOperationAction(ISD::FMA,        MVT::f64, Expand);
597     setOperationAction(ISD::FDIV,       MVT::f64, Expand);
598     setOperationAction(ISD::FREM,       MVT::f64, Expand);
599     setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
600     setOperationAction(ISD::FGETSIGN,   MVT::f64, Expand);
601     setOperationAction(ISD::FNEG,       MVT::f64, Expand);
602     setOperationAction(ISD::FABS,       MVT::f64, Expand);
603     setOperationAction(ISD::FSQRT,      MVT::f64, Expand);
604     setOperationAction(ISD::FSIN,       MVT::f64, Expand);
605     setOperationAction(ISD::FCOS,       MVT::f64, Expand);
606     setOperationAction(ISD::FPOWI,      MVT::f64, Expand);
607     setOperationAction(ISD::FPOW,       MVT::f64, Expand);
608     setOperationAction(ISD::FLOG,       MVT::f64, Expand);
609     setOperationAction(ISD::FLOG2,      MVT::f64, Expand);
610     setOperationAction(ISD::FLOG10,     MVT::f64, Expand);
611     setOperationAction(ISD::FEXP,       MVT::f64, Expand);
612     setOperationAction(ISD::FEXP2,      MVT::f64, Expand);
613     setOperationAction(ISD::FCEIL,      MVT::f64, Expand);
614     setOperationAction(ISD::FTRUNC,     MVT::f64, Expand);
615     setOperationAction(ISD::FRINT,      MVT::f64, Expand);
616     setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
617     setOperationAction(ISD::FFLOOR,     MVT::f64, Expand);
618     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
619     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
620     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
621     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
622     setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
623     setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
624     setOperationAction(ISD::FP_ROUND,   MVT::f32, Custom);
625     setOperationAction(ISD::FP_EXTEND,  MVT::f64, Custom);
626   }
627
628   computeRegisterProperties(Subtarget->getRegisterInfo());
629
630   // ARM does not have floating-point extending loads.
631   for (MVT VT : MVT::fp_valuetypes()) {
632     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
633     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
634   }
635
636   // ... or truncating stores
637   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
638   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
639   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
640
641   // ARM does not have i1 sign extending load.
642   for (MVT VT : MVT::integer_valuetypes())
643     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
644
645   // ARM supports all 4 flavors of integer indexed load / store.
646   if (!Subtarget->isThumb1Only()) {
647     for (unsigned im = (unsigned)ISD::PRE_INC;
648          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
649       setIndexedLoadAction(im,  MVT::i1,  Legal);
650       setIndexedLoadAction(im,  MVT::i8,  Legal);
651       setIndexedLoadAction(im,  MVT::i16, Legal);
652       setIndexedLoadAction(im,  MVT::i32, Legal);
653       setIndexedStoreAction(im, MVT::i1,  Legal);
654       setIndexedStoreAction(im, MVT::i8,  Legal);
655       setIndexedStoreAction(im, MVT::i16, Legal);
656       setIndexedStoreAction(im, MVT::i32, Legal);
657     }
658   }
659
660   setOperationAction(ISD::SADDO, MVT::i32, Custom);
661   setOperationAction(ISD::UADDO, MVT::i32, Custom);
662   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
663   setOperationAction(ISD::USUBO, MVT::i32, Custom);
664
665   // i64 operation support.
666   setOperationAction(ISD::MUL,     MVT::i64, Expand);
667   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
668   if (Subtarget->isThumb1Only()) {
669     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
670     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
671   }
672   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
673       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
674     setOperationAction(ISD::MULHS, MVT::i32, Expand);
675
676   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
677   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
678   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
679   setOperationAction(ISD::SRL,       MVT::i64, Custom);
680   setOperationAction(ISD::SRA,       MVT::i64, Custom);
681
682   if (!Subtarget->isThumb1Only()) {
683     // FIXME: We should do this for Thumb1 as well.
684     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
685     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
686     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
687     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
688   }
689
690   // ARM does not have ROTL.
691   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
692   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
693   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
694   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
695     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
696
697   // These just redirect to CTTZ and CTLZ on ARM.
698   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
699   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
700
701   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
702
703   // Only ARMv6 has BSWAP.
704   if (!Subtarget->hasV6Ops())
705     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
706
707   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
708       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
709     // These are expanded into libcalls if the cpu doesn't have HW divider.
710     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
711     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
712   }
713
714   // FIXME: Also set divmod for SREM on EABI
715   setOperationAction(ISD::SREM,  MVT::i32, Expand);
716   setOperationAction(ISD::UREM,  MVT::i32, Expand);
717   // Register based DivRem for AEABI (RTABI 4.2)
718   if (Subtarget->isTargetAEABI()) {
719     setLibcallName(RTLIB::SDIVREM_I8,  "__aeabi_idivmod");
720     setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
721     setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
722     setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
723     setLibcallName(RTLIB::UDIVREM_I8,  "__aeabi_uidivmod");
724     setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
725     setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
726     setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
727
728     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
729     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
730     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
731     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
732     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
733     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
734     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
735     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
736
737     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
738     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
739   } else {
740     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
741     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
742   }
743
744   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
745   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
746   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
747   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
748   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
749
750   setOperationAction(ISD::TRAP, MVT::Other, Legal);
751
752   // Use the default implementation.
753   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
754   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
755   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
756   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
757   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
758   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
759
760   if (!Subtarget->isTargetMachO()) {
761     // Non-MachO platforms may return values in these registers via the
762     // personality function.
763     setExceptionPointerRegister(ARM::R0);
764     setExceptionSelectorRegister(ARM::R1);
765   }
766
767   if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
768     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
769   else
770     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
771
772   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
773   // the default expansion. If we are targeting a single threaded system,
774   // then set them all for expand so we can lower them later into their
775   // non-atomic form.
776   if (TM.Options.ThreadModel == ThreadModel::Single)
777     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
778   else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
779     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
780     // to ldrex/strex loops already.
781     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
782
783     // On v8, we have particularly efficient implementations of atomic fences
784     // if they can be combined with nearby atomic loads and stores.
785     if (!Subtarget->hasV8Ops()) {
786       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
787       setInsertFencesForAtomic(true);
788     }
789   } else {
790     // If there's anything we can use as a barrier, go through custom lowering
791     // for ATOMIC_FENCE.
792     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
793                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
794
795     // Set them all for expansion, which will force libcalls.
796     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
797     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
798     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
799     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
800     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
801     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
802     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
803     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
804     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
805     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
806     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
807     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
808     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
809     // Unordered/Monotonic case.
810     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
811     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
812   }
813
814   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
815
816   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
817   if (!Subtarget->hasV6Ops()) {
818     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
819     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
820   }
821   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
822
823   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
824       !Subtarget->isThumb1Only()) {
825     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
826     // iff target supports vfp2.
827     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
828     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
829   }
830
831   // We want to custom lower some of our intrinsics.
832   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
833   if (Subtarget->isTargetDarwin()) {
834     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
835     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
836     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
837   }
838
839   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
840   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
841   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
842   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
843   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
844   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
845   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
846   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
847   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
848
849   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
850   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
851   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
852   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
853   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
854
855   // We don't support sin/cos/fmod/copysign/pow
856   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
857   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
858   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
859   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
860   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
861   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
862   setOperationAction(ISD::FREM,      MVT::f64, Expand);
863   setOperationAction(ISD::FREM,      MVT::f32, Expand);
864   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
865       !Subtarget->isThumb1Only()) {
866     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
867     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
868   }
869   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
870   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
871
872   if (!Subtarget->hasVFP4()) {
873     setOperationAction(ISD::FMA, MVT::f64, Expand);
874     setOperationAction(ISD::FMA, MVT::f32, Expand);
875   }
876
877   // Various VFP goodness
878   if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
879     // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
880     if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
881       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
882       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
883     }
884
885     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
886     if (!Subtarget->hasFP16()) {
887       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
888       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
889     }
890   }
891
892   // Combine sin / cos into one node or libcall if possible.
893   if (Subtarget->hasSinCos()) {
894     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
895     setLibcallName(RTLIB::SINCOS_F64, "sincos");
896     if (Subtarget->getTargetTriple().isiOS()) {
897       // For iOS, we don't want to the normal expansion of a libcall to
898       // sincos. We want to issue a libcall to __sincos_stret.
899       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
900       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
901     }
902   }
903
904   // FP-ARMv8 implements a lot of rounding-like FP operations.
905   if (Subtarget->hasFPARMv8()) {
906     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
907     setOperationAction(ISD::FCEIL, MVT::f32, Legal);
908     setOperationAction(ISD::FROUND, MVT::f32, Legal);
909     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
910     setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
911     setOperationAction(ISD::FRINT, MVT::f32, Legal);
912     if (!Subtarget->isFPOnlySP()) {
913       setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
914       setOperationAction(ISD::FCEIL, MVT::f64, Legal);
915       setOperationAction(ISD::FROUND, MVT::f64, Legal);
916       setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
917       setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
918       setOperationAction(ISD::FRINT, MVT::f64, Legal);
919     }
920   }
921   // We have target-specific dag combine patterns for the following nodes:
922   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
923   setTargetDAGCombine(ISD::ADD);
924   setTargetDAGCombine(ISD::SUB);
925   setTargetDAGCombine(ISD::MUL);
926   setTargetDAGCombine(ISD::AND);
927   setTargetDAGCombine(ISD::OR);
928   setTargetDAGCombine(ISD::XOR);
929
930   if (Subtarget->hasV6Ops())
931     setTargetDAGCombine(ISD::SRL);
932
933   setStackPointerRegisterToSaveRestore(ARM::SP);
934
935   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
936       !Subtarget->hasVFP2())
937     setSchedulingPreference(Sched::RegPressure);
938   else
939     setSchedulingPreference(Sched::Hybrid);
940
941   //// temporary - rewrite interface to use type
942   MaxStoresPerMemset = 8;
943   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
944   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
945   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
946   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
947   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
948
949   // On ARM arguments smaller than 4 bytes are extended, so all arguments
950   // are at least 4 bytes aligned.
951   setMinStackArgumentAlignment(4);
952
953   // Prefer likely predicted branches to selects on out-of-order cores.
954   PredictableSelectIsExpensive = Subtarget->isLikeA9();
955
956   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
957 }
958
959 // FIXME: It might make sense to define the representative register class as the
960 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
961 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
962 // SPR's representative would be DPR_VFP2. This should work well if register
963 // pressure tracking were modified such that a register use would increment the
964 // pressure of the register class's representative and all of it's super
965 // classes' representatives transitively. We have not implemented this because
966 // of the difficulty prior to coalescing of modeling operand register classes
967 // due to the common occurrence of cross class copies and subregister insertions
968 // and extractions.
969 std::pair<const TargetRegisterClass *, uint8_t>
970 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
971                                            MVT VT) const {
972   const TargetRegisterClass *RRC = nullptr;
973   uint8_t Cost = 1;
974   switch (VT.SimpleTy) {
975   default:
976     return TargetLowering::findRepresentativeClass(TRI, VT);
977   // Use DPR as representative register class for all floating point
978   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
979   // the cost is 1 for both f32 and f64.
980   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
981   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
982     RRC = &ARM::DPRRegClass;
983     // When NEON is used for SP, only half of the register file is available
984     // because operations that define both SP and DP results will be constrained
985     // to the VFP2 class (D0-D15). We currently model this constraint prior to
986     // coalescing by double-counting the SP regs. See the FIXME above.
987     if (Subtarget->useNEONForSinglePrecisionFP())
988       Cost = 2;
989     break;
990   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
991   case MVT::v4f32: case MVT::v2f64:
992     RRC = &ARM::DPRRegClass;
993     Cost = 2;
994     break;
995   case MVT::v4i64:
996     RRC = &ARM::DPRRegClass;
997     Cost = 4;
998     break;
999   case MVT::v8i64:
1000     RRC = &ARM::DPRRegClass;
1001     Cost = 8;
1002     break;
1003   }
1004   return std::make_pair(RRC, Cost);
1005 }
1006
1007 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1008   switch ((ARMISD::NodeType)Opcode) {
1009   case ARMISD::FIRST_NUMBER:  break;
1010   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1011   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1012   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1013   case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1014   case ARMISD::CALL:          return "ARMISD::CALL";
1015   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1016   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1017   case ARMISD::tCALL:         return "ARMISD::tCALL";
1018   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1019   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1020   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1021   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1022   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1023   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1024   case ARMISD::CMP:           return "ARMISD::CMP";
1025   case ARMISD::CMN:           return "ARMISD::CMN";
1026   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1027   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1028   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1029   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1030   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1031
1032   case ARMISD::CMOV:          return "ARMISD::CMOV";
1033
1034   case ARMISD::RBIT:          return "ARMISD::RBIT";
1035
1036   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1037   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1038   case ARMISD::RRX:           return "ARMISD::RRX";
1039
1040   case ARMISD::ADDC:          return "ARMISD::ADDC";
1041   case ARMISD::ADDE:          return "ARMISD::ADDE";
1042   case ARMISD::SUBC:          return "ARMISD::SUBC";
1043   case ARMISD::SUBE:          return "ARMISD::SUBE";
1044
1045   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1046   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1047
1048   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1049   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
1050
1051   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1052
1053   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1054
1055   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1056
1057   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1058
1059   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1060
1061   case ARMISD::WIN__CHKSTK:   return "ARMISD:::WIN__CHKSTK";
1062
1063   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1064   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1065   case ARMISD::VCGE:          return "ARMISD::VCGE";
1066   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1067   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1068   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1069   case ARMISD::VCGT:          return "ARMISD::VCGT";
1070   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1071   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1072   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1073   case ARMISD::VTST:          return "ARMISD::VTST";
1074
1075   case ARMISD::VSHL:          return "ARMISD::VSHL";
1076   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1077   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1078   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1079   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1080   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1081   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1082   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1083   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1084   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1085   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1086   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1087   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1088   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1089   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1090   case ARMISD::VSLI:          return "ARMISD::VSLI";
1091   case ARMISD::VSRI:          return "ARMISD::VSRI";
1092   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1093   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1094   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1095   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1096   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1097   case ARMISD::VDUP:          return "ARMISD::VDUP";
1098   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1099   case ARMISD::VEXT:          return "ARMISD::VEXT";
1100   case ARMISD::VREV64:        return "ARMISD::VREV64";
1101   case ARMISD::VREV32:        return "ARMISD::VREV32";
1102   case ARMISD::VREV16:        return "ARMISD::VREV16";
1103   case ARMISD::VZIP:          return "ARMISD::VZIP";
1104   case ARMISD::VUZP:          return "ARMISD::VUZP";
1105   case ARMISD::VTRN:          return "ARMISD::VTRN";
1106   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1107   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1108   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1109   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1110   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1111   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1112   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1113   case ARMISD::FMAX:          return "ARMISD::FMAX";
1114   case ARMISD::FMIN:          return "ARMISD::FMIN";
1115   case ARMISD::VMAXNM:        return "ARMISD::VMAX";
1116   case ARMISD::VMINNM:        return "ARMISD::VMIN";
1117   case ARMISD::BFI:           return "ARMISD::BFI";
1118   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1119   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1120   case ARMISD::VBSL:          return "ARMISD::VBSL";
1121   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1122   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1123   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1124   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1125   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1126   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1127   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1128   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1129   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1130   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1131   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1132   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1133   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1134   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1135   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1136   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1137   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1138   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1139   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1140   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1141   }
1142   return nullptr;
1143 }
1144
1145 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1146   if (!VT.isVector()) return getPointerTy();
1147   return VT.changeVectorElementTypeToInteger();
1148 }
1149
1150 /// getRegClassFor - Return the register class that should be used for the
1151 /// specified value type.
1152 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1153   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1154   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1155   // load / store 4 to 8 consecutive D registers.
1156   if (Subtarget->hasNEON()) {
1157     if (VT == MVT::v4i64)
1158       return &ARM::QQPRRegClass;
1159     if (VT == MVT::v8i64)
1160       return &ARM::QQQQPRRegClass;
1161   }
1162   return TargetLowering::getRegClassFor(VT);
1163 }
1164
1165 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1166 // source/dest is aligned and the copy size is large enough. We therefore want
1167 // to align such objects passed to memory intrinsics.
1168 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1169                                                unsigned &PrefAlign) const {
1170   if (!isa<MemIntrinsic>(CI))
1171     return false;
1172   MinSize = 8;
1173   // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1174   // cycle faster than 4-byte aligned LDM.
1175   PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1176   return true;
1177 }
1178
1179 // Create a fast isel object.
1180 FastISel *
1181 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1182                                   const TargetLibraryInfo *libInfo) const {
1183   return ARM::createFastISel(funcInfo, libInfo);
1184 }
1185
1186 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1187   unsigned NumVals = N->getNumValues();
1188   if (!NumVals)
1189     return Sched::RegPressure;
1190
1191   for (unsigned i = 0; i != NumVals; ++i) {
1192     EVT VT = N->getValueType(i);
1193     if (VT == MVT::Glue || VT == MVT::Other)
1194       continue;
1195     if (VT.isFloatingPoint() || VT.isVector())
1196       return Sched::ILP;
1197   }
1198
1199   if (!N->isMachineOpcode())
1200     return Sched::RegPressure;
1201
1202   // Load are scheduled for latency even if there instruction itinerary
1203   // is not available.
1204   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1205   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1206
1207   if (MCID.getNumDefs() == 0)
1208     return Sched::RegPressure;
1209   if (!Itins->isEmpty() &&
1210       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1211     return Sched::ILP;
1212
1213   return Sched::RegPressure;
1214 }
1215
1216 //===----------------------------------------------------------------------===//
1217 // Lowering Code
1218 //===----------------------------------------------------------------------===//
1219
1220 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1221 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1222   switch (CC) {
1223   default: llvm_unreachable("Unknown condition code!");
1224   case ISD::SETNE:  return ARMCC::NE;
1225   case ISD::SETEQ:  return ARMCC::EQ;
1226   case ISD::SETGT:  return ARMCC::GT;
1227   case ISD::SETGE:  return ARMCC::GE;
1228   case ISD::SETLT:  return ARMCC::LT;
1229   case ISD::SETLE:  return ARMCC::LE;
1230   case ISD::SETUGT: return ARMCC::HI;
1231   case ISD::SETUGE: return ARMCC::HS;
1232   case ISD::SETULT: return ARMCC::LO;
1233   case ISD::SETULE: return ARMCC::LS;
1234   }
1235 }
1236
1237 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1238 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1239                         ARMCC::CondCodes &CondCode2) {
1240   CondCode2 = ARMCC::AL;
1241   switch (CC) {
1242   default: llvm_unreachable("Unknown FP condition!");
1243   case ISD::SETEQ:
1244   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1245   case ISD::SETGT:
1246   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1247   case ISD::SETGE:
1248   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1249   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1250   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1251   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1252   case ISD::SETO:   CondCode = ARMCC::VC; break;
1253   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1254   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1255   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1256   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1257   case ISD::SETLT:
1258   case ISD::SETULT: CondCode = ARMCC::LT; break;
1259   case ISD::SETLE:
1260   case ISD::SETULE: CondCode = ARMCC::LE; break;
1261   case ISD::SETNE:
1262   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1263   }
1264 }
1265
1266 //===----------------------------------------------------------------------===//
1267 //                      Calling Convention Implementation
1268 //===----------------------------------------------------------------------===//
1269
1270 #include "ARMGenCallingConv.inc"
1271
1272 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1273 /// account presence of floating point hardware and calling convention
1274 /// limitations, such as support for variadic functions.
1275 CallingConv::ID
1276 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1277                                            bool isVarArg) const {
1278   switch (CC) {
1279   default:
1280     llvm_unreachable("Unsupported calling convention");
1281   case CallingConv::ARM_AAPCS:
1282   case CallingConv::ARM_APCS:
1283   case CallingConv::GHC:
1284     return CC;
1285   case CallingConv::ARM_AAPCS_VFP:
1286     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1287   case CallingConv::C:
1288     if (!Subtarget->isAAPCS_ABI())
1289       return CallingConv::ARM_APCS;
1290     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1291              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1292              !isVarArg)
1293       return CallingConv::ARM_AAPCS_VFP;
1294     else
1295       return CallingConv::ARM_AAPCS;
1296   case CallingConv::Fast:
1297     if (!Subtarget->isAAPCS_ABI()) {
1298       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1299         return CallingConv::Fast;
1300       return CallingConv::ARM_APCS;
1301     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1302       return CallingConv::ARM_AAPCS_VFP;
1303     else
1304       return CallingConv::ARM_AAPCS;
1305   }
1306 }
1307
1308 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1309 /// CallingConvention.
1310 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1311                                                  bool Return,
1312                                                  bool isVarArg) const {
1313   switch (getEffectiveCallingConv(CC, isVarArg)) {
1314   default:
1315     llvm_unreachable("Unsupported calling convention");
1316   case CallingConv::ARM_APCS:
1317     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1318   case CallingConv::ARM_AAPCS:
1319     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1320   case CallingConv::ARM_AAPCS_VFP:
1321     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1322   case CallingConv::Fast:
1323     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1324   case CallingConv::GHC:
1325     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1326   }
1327 }
1328
1329 /// LowerCallResult - Lower the result values of a call into the
1330 /// appropriate copies out of appropriate physical registers.
1331 SDValue
1332 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1333                                    CallingConv::ID CallConv, bool isVarArg,
1334                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1335                                    SDLoc dl, SelectionDAG &DAG,
1336                                    SmallVectorImpl<SDValue> &InVals,
1337                                    bool isThisReturn, SDValue ThisVal) const {
1338
1339   // Assign locations to each value returned by this call.
1340   SmallVector<CCValAssign, 16> RVLocs;
1341   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1342                     *DAG.getContext(), Call);
1343   CCInfo.AnalyzeCallResult(Ins,
1344                            CCAssignFnForNode(CallConv, /* Return*/ true,
1345                                              isVarArg));
1346
1347   // Copy all of the result registers out of their specified physreg.
1348   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1349     CCValAssign VA = RVLocs[i];
1350
1351     // Pass 'this' value directly from the argument to return value, to avoid
1352     // reg unit interference
1353     if (i == 0 && isThisReturn) {
1354       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1355              "unexpected return calling convention register assignment");
1356       InVals.push_back(ThisVal);
1357       continue;
1358     }
1359
1360     SDValue Val;
1361     if (VA.needsCustom()) {
1362       // Handle f64 or half of a v2f64.
1363       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1364                                       InFlag);
1365       Chain = Lo.getValue(1);
1366       InFlag = Lo.getValue(2);
1367       VA = RVLocs[++i]; // skip ahead to next loc
1368       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1369                                       InFlag);
1370       Chain = Hi.getValue(1);
1371       InFlag = Hi.getValue(2);
1372       if (!Subtarget->isLittle())
1373         std::swap (Lo, Hi);
1374       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1375
1376       if (VA.getLocVT() == MVT::v2f64) {
1377         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1378         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1379                           DAG.getConstant(0, dl, MVT::i32));
1380
1381         VA = RVLocs[++i]; // skip ahead to next loc
1382         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1383         Chain = Lo.getValue(1);
1384         InFlag = Lo.getValue(2);
1385         VA = RVLocs[++i]; // skip ahead to next loc
1386         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1387         Chain = Hi.getValue(1);
1388         InFlag = Hi.getValue(2);
1389         if (!Subtarget->isLittle())
1390           std::swap (Lo, Hi);
1391         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1392         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1393                           DAG.getConstant(1, dl, MVT::i32));
1394       }
1395     } else {
1396       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1397                                InFlag);
1398       Chain = Val.getValue(1);
1399       InFlag = Val.getValue(2);
1400     }
1401
1402     switch (VA.getLocInfo()) {
1403     default: llvm_unreachable("Unknown loc info!");
1404     case CCValAssign::Full: break;
1405     case CCValAssign::BCvt:
1406       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1407       break;
1408     }
1409
1410     InVals.push_back(Val);
1411   }
1412
1413   return Chain;
1414 }
1415
1416 /// LowerMemOpCallTo - Store the argument to the stack.
1417 SDValue
1418 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1419                                     SDValue StackPtr, SDValue Arg,
1420                                     SDLoc dl, SelectionDAG &DAG,
1421                                     const CCValAssign &VA,
1422                                     ISD::ArgFlagsTy Flags) const {
1423   unsigned LocMemOffset = VA.getLocMemOffset();
1424   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1425   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1426   return DAG.getStore(Chain, dl, Arg, PtrOff,
1427                       MachinePointerInfo::getStack(LocMemOffset),
1428                       false, false, 0);
1429 }
1430
1431 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1432                                          SDValue Chain, SDValue &Arg,
1433                                          RegsToPassVector &RegsToPass,
1434                                          CCValAssign &VA, CCValAssign &NextVA,
1435                                          SDValue &StackPtr,
1436                                          SmallVectorImpl<SDValue> &MemOpChains,
1437                                          ISD::ArgFlagsTy Flags) const {
1438
1439   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1440                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1441   unsigned id = Subtarget->isLittle() ? 0 : 1;
1442   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1443
1444   if (NextVA.isRegLoc())
1445     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1446   else {
1447     assert(NextVA.isMemLoc());
1448     if (!StackPtr.getNode())
1449       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1450
1451     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1452                                            dl, DAG, NextVA,
1453                                            Flags));
1454   }
1455 }
1456
1457 /// LowerCall - Lowering a call into a callseq_start <-
1458 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1459 /// nodes.
1460 SDValue
1461 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1462                              SmallVectorImpl<SDValue> &InVals) const {
1463   SelectionDAG &DAG                     = CLI.DAG;
1464   SDLoc &dl                             = CLI.DL;
1465   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1466   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1467   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1468   SDValue Chain                         = CLI.Chain;
1469   SDValue Callee                        = CLI.Callee;
1470   bool &isTailCall                      = CLI.IsTailCall;
1471   CallingConv::ID CallConv              = CLI.CallConv;
1472   bool doesNotRet                       = CLI.DoesNotReturn;
1473   bool isVarArg                         = CLI.IsVarArg;
1474
1475   MachineFunction &MF = DAG.getMachineFunction();
1476   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1477   bool isThisReturn   = false;
1478   bool isSibCall      = false;
1479
1480   // Disable tail calls if they're not supported.
1481   if (!Subtarget->supportsTailCall() || MF.getTarget().Options.DisableTailCalls)
1482     isTailCall = false;
1483
1484   if (isTailCall) {
1485     // Check if it's really possible to do a tail call.
1486     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1487                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1488                                                    Outs, OutVals, Ins, DAG);
1489     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1490       report_fatal_error("failed to perform tail call elimination on a call "
1491                          "site marked musttail");
1492     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1493     // detected sibcalls.
1494     if (isTailCall) {
1495       ++NumTailCalls;
1496       isSibCall = true;
1497     }
1498   }
1499
1500   // Analyze operands of the call, assigning locations to each operand.
1501   SmallVector<CCValAssign, 16> ArgLocs;
1502   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1503                     *DAG.getContext(), Call);
1504   CCInfo.AnalyzeCallOperands(Outs,
1505                              CCAssignFnForNode(CallConv, /* Return*/ false,
1506                                                isVarArg));
1507
1508   // Get a count of how many bytes are to be pushed on the stack.
1509   unsigned NumBytes = CCInfo.getNextStackOffset();
1510
1511   // For tail calls, memory operands are available in our caller's stack.
1512   if (isSibCall)
1513     NumBytes = 0;
1514
1515   // Adjust the stack pointer for the new arguments...
1516   // These operations are automatically eliminated by the prolog/epilog pass
1517   if (!isSibCall)
1518     Chain = DAG.getCALLSEQ_START(Chain,
1519                                  DAG.getIntPtrConstant(NumBytes, dl, true), dl);
1520
1521   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1522
1523   RegsToPassVector RegsToPass;
1524   SmallVector<SDValue, 8> MemOpChains;
1525
1526   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1527   // of tail call optimization, arguments are handled later.
1528   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1529        i != e;
1530        ++i, ++realArgIdx) {
1531     CCValAssign &VA = ArgLocs[i];
1532     SDValue Arg = OutVals[realArgIdx];
1533     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1534     bool isByVal = Flags.isByVal();
1535
1536     // Promote the value if needed.
1537     switch (VA.getLocInfo()) {
1538     default: llvm_unreachable("Unknown loc info!");
1539     case CCValAssign::Full: break;
1540     case CCValAssign::SExt:
1541       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1542       break;
1543     case CCValAssign::ZExt:
1544       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1545       break;
1546     case CCValAssign::AExt:
1547       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1548       break;
1549     case CCValAssign::BCvt:
1550       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1551       break;
1552     }
1553
1554     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1555     if (VA.needsCustom()) {
1556       if (VA.getLocVT() == MVT::v2f64) {
1557         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1558                                   DAG.getConstant(0, dl, MVT::i32));
1559         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1560                                   DAG.getConstant(1, dl, MVT::i32));
1561
1562         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1563                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1564
1565         VA = ArgLocs[++i]; // skip ahead to next loc
1566         if (VA.isRegLoc()) {
1567           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1568                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1569         } else {
1570           assert(VA.isMemLoc());
1571
1572           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1573                                                  dl, DAG, VA, Flags));
1574         }
1575       } else {
1576         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1577                          StackPtr, MemOpChains, Flags);
1578       }
1579     } else if (VA.isRegLoc()) {
1580       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1581         assert(VA.getLocVT() == MVT::i32 &&
1582                "unexpected calling convention register assignment");
1583         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1584                "unexpected use of 'returned'");
1585         isThisReturn = true;
1586       }
1587       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1588     } else if (isByVal) {
1589       assert(VA.isMemLoc());
1590       unsigned offset = 0;
1591
1592       // True if this byval aggregate will be split between registers
1593       // and memory.
1594       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1595       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1596
1597       if (CurByValIdx < ByValArgsCount) {
1598
1599         unsigned RegBegin, RegEnd;
1600         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1601
1602         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1603         unsigned int i, j;
1604         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1605           SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1606           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1607           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1608                                      MachinePointerInfo(),
1609                                      false, false, false,
1610                                      DAG.InferPtrAlignment(AddArg));
1611           MemOpChains.push_back(Load.getValue(1));
1612           RegsToPass.push_back(std::make_pair(j, Load));
1613         }
1614
1615         // If parameter size outsides register area, "offset" value
1616         // helps us to calculate stack slot for remained part properly.
1617         offset = RegEnd - RegBegin;
1618
1619         CCInfo.nextInRegsParam();
1620       }
1621
1622       if (Flags.getByValSize() > 4*offset) {
1623         unsigned LocMemOffset = VA.getLocMemOffset();
1624         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1625         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1626                                   StkPtrOff);
1627         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1628         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1629         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1630                                            MVT::i32);
1631         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1632                                             MVT::i32);
1633
1634         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1635         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1636         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1637                                           Ops));
1638       }
1639     } else if (!isSibCall) {
1640       assert(VA.isMemLoc());
1641
1642       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1643                                              dl, DAG, VA, Flags));
1644     }
1645   }
1646
1647   if (!MemOpChains.empty())
1648     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1649
1650   // Build a sequence of copy-to-reg nodes chained together with token chain
1651   // and flag operands which copy the outgoing args into the appropriate regs.
1652   SDValue InFlag;
1653   // Tail call byval lowering might overwrite argument registers so in case of
1654   // tail call optimization the copies to registers are lowered later.
1655   if (!isTailCall)
1656     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1657       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1658                                RegsToPass[i].second, InFlag);
1659       InFlag = Chain.getValue(1);
1660     }
1661
1662   // For tail calls lower the arguments to the 'real' stack slot.
1663   if (isTailCall) {
1664     // Force all the incoming stack arguments to be loaded from the stack
1665     // before any new outgoing arguments are stored to the stack, because the
1666     // outgoing stack slots may alias the incoming argument stack slots, and
1667     // the alias isn't otherwise explicit. This is slightly more conservative
1668     // than necessary, because it means that each store effectively depends
1669     // on every argument instead of just those arguments it would clobber.
1670
1671     // Do not flag preceding copytoreg stuff together with the following stuff.
1672     InFlag = SDValue();
1673     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1674       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1675                                RegsToPass[i].second, InFlag);
1676       InFlag = Chain.getValue(1);
1677     }
1678     InFlag = SDValue();
1679   }
1680
1681   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1682   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1683   // node so that legalize doesn't hack it.
1684   bool isDirect = false;
1685   bool isARMFunc = false;
1686   bool isLocalARMFunc = false;
1687   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1688
1689   if (EnableARMLongCalls) {
1690     assert((Subtarget->isTargetWindows() ||
1691             getTargetMachine().getRelocationModel() == Reloc::Static) &&
1692            "long-calls with non-static relocation model!");
1693     // Handle a global address or an external symbol. If it's not one of
1694     // those, the target's already in a register, so we don't need to do
1695     // anything extra.
1696     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1697       const GlobalValue *GV = G->getGlobal();
1698       // Create a constant pool entry for the callee address
1699       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1700       ARMConstantPoolValue *CPV =
1701         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1702
1703       // Get the address of the callee into a register
1704       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1705       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1706       Callee = DAG.getLoad(getPointerTy(), dl,
1707                            DAG.getEntryNode(), CPAddr,
1708                            MachinePointerInfo::getConstantPool(),
1709                            false, false, false, 0);
1710     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1711       const char *Sym = S->getSymbol();
1712
1713       // Create a constant pool entry for the callee address
1714       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1715       ARMConstantPoolValue *CPV =
1716         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1717                                       ARMPCLabelIndex, 0);
1718       // Get the address of the callee into a register
1719       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1720       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1721       Callee = DAG.getLoad(getPointerTy(), dl,
1722                            DAG.getEntryNode(), CPAddr,
1723                            MachinePointerInfo::getConstantPool(),
1724                            false, false, false, 0);
1725     }
1726   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1727     const GlobalValue *GV = G->getGlobal();
1728     isDirect = true;
1729     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1730     bool isStub = (isExt && Subtarget->isTargetMachO()) &&
1731                    getTargetMachine().getRelocationModel() != Reloc::Static;
1732     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1733     // ARM call to a local ARM function is predicable.
1734     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1735     // tBX takes a register source operand.
1736     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1737       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1738       Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1739                            DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
1740                                                       0, ARMII::MO_NONLAZY));
1741       Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
1742                            MachinePointerInfo::getGOT(), false, false, true, 0);
1743     } else if (Subtarget->isTargetCOFF()) {
1744       assert(Subtarget->isTargetWindows() &&
1745              "Windows is the only supported COFF target");
1746       unsigned TargetFlags = GV->hasDLLImportStorageClass()
1747                                  ? ARMII::MO_DLLIMPORT
1748                                  : ARMII::MO_NO_FLAG;
1749       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), /*Offset=*/0,
1750                                           TargetFlags);
1751       if (GV->hasDLLImportStorageClass())
1752         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
1753                              DAG.getNode(ARMISD::Wrapper, dl, getPointerTy(),
1754                                          Callee), MachinePointerInfo::getGOT(),
1755                              false, false, false, 0);
1756     } else {
1757       // On ELF targets for PIC code, direct calls should go through the PLT
1758       unsigned OpFlags = 0;
1759       if (Subtarget->isTargetELF() &&
1760           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1761         OpFlags = ARMII::MO_PLT;
1762       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1763     }
1764   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1765     isDirect = true;
1766     bool isStub = Subtarget->isTargetMachO() &&
1767                   getTargetMachine().getRelocationModel() != Reloc::Static;
1768     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1769     // tBX takes a register source operand.
1770     const char *Sym = S->getSymbol();
1771     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1772       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1773       ARMConstantPoolValue *CPV =
1774         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1775                                       ARMPCLabelIndex, 4);
1776       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1777       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1778       Callee = DAG.getLoad(getPointerTy(), dl,
1779                            DAG.getEntryNode(), CPAddr,
1780                            MachinePointerInfo::getConstantPool(),
1781                            false, false, false, 0);
1782       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
1783       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1784                            getPointerTy(), Callee, PICLabel);
1785     } else {
1786       unsigned OpFlags = 0;
1787       // On ELF targets for PIC code, direct calls should go through the PLT
1788       if (Subtarget->isTargetELF() &&
1789                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1790         OpFlags = ARMII::MO_PLT;
1791       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1792     }
1793   }
1794
1795   // FIXME: handle tail calls differently.
1796   unsigned CallOpc;
1797   bool HasMinSizeAttr = MF.getFunction()->hasFnAttribute(Attribute::MinSize);
1798   if (Subtarget->isThumb()) {
1799     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1800       CallOpc = ARMISD::CALL_NOLINK;
1801     else
1802       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1803   } else {
1804     if (!isDirect && !Subtarget->hasV5TOps())
1805       CallOpc = ARMISD::CALL_NOLINK;
1806     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1807                // Emit regular call when code size is the priority
1808                !HasMinSizeAttr)
1809       // "mov lr, pc; b _foo" to avoid confusing the RSP
1810       CallOpc = ARMISD::CALL_NOLINK;
1811     else
1812       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1813   }
1814
1815   std::vector<SDValue> Ops;
1816   Ops.push_back(Chain);
1817   Ops.push_back(Callee);
1818
1819   // Add argument registers to the end of the list so that they are known live
1820   // into the call.
1821   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1822     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1823                                   RegsToPass[i].second.getValueType()));
1824
1825   // Add a register mask operand representing the call-preserved registers.
1826   if (!isTailCall) {
1827     const uint32_t *Mask;
1828     const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
1829     if (isThisReturn) {
1830       // For 'this' returns, use the R0-preserving mask if applicable
1831       Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
1832       if (!Mask) {
1833         // Set isThisReturn to false if the calling convention is not one that
1834         // allows 'returned' to be modeled in this way, so LowerCallResult does
1835         // not try to pass 'this' straight through
1836         isThisReturn = false;
1837         Mask = ARI->getCallPreservedMask(MF, CallConv);
1838       }
1839     } else
1840       Mask = ARI->getCallPreservedMask(MF, CallConv);
1841
1842     assert(Mask && "Missing call preserved mask for calling convention");
1843     Ops.push_back(DAG.getRegisterMask(Mask));
1844   }
1845
1846   if (InFlag.getNode())
1847     Ops.push_back(InFlag);
1848
1849   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1850   if (isTailCall) {
1851     MF.getFrameInfo()->setHasTailCall();
1852     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1853   }
1854
1855   // Returns a chain and a flag for retval copy to use.
1856   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1857   InFlag = Chain.getValue(1);
1858
1859   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
1860                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
1861   if (!Ins.empty())
1862     InFlag = Chain.getValue(1);
1863
1864   // Handle result values, copying them out of physregs into vregs that we
1865   // return.
1866   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1867                          InVals, isThisReturn,
1868                          isThisReturn ? OutVals[0] : SDValue());
1869 }
1870
1871 /// HandleByVal - Every parameter *after* a byval parameter is passed
1872 /// on the stack.  Remember the next parameter register to allocate,
1873 /// and then confiscate the rest of the parameter registers to insure
1874 /// this.
1875 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
1876                                     unsigned Align) const {
1877   assert((State->getCallOrPrologue() == Prologue ||
1878           State->getCallOrPrologue() == Call) &&
1879          "unhandled ParmContext");
1880
1881   // Byval (as with any stack) slots are always at least 4 byte aligned.
1882   Align = std::max(Align, 4U);
1883
1884   unsigned Reg = State->AllocateReg(GPRArgRegs);
1885   if (!Reg)
1886     return;
1887
1888   unsigned AlignInRegs = Align / 4;
1889   unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
1890   for (unsigned i = 0; i < Waste; ++i)
1891     Reg = State->AllocateReg(GPRArgRegs);
1892
1893   if (!Reg)
1894     return;
1895
1896   unsigned Excess = 4 * (ARM::R4 - Reg);
1897
1898   // Special case when NSAA != SP and parameter size greater than size of
1899   // all remained GPR regs. In that case we can't split parameter, we must
1900   // send it to stack. We also must set NCRN to R4, so waste all
1901   // remained registers.
1902   const unsigned NSAAOffset = State->getNextStackOffset();
1903   if (NSAAOffset != 0 && Size > Excess) {
1904     while (State->AllocateReg(GPRArgRegs))
1905       ;
1906     return;
1907   }
1908
1909   // First register for byval parameter is the first register that wasn't
1910   // allocated before this method call, so it would be "reg".
1911   // If parameter is small enough to be saved in range [reg, r4), then
1912   // the end (first after last) register would be reg + param-size-in-regs,
1913   // else parameter would be splitted between registers and stack,
1914   // end register would be r4 in this case.
1915   unsigned ByValRegBegin = Reg;
1916   unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
1917   State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1918   // Note, first register is allocated in the beginning of function already,
1919   // allocate remained amount of registers we need.
1920   for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
1921     State->AllocateReg(GPRArgRegs);
1922   // A byval parameter that is split between registers and memory needs its
1923   // size truncated here.
1924   // In the case where the entire structure fits in registers, we set the
1925   // size in memory to zero.
1926   Size = std::max<int>(Size - Excess, 0);
1927 }
1928
1929
1930 /// MatchingStackOffset - Return true if the given stack call argument is
1931 /// already available in the same position (relatively) of the caller's
1932 /// incoming argument stack.
1933 static
1934 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1935                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1936                          const TargetInstrInfo *TII) {
1937   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1938   int FI = INT_MAX;
1939   if (Arg.getOpcode() == ISD::CopyFromReg) {
1940     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1941     if (!TargetRegisterInfo::isVirtualRegister(VR))
1942       return false;
1943     MachineInstr *Def = MRI->getVRegDef(VR);
1944     if (!Def)
1945       return false;
1946     if (!Flags.isByVal()) {
1947       if (!TII->isLoadFromStackSlot(Def, FI))
1948         return false;
1949     } else {
1950       return false;
1951     }
1952   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1953     if (Flags.isByVal())
1954       // ByVal argument is passed in as a pointer but it's now being
1955       // dereferenced. e.g.
1956       // define @foo(%struct.X* %A) {
1957       //   tail call @bar(%struct.X* byval %A)
1958       // }
1959       return false;
1960     SDValue Ptr = Ld->getBasePtr();
1961     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1962     if (!FINode)
1963       return false;
1964     FI = FINode->getIndex();
1965   } else
1966     return false;
1967
1968   assert(FI != INT_MAX);
1969   if (!MFI->isFixedObjectIndex(FI))
1970     return false;
1971   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1972 }
1973
1974 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1975 /// for tail call optimization. Targets which want to do tail call
1976 /// optimization should implement this function.
1977 bool
1978 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1979                                                      CallingConv::ID CalleeCC,
1980                                                      bool isVarArg,
1981                                                      bool isCalleeStructRet,
1982                                                      bool isCallerStructRet,
1983                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1984                                     const SmallVectorImpl<SDValue> &OutVals,
1985                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1986                                                      SelectionDAG& DAG) const {
1987   const Function *CallerF = DAG.getMachineFunction().getFunction();
1988   CallingConv::ID CallerCC = CallerF->getCallingConv();
1989   bool CCMatch = CallerCC == CalleeCC;
1990
1991   // Look for obvious safe cases to perform tail call optimization that do not
1992   // require ABI changes. This is what gcc calls sibcall.
1993
1994   // Do not sibcall optimize vararg calls unless the call site is not passing
1995   // any arguments.
1996   if (isVarArg && !Outs.empty())
1997     return false;
1998
1999   // Exception-handling functions need a special set of instructions to indicate
2000   // a return to the hardware. Tail-calling another function would probably
2001   // break this.
2002   if (CallerF->hasFnAttribute("interrupt"))
2003     return false;
2004
2005   // Also avoid sibcall optimization if either caller or callee uses struct
2006   // return semantics.
2007   if (isCalleeStructRet || isCallerStructRet)
2008     return false;
2009
2010   // FIXME: Completely disable sibcall for Thumb1 since ThumbRegisterInfo::
2011   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
2012   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
2013   // support in the assembler and linker to be used. This would need to be
2014   // fixed to fully support tail calls in Thumb1.
2015   //
2016   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
2017   // LR.  This means if we need to reload LR, it takes an extra instructions,
2018   // which outweighs the value of the tail call; but here we don't know yet
2019   // whether LR is going to be used.  Probably the right approach is to
2020   // generate the tail call here and turn it back into CALL/RET in
2021   // emitEpilogue if LR is used.
2022
2023   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
2024   // but we need to make sure there are enough registers; the only valid
2025   // registers are the 4 used for parameters.  We don't currently do this
2026   // case.
2027   if (Subtarget->isThumb1Only())
2028     return false;
2029
2030   // Externally-defined functions with weak linkage should not be
2031   // tail-called on ARM when the OS does not support dynamic
2032   // pre-emption of symbols, as the AAELF spec requires normal calls
2033   // to undefined weak functions to be replaced with a NOP or jump to the
2034   // next instruction. The behaviour of branch instructions in this
2035   // situation (as used for tail calls) is implementation-defined, so we
2036   // cannot rely on the linker replacing the tail call with a return.
2037   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2038     const GlobalValue *GV = G->getGlobal();
2039     const Triple TT(getTargetMachine().getTargetTriple());
2040     if (GV->hasExternalWeakLinkage() &&
2041         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2042       return false;
2043   }
2044
2045   // If the calling conventions do not match, then we'd better make sure the
2046   // results are returned in the same way as what the caller expects.
2047   if (!CCMatch) {
2048     SmallVector<CCValAssign, 16> RVLocs1;
2049     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2050                        *DAG.getContext(), Call);
2051     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2052
2053     SmallVector<CCValAssign, 16> RVLocs2;
2054     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2055                        *DAG.getContext(), Call);
2056     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2057
2058     if (RVLocs1.size() != RVLocs2.size())
2059       return false;
2060     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2061       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2062         return false;
2063       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2064         return false;
2065       if (RVLocs1[i].isRegLoc()) {
2066         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2067           return false;
2068       } else {
2069         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2070           return false;
2071       }
2072     }
2073   }
2074
2075   // If Caller's vararg or byval argument has been split between registers and
2076   // stack, do not perform tail call, since part of the argument is in caller's
2077   // local frame.
2078   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2079                                       getInfo<ARMFunctionInfo>();
2080   if (AFI_Caller->getArgRegsSaveSize())
2081     return false;
2082
2083   // If the callee takes no arguments then go on to check the results of the
2084   // call.
2085   if (!Outs.empty()) {
2086     // Check if stack adjustment is needed. For now, do not do this if any
2087     // argument is passed on the stack.
2088     SmallVector<CCValAssign, 16> ArgLocs;
2089     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2090                       *DAG.getContext(), Call);
2091     CCInfo.AnalyzeCallOperands(Outs,
2092                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2093     if (CCInfo.getNextStackOffset()) {
2094       MachineFunction &MF = DAG.getMachineFunction();
2095
2096       // Check if the arguments are already laid out in the right way as
2097       // the caller's fixed stack objects.
2098       MachineFrameInfo *MFI = MF.getFrameInfo();
2099       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2100       const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2101       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2102            i != e;
2103            ++i, ++realArgIdx) {
2104         CCValAssign &VA = ArgLocs[i];
2105         EVT RegVT = VA.getLocVT();
2106         SDValue Arg = OutVals[realArgIdx];
2107         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2108         if (VA.getLocInfo() == CCValAssign::Indirect)
2109           return false;
2110         if (VA.needsCustom()) {
2111           // f64 and vector types are split into multiple registers or
2112           // register/stack-slot combinations.  The types will not match
2113           // the registers; give up on memory f64 refs until we figure
2114           // out what to do about this.
2115           if (!VA.isRegLoc())
2116             return false;
2117           if (!ArgLocs[++i].isRegLoc())
2118             return false;
2119           if (RegVT == MVT::v2f64) {
2120             if (!ArgLocs[++i].isRegLoc())
2121               return false;
2122             if (!ArgLocs[++i].isRegLoc())
2123               return false;
2124           }
2125         } else if (!VA.isRegLoc()) {
2126           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2127                                    MFI, MRI, TII))
2128             return false;
2129         }
2130       }
2131     }
2132   }
2133
2134   return true;
2135 }
2136
2137 bool
2138 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2139                                   MachineFunction &MF, bool isVarArg,
2140                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2141                                   LLVMContext &Context) const {
2142   SmallVector<CCValAssign, 16> RVLocs;
2143   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2144   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2145                                                     isVarArg));
2146 }
2147
2148 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2149                                     SDLoc DL, SelectionDAG &DAG) {
2150   const MachineFunction &MF = DAG.getMachineFunction();
2151   const Function *F = MF.getFunction();
2152
2153   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2154
2155   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2156   // version of the "preferred return address". These offsets affect the return
2157   // instruction if this is a return from PL1 without hypervisor extensions.
2158   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2159   //    SWI:     0      "subs pc, lr, #0"
2160   //    ABORT:   +4     "subs pc, lr, #4"
2161   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2162   // UNDEF varies depending on where the exception came from ARM or Thumb
2163   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2164
2165   int64_t LROffset;
2166   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2167       IntKind == "ABORT")
2168     LROffset = 4;
2169   else if (IntKind == "SWI" || IntKind == "UNDEF")
2170     LROffset = 0;
2171   else
2172     report_fatal_error("Unsupported interrupt attribute. If present, value "
2173                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2174
2175   RetOps.insert(RetOps.begin() + 1,
2176                 DAG.getConstant(LROffset, DL, MVT::i32, false));
2177
2178   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2179 }
2180
2181 SDValue
2182 ARMTargetLowering::LowerReturn(SDValue Chain,
2183                                CallingConv::ID CallConv, bool isVarArg,
2184                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2185                                const SmallVectorImpl<SDValue> &OutVals,
2186                                SDLoc dl, SelectionDAG &DAG) const {
2187
2188   // CCValAssign - represent the assignment of the return value to a location.
2189   SmallVector<CCValAssign, 16> RVLocs;
2190
2191   // CCState - Info about the registers and stack slots.
2192   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2193                     *DAG.getContext(), Call);
2194
2195   // Analyze outgoing return values.
2196   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2197                                                isVarArg));
2198
2199   SDValue Flag;
2200   SmallVector<SDValue, 4> RetOps;
2201   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2202   bool isLittleEndian = Subtarget->isLittle();
2203
2204   MachineFunction &MF = DAG.getMachineFunction();
2205   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2206   AFI->setReturnRegsCount(RVLocs.size());
2207
2208   // Copy the result values into the output registers.
2209   for (unsigned i = 0, realRVLocIdx = 0;
2210        i != RVLocs.size();
2211        ++i, ++realRVLocIdx) {
2212     CCValAssign &VA = RVLocs[i];
2213     assert(VA.isRegLoc() && "Can only return in registers!");
2214
2215     SDValue Arg = OutVals[realRVLocIdx];
2216
2217     switch (VA.getLocInfo()) {
2218     default: llvm_unreachable("Unknown loc info!");
2219     case CCValAssign::Full: break;
2220     case CCValAssign::BCvt:
2221       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2222       break;
2223     }
2224
2225     if (VA.needsCustom()) {
2226       if (VA.getLocVT() == MVT::v2f64) {
2227         // Extract the first half and return it in two registers.
2228         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2229                                    DAG.getConstant(0, dl, MVT::i32));
2230         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2231                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2232
2233         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2234                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2235                                  Flag);
2236         Flag = Chain.getValue(1);
2237         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2238         VA = RVLocs[++i]; // skip ahead to next loc
2239         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2240                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2241                                  Flag);
2242         Flag = Chain.getValue(1);
2243         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2244         VA = RVLocs[++i]; // skip ahead to next loc
2245
2246         // Extract the 2nd half and fall through to handle it as an f64 value.
2247         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2248                           DAG.getConstant(1, dl, MVT::i32));
2249       }
2250       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2251       // available.
2252       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2253                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2254       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2255                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2256                                Flag);
2257       Flag = Chain.getValue(1);
2258       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2259       VA = RVLocs[++i]; // skip ahead to next loc
2260       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2261                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2262                                Flag);
2263     } else
2264       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2265
2266     // Guarantee that all emitted copies are
2267     // stuck together, avoiding something bad.
2268     Flag = Chain.getValue(1);
2269     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2270   }
2271
2272   // Update chain and glue.
2273   RetOps[0] = Chain;
2274   if (Flag.getNode())
2275     RetOps.push_back(Flag);
2276
2277   // CPUs which aren't M-class use a special sequence to return from
2278   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2279   // though we use "subs pc, lr, #N").
2280   //
2281   // M-class CPUs actually use a normal return sequence with a special
2282   // (hardware-provided) value in LR, so the normal code path works.
2283   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2284       !Subtarget->isMClass()) {
2285     if (Subtarget->isThumb1Only())
2286       report_fatal_error("interrupt attribute is not supported in Thumb1");
2287     return LowerInterruptReturn(RetOps, dl, DAG);
2288   }
2289
2290   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2291 }
2292
2293 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2294   if (N->getNumValues() != 1)
2295     return false;
2296   if (!N->hasNUsesOfValue(1, 0))
2297     return false;
2298
2299   SDValue TCChain = Chain;
2300   SDNode *Copy = *N->use_begin();
2301   if (Copy->getOpcode() == ISD::CopyToReg) {
2302     // If the copy has a glue operand, we conservatively assume it isn't safe to
2303     // perform a tail call.
2304     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2305       return false;
2306     TCChain = Copy->getOperand(0);
2307   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2308     SDNode *VMov = Copy;
2309     // f64 returned in a pair of GPRs.
2310     SmallPtrSet<SDNode*, 2> Copies;
2311     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2312          UI != UE; ++UI) {
2313       if (UI->getOpcode() != ISD::CopyToReg)
2314         return false;
2315       Copies.insert(*UI);
2316     }
2317     if (Copies.size() > 2)
2318       return false;
2319
2320     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2321          UI != UE; ++UI) {
2322       SDValue UseChain = UI->getOperand(0);
2323       if (Copies.count(UseChain.getNode()))
2324         // Second CopyToReg
2325         Copy = *UI;
2326       else {
2327         // We are at the top of this chain.
2328         // If the copy has a glue operand, we conservatively assume it
2329         // isn't safe to perform a tail call.
2330         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2331           return false;
2332         // First CopyToReg
2333         TCChain = UseChain;
2334       }
2335     }
2336   } else if (Copy->getOpcode() == ISD::BITCAST) {
2337     // f32 returned in a single GPR.
2338     if (!Copy->hasOneUse())
2339       return false;
2340     Copy = *Copy->use_begin();
2341     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2342       return false;
2343     // If the copy has a glue operand, we conservatively assume it isn't safe to
2344     // perform a tail call.
2345     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2346       return false;
2347     TCChain = Copy->getOperand(0);
2348   } else {
2349     return false;
2350   }
2351
2352   bool HasRet = false;
2353   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2354        UI != UE; ++UI) {
2355     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2356         UI->getOpcode() != ARMISD::INTRET_FLAG)
2357       return false;
2358     HasRet = true;
2359   }
2360
2361   if (!HasRet)
2362     return false;
2363
2364   Chain = TCChain;
2365   return true;
2366 }
2367
2368 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2369   if (!Subtarget->supportsTailCall())
2370     return false;
2371
2372   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2373     return false;
2374
2375   return !Subtarget->isThumb1Only();
2376 }
2377
2378 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2379 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2380 // one of the above mentioned nodes. It has to be wrapped because otherwise
2381 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2382 // be used to form addressing mode. These wrapped nodes will be selected
2383 // into MOVi.
2384 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2385   EVT PtrVT = Op.getValueType();
2386   // FIXME there is no actual debug info here
2387   SDLoc dl(Op);
2388   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2389   SDValue Res;
2390   if (CP->isMachineConstantPoolEntry())
2391     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2392                                     CP->getAlignment());
2393   else
2394     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2395                                     CP->getAlignment());
2396   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2397 }
2398
2399 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2400   return MachineJumpTableInfo::EK_Inline;
2401 }
2402
2403 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2404                                              SelectionDAG &DAG) const {
2405   MachineFunction &MF = DAG.getMachineFunction();
2406   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2407   unsigned ARMPCLabelIndex = 0;
2408   SDLoc DL(Op);
2409   EVT PtrVT = getPointerTy();
2410   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2411   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2412   SDValue CPAddr;
2413   if (RelocM == Reloc::Static) {
2414     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2415   } else {
2416     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2417     ARMPCLabelIndex = AFI->createPICLabelUId();
2418     ARMConstantPoolValue *CPV =
2419       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2420                                       ARMCP::CPBlockAddress, PCAdj);
2421     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2422   }
2423   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2424   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2425                                MachinePointerInfo::getConstantPool(),
2426                                false, false, false, 0);
2427   if (RelocM == Reloc::Static)
2428     return Result;
2429   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2430   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2431 }
2432
2433 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2434 SDValue
2435 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2436                                                  SelectionDAG &DAG) const {
2437   SDLoc dl(GA);
2438   EVT PtrVT = getPointerTy();
2439   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2440   MachineFunction &MF = DAG.getMachineFunction();
2441   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2442   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2443   ARMConstantPoolValue *CPV =
2444     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2445                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2446   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2447   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2448   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2449                          MachinePointerInfo::getConstantPool(),
2450                          false, false, false, 0);
2451   SDValue Chain = Argument.getValue(1);
2452
2453   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2454   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2455
2456   // call __tls_get_addr.
2457   ArgListTy Args;
2458   ArgListEntry Entry;
2459   Entry.Node = Argument;
2460   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2461   Args.push_back(Entry);
2462
2463   // FIXME: is there useful debug info available here?
2464   TargetLowering::CallLoweringInfo CLI(DAG);
2465   CLI.setDebugLoc(dl).setChain(Chain)
2466     .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2467                DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2468                0);
2469
2470   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2471   return CallResult.first;
2472 }
2473
2474 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2475 // "local exec" model.
2476 SDValue
2477 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2478                                         SelectionDAG &DAG,
2479                                         TLSModel::Model model) const {
2480   const GlobalValue *GV = GA->getGlobal();
2481   SDLoc dl(GA);
2482   SDValue Offset;
2483   SDValue Chain = DAG.getEntryNode();
2484   EVT PtrVT = getPointerTy();
2485   // Get the Thread Pointer
2486   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2487
2488   if (model == TLSModel::InitialExec) {
2489     MachineFunction &MF = DAG.getMachineFunction();
2490     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2491     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2492     // Initial exec model.
2493     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2494     ARMConstantPoolValue *CPV =
2495       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2496                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2497                                       true);
2498     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2499     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2500     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2501                          MachinePointerInfo::getConstantPool(),
2502                          false, false, false, 0);
2503     Chain = Offset.getValue(1);
2504
2505     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2506     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2507
2508     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2509                          MachinePointerInfo::getConstantPool(),
2510                          false, false, false, 0);
2511   } else {
2512     // local exec model
2513     assert(model == TLSModel::LocalExec);
2514     ARMConstantPoolValue *CPV =
2515       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2516     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2517     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2518     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2519                          MachinePointerInfo::getConstantPool(),
2520                          false, false, false, 0);
2521   }
2522
2523   // The address of the thread local variable is the add of the thread
2524   // pointer with the offset of the variable.
2525   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2526 }
2527
2528 SDValue
2529 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2530   // TODO: implement the "local dynamic" model
2531   assert(Subtarget->isTargetELF() &&
2532          "TLS not implemented for non-ELF targets");
2533   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2534
2535   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2536
2537   switch (model) {
2538     case TLSModel::GeneralDynamic:
2539     case TLSModel::LocalDynamic:
2540       return LowerToTLSGeneralDynamicModel(GA, DAG);
2541     case TLSModel::InitialExec:
2542     case TLSModel::LocalExec:
2543       return LowerToTLSExecModels(GA, DAG, model);
2544   }
2545   llvm_unreachable("bogus TLS model");
2546 }
2547
2548 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2549                                                  SelectionDAG &DAG) const {
2550   EVT PtrVT = getPointerTy();
2551   SDLoc dl(Op);
2552   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2553   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2554     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2555     ARMConstantPoolValue *CPV =
2556       ARMConstantPoolConstant::Create(GV,
2557                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2558     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2559     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2560     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2561                                  CPAddr,
2562                                  MachinePointerInfo::getConstantPool(),
2563                                  false, false, false, 0);
2564     SDValue Chain = Result.getValue(1);
2565     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2566     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2567     if (!UseGOTOFF)
2568       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2569                            MachinePointerInfo::getGOT(),
2570                            false, false, false, 0);
2571     return Result;
2572   }
2573
2574   // If we have T2 ops, we can materialize the address directly via movt/movw
2575   // pair. This is always cheaper.
2576   if (Subtarget->useMovt(DAG.getMachineFunction())) {
2577     ++NumMovwMovt;
2578     // FIXME: Once remat is capable of dealing with instructions with register
2579     // operands, expand this into two nodes.
2580     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2581                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2582   } else {
2583     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2584     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2585     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2586                        MachinePointerInfo::getConstantPool(),
2587                        false, false, false, 0);
2588   }
2589 }
2590
2591 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2592                                                     SelectionDAG &DAG) const {
2593   EVT PtrVT = getPointerTy();
2594   SDLoc dl(Op);
2595   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2596   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2597
2598   if (Subtarget->useMovt(DAG.getMachineFunction()))
2599     ++NumMovwMovt;
2600
2601   // FIXME: Once remat is capable of dealing with instructions with register
2602   // operands, expand this into multiple nodes
2603   unsigned Wrapper =
2604       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2605
2606   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2607   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2608
2609   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2610     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2611                          MachinePointerInfo::getGOT(), false, false, false, 0);
2612   return Result;
2613 }
2614
2615 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2616                                                      SelectionDAG &DAG) const {
2617   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2618   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2619          "Windows on ARM expects to use movw/movt");
2620
2621   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2622   const ARMII::TOF TargetFlags =
2623     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2624   EVT PtrVT = getPointerTy();
2625   SDValue Result;
2626   SDLoc DL(Op);
2627
2628   ++NumMovwMovt;
2629
2630   // FIXME: Once remat is capable of dealing with instructions with register
2631   // operands, expand this into two nodes.
2632   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2633                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2634                                                   TargetFlags));
2635   if (GV->hasDLLImportStorageClass())
2636     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2637                          MachinePointerInfo::getGOT(), false, false, false, 0);
2638   return Result;
2639 }
2640
2641 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2642                                                     SelectionDAG &DAG) const {
2643   assert(Subtarget->isTargetELF() &&
2644          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2645   MachineFunction &MF = DAG.getMachineFunction();
2646   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2647   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2648   EVT PtrVT = getPointerTy();
2649   SDLoc dl(Op);
2650   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2651   ARMConstantPoolValue *CPV =
2652     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2653                                   ARMPCLabelIndex, PCAdj);
2654   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2655   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2656   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2657                                MachinePointerInfo::getConstantPool(),
2658                                false, false, false, 0);
2659   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2660   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2661 }
2662
2663 SDValue
2664 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2665   SDLoc dl(Op);
2666   SDValue Val = DAG.getConstant(0, dl, MVT::i32);
2667   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2668                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2669                      Op.getOperand(1), Val);
2670 }
2671
2672 SDValue
2673 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2674   SDLoc dl(Op);
2675   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2676                      Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
2677 }
2678
2679 SDValue
2680 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2681                                           const ARMSubtarget *Subtarget) const {
2682   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2683   SDLoc dl(Op);
2684   switch (IntNo) {
2685   default: return SDValue();    // Don't custom lower most intrinsics.
2686   case Intrinsic::arm_rbit: {
2687     assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2688            "RBIT intrinsic must have i32 type!");
2689     return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1));
2690   }
2691   case Intrinsic::arm_thread_pointer: {
2692     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2693     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2694   }
2695   case Intrinsic::eh_sjlj_lsda: {
2696     MachineFunction &MF = DAG.getMachineFunction();
2697     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2698     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2699     EVT PtrVT = getPointerTy();
2700     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2701     SDValue CPAddr;
2702     unsigned PCAdj = (RelocM != Reloc::PIC_)
2703       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2704     ARMConstantPoolValue *CPV =
2705       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2706                                       ARMCP::CPLSDA, PCAdj);
2707     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2708     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2709     SDValue Result =
2710       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2711                   MachinePointerInfo::getConstantPool(),
2712                   false, false, false, 0);
2713
2714     if (RelocM == Reloc::PIC_) {
2715       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2716       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2717     }
2718     return Result;
2719   }
2720   case Intrinsic::arm_neon_vmulls:
2721   case Intrinsic::arm_neon_vmullu: {
2722     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2723       ? ARMISD::VMULLs : ARMISD::VMULLu;
2724     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2725                        Op.getOperand(1), Op.getOperand(2));
2726   }
2727   }
2728 }
2729
2730 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2731                                  const ARMSubtarget *Subtarget) {
2732   // FIXME: handle "fence singlethread" more efficiently.
2733   SDLoc dl(Op);
2734   if (!Subtarget->hasDataBarrier()) {
2735     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2736     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2737     // here.
2738     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2739            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2740     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2741                        DAG.getConstant(0, dl, MVT::i32));
2742   }
2743
2744   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2745   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2746   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
2747   if (Subtarget->isMClass()) {
2748     // Only a full system barrier exists in the M-class architectures.
2749     Domain = ARM_MB::SY;
2750   } else if (Subtarget->isSwift() && Ord == Release) {
2751     // Swift happens to implement ISHST barriers in a way that's compatible with
2752     // Release semantics but weaker than ISH so we'd be fools not to use
2753     // it. Beware: other processors probably don't!
2754     Domain = ARM_MB::ISHST;
2755   }
2756
2757   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2758                      DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
2759                      DAG.getConstant(Domain, dl, MVT::i32));
2760 }
2761
2762 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2763                              const ARMSubtarget *Subtarget) {
2764   // ARM pre v5TE and Thumb1 does not have preload instructions.
2765   if (!(Subtarget->isThumb2() ||
2766         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2767     // Just preserve the chain.
2768     return Op.getOperand(0);
2769
2770   SDLoc dl(Op);
2771   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2772   if (!isRead &&
2773       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2774     // ARMv7 with MP extension has PLDW.
2775     return Op.getOperand(0);
2776
2777   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2778   if (Subtarget->isThumb()) {
2779     // Invert the bits.
2780     isRead = ~isRead & 1;
2781     isData = ~isData & 1;
2782   }
2783
2784   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2785                      Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
2786                      DAG.getConstant(isData, dl, MVT::i32));
2787 }
2788
2789 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2790   MachineFunction &MF = DAG.getMachineFunction();
2791   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2792
2793   // vastart just stores the address of the VarArgsFrameIndex slot into the
2794   // memory location argument.
2795   SDLoc dl(Op);
2796   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2797   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2798   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2799   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2800                       MachinePointerInfo(SV), false, false, 0);
2801 }
2802
2803 SDValue
2804 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2805                                         SDValue &Root, SelectionDAG &DAG,
2806                                         SDLoc dl) const {
2807   MachineFunction &MF = DAG.getMachineFunction();
2808   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2809
2810   const TargetRegisterClass *RC;
2811   if (AFI->isThumb1OnlyFunction())
2812     RC = &ARM::tGPRRegClass;
2813   else
2814     RC = &ARM::GPRRegClass;
2815
2816   // Transform the arguments stored in physical registers into virtual ones.
2817   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2818   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2819
2820   SDValue ArgValue2;
2821   if (NextVA.isMemLoc()) {
2822     MachineFrameInfo *MFI = MF.getFrameInfo();
2823     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2824
2825     // Create load node to retrieve arguments from the stack.
2826     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2827     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2828                             MachinePointerInfo::getFixedStack(FI),
2829                             false, false, false, 0);
2830   } else {
2831     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2832     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2833   }
2834   if (!Subtarget->isLittle())
2835     std::swap (ArgValue, ArgValue2);
2836   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2837 }
2838
2839 // The remaining GPRs hold either the beginning of variable-argument
2840 // data, or the beginning of an aggregate passed by value (usually
2841 // byval).  Either way, we allocate stack slots adjacent to the data
2842 // provided by our caller, and store the unallocated registers there.
2843 // If this is a variadic function, the va_list pointer will begin with
2844 // these values; otherwise, this reassembles a (byval) structure that
2845 // was split between registers and memory.
2846 // Return: The frame index registers were stored into.
2847 int
2848 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2849                                   SDLoc dl, SDValue &Chain,
2850                                   const Value *OrigArg,
2851                                   unsigned InRegsParamRecordIdx,
2852                                   int ArgOffset,
2853                                   unsigned ArgSize) const {
2854   // Currently, two use-cases possible:
2855   // Case #1. Non-var-args function, and we meet first byval parameter.
2856   //          Setup first unallocated register as first byval register;
2857   //          eat all remained registers
2858   //          (these two actions are performed by HandleByVal method).
2859   //          Then, here, we initialize stack frame with
2860   //          "store-reg" instructions.
2861   // Case #2. Var-args function, that doesn't contain byval parameters.
2862   //          The same: eat all remained unallocated registers,
2863   //          initialize stack frame.
2864
2865   MachineFunction &MF = DAG.getMachineFunction();
2866   MachineFrameInfo *MFI = MF.getFrameInfo();
2867   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2868   unsigned RBegin, REnd;
2869   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2870     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2871   } else {
2872     unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
2873     RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
2874     REnd = ARM::R4;
2875   }
2876
2877   if (REnd != RBegin)
2878     ArgOffset = -4 * (ARM::R4 - RBegin);
2879
2880   int FrameIndex = MFI->CreateFixedObject(ArgSize, ArgOffset, false);
2881   SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2882
2883   SmallVector<SDValue, 4> MemOps;
2884   const TargetRegisterClass *RC =
2885       AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
2886
2887   for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
2888     unsigned VReg = MF.addLiveIn(Reg, RC);
2889     SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2890     SDValue Store =
2891         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2892                      MachinePointerInfo(OrigArg, 4 * i), false, false, 0);
2893     MemOps.push_back(Store);
2894     FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2895                       DAG.getConstant(4, dl, getPointerTy()));
2896   }
2897
2898   if (!MemOps.empty())
2899     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2900   return FrameIndex;
2901 }
2902
2903 // Setup stack frame, the va_list pointer will start from.
2904 void
2905 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2906                                         SDLoc dl, SDValue &Chain,
2907                                         unsigned ArgOffset,
2908                                         unsigned TotalArgRegsSaveSize,
2909                                         bool ForceMutable) const {
2910   MachineFunction &MF = DAG.getMachineFunction();
2911   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2912
2913   // Try to store any remaining integer argument regs
2914   // to their spots on the stack so that they may be loaded by deferencing
2915   // the result of va_next.
2916   // If there is no regs to be stored, just point address after last
2917   // argument passed via stack.
2918   int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
2919                                   CCInfo.getInRegsParamsCount(),
2920                                   CCInfo.getNextStackOffset(), 4);
2921   AFI->setVarArgsFrameIndex(FrameIndex);
2922 }
2923
2924 SDValue
2925 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2926                                         CallingConv::ID CallConv, bool isVarArg,
2927                                         const SmallVectorImpl<ISD::InputArg>
2928                                           &Ins,
2929                                         SDLoc dl, SelectionDAG &DAG,
2930                                         SmallVectorImpl<SDValue> &InVals)
2931                                           const {
2932   MachineFunction &MF = DAG.getMachineFunction();
2933   MachineFrameInfo *MFI = MF.getFrameInfo();
2934
2935   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2936
2937   // Assign locations to all of the incoming arguments.
2938   SmallVector<CCValAssign, 16> ArgLocs;
2939   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2940                     *DAG.getContext(), Prologue);
2941   CCInfo.AnalyzeFormalArguments(Ins,
2942                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2943                                                   isVarArg));
2944
2945   SmallVector<SDValue, 16> ArgValues;
2946   SDValue ArgValue;
2947   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2948   unsigned CurArgIdx = 0;
2949
2950   // Initially ArgRegsSaveSize is zero.
2951   // Then we increase this value each time we meet byval parameter.
2952   // We also increase this value in case of varargs function.
2953   AFI->setArgRegsSaveSize(0);
2954
2955   // Calculate the amount of stack space that we need to allocate to store
2956   // byval and variadic arguments that are passed in registers.
2957   // We need to know this before we allocate the first byval or variadic
2958   // argument, as they will be allocated a stack slot below the CFA (Canonical
2959   // Frame Address, the stack pointer at entry to the function).
2960   unsigned ArgRegBegin = ARM::R4;
2961   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2962     if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
2963       break;
2964
2965     CCValAssign &VA = ArgLocs[i];
2966     unsigned Index = VA.getValNo();
2967     ISD::ArgFlagsTy Flags = Ins[Index].Flags;
2968     if (!Flags.isByVal())
2969       continue;
2970
2971     assert(VA.isMemLoc() && "unexpected byval pointer in reg");
2972     unsigned RBegin, REnd;
2973     CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
2974     ArgRegBegin = std::min(ArgRegBegin, RBegin);
2975
2976     CCInfo.nextInRegsParam();
2977   }
2978   CCInfo.rewindByValRegsInfo();
2979
2980   int lastInsIndex = -1;
2981   if (isVarArg && MFI->hasVAStart()) {
2982     unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
2983     if (RegIdx != array_lengthof(GPRArgRegs))
2984       ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
2985   }
2986
2987   unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
2988   AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
2989
2990   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2991     CCValAssign &VA = ArgLocs[i];
2992     if (Ins[VA.getValNo()].isOrigArg()) {
2993       std::advance(CurOrigArg,
2994                    Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
2995       CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
2996     }
2997     // Arguments stored in registers.
2998     if (VA.isRegLoc()) {
2999       EVT RegVT = VA.getLocVT();
3000
3001       if (VA.needsCustom()) {
3002         // f64 and vector types are split up into multiple registers or
3003         // combinations of registers and stack slots.
3004         if (VA.getLocVT() == MVT::v2f64) {
3005           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3006                                                    Chain, DAG, dl);
3007           VA = ArgLocs[++i]; // skip ahead to next loc
3008           SDValue ArgValue2;
3009           if (VA.isMemLoc()) {
3010             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3011             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3012             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3013                                     MachinePointerInfo::getFixedStack(FI),
3014                                     false, false, false, 0);
3015           } else {
3016             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3017                                              Chain, DAG, dl);
3018           }
3019           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3020           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3021                                  ArgValue, ArgValue1,
3022                                  DAG.getIntPtrConstant(0, dl));
3023           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3024                                  ArgValue, ArgValue2,
3025                                  DAG.getIntPtrConstant(1, dl));
3026         } else
3027           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3028
3029       } else {
3030         const TargetRegisterClass *RC;
3031
3032         if (RegVT == MVT::f32)
3033           RC = &ARM::SPRRegClass;
3034         else if (RegVT == MVT::f64)
3035           RC = &ARM::DPRRegClass;
3036         else if (RegVT == MVT::v2f64)
3037           RC = &ARM::QPRRegClass;
3038         else if (RegVT == MVT::i32)
3039           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3040                                            : &ARM::GPRRegClass;
3041         else
3042           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3043
3044         // Transform the arguments in physical registers into virtual ones.
3045         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3046         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3047       }
3048
3049       // If this is an 8 or 16-bit value, it is really passed promoted
3050       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3051       // truncate to the right size.
3052       switch (VA.getLocInfo()) {
3053       default: llvm_unreachable("Unknown loc info!");
3054       case CCValAssign::Full: break;
3055       case CCValAssign::BCvt:
3056         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3057         break;
3058       case CCValAssign::SExt:
3059         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3060                                DAG.getValueType(VA.getValVT()));
3061         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3062         break;
3063       case CCValAssign::ZExt:
3064         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3065                                DAG.getValueType(VA.getValVT()));
3066         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3067         break;
3068       }
3069
3070       InVals.push_back(ArgValue);
3071
3072     } else { // VA.isRegLoc()
3073
3074       // sanity check
3075       assert(VA.isMemLoc());
3076       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3077
3078       int index = VA.getValNo();
3079
3080       // Some Ins[] entries become multiple ArgLoc[] entries.
3081       // Process them only once.
3082       if (index != lastInsIndex)
3083         {
3084           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3085           // FIXME: For now, all byval parameter objects are marked mutable.
3086           // This can be changed with more analysis.
3087           // In case of tail call optimization mark all arguments mutable.
3088           // Since they could be overwritten by lowering of arguments in case of
3089           // a tail call.
3090           if (Flags.isByVal()) {
3091             assert(Ins[index].isOrigArg() &&
3092                    "Byval arguments cannot be implicit");
3093             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3094
3095             int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, CurOrigArg,
3096                                             CurByValIndex, VA.getLocMemOffset(),
3097                                             Flags.getByValSize());
3098             InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3099             CCInfo.nextInRegsParam();
3100           } else {
3101             unsigned FIOffset = VA.getLocMemOffset();
3102             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3103                                             FIOffset, true);
3104
3105             // Create load nodes to retrieve arguments from the stack.
3106             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3107             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3108                                          MachinePointerInfo::getFixedStack(FI),
3109                                          false, false, false, 0));
3110           }
3111           lastInsIndex = index;
3112         }
3113     }
3114   }
3115
3116   // varargs
3117   if (isVarArg && MFI->hasVAStart())
3118     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3119                          CCInfo.getNextStackOffset(),
3120                          TotalArgRegsSaveSize);
3121
3122   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3123
3124   return Chain;
3125 }
3126
3127 /// isFloatingPointZero - Return true if this is +0.0.
3128 static bool isFloatingPointZero(SDValue Op) {
3129   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3130     return CFP->getValueAPF().isPosZero();
3131   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3132     // Maybe this has already been legalized into the constant pool?
3133     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3134       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3135       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3136         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3137           return CFP->getValueAPF().isPosZero();
3138     }
3139   } else if (Op->getOpcode() == ISD::BITCAST &&
3140              Op->getValueType(0) == MVT::f64) {
3141     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3142     // created by LowerConstantFP().
3143     SDValue BitcastOp = Op->getOperand(0);
3144     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM) {
3145       SDValue MoveOp = BitcastOp->getOperand(0);
3146       if (MoveOp->getOpcode() == ISD::TargetConstant &&
3147           cast<ConstantSDNode>(MoveOp)->getZExtValue() == 0) {
3148         return true;
3149       }
3150     }
3151   }
3152   return false;
3153 }
3154
3155 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3156 /// the given operands.
3157 SDValue
3158 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3159                              SDValue &ARMcc, SelectionDAG &DAG,
3160                              SDLoc dl) const {
3161   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3162     unsigned C = RHSC->getZExtValue();
3163     if (!isLegalICmpImmediate(C)) {
3164       // Constant does not fit, try adjusting it by one?
3165       switch (CC) {
3166       default: break;
3167       case ISD::SETLT:
3168       case ISD::SETGE:
3169         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3170           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3171           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3172         }
3173         break;
3174       case ISD::SETULT:
3175       case ISD::SETUGE:
3176         if (C != 0 && isLegalICmpImmediate(C-1)) {
3177           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3178           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3179         }
3180         break;
3181       case ISD::SETLE:
3182       case ISD::SETGT:
3183         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3184           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3185           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3186         }
3187         break;
3188       case ISD::SETULE:
3189       case ISD::SETUGT:
3190         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3191           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3192           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3193         }
3194         break;
3195       }
3196     }
3197   }
3198
3199   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3200   ARMISD::NodeType CompareType;
3201   switch (CondCode) {
3202   default:
3203     CompareType = ARMISD::CMP;
3204     break;
3205   case ARMCC::EQ:
3206   case ARMCC::NE:
3207     // Uses only Z Flag
3208     CompareType = ARMISD::CMPZ;
3209     break;
3210   }
3211   ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3212   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3213 }
3214
3215 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3216 SDValue
3217 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3218                              SDLoc dl) const {
3219   assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3220   SDValue Cmp;
3221   if (!isFloatingPointZero(RHS))
3222     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3223   else
3224     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3225   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3226 }
3227
3228 /// duplicateCmp - Glue values can have only one use, so this function
3229 /// duplicates a comparison node.
3230 SDValue
3231 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3232   unsigned Opc = Cmp.getOpcode();
3233   SDLoc DL(Cmp);
3234   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3235     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3236
3237   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3238   Cmp = Cmp.getOperand(0);
3239   Opc = Cmp.getOpcode();
3240   if (Opc == ARMISD::CMPFP)
3241     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3242   else {
3243     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3244     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3245   }
3246   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3247 }
3248
3249 std::pair<SDValue, SDValue>
3250 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3251                                  SDValue &ARMcc) const {
3252   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3253
3254   SDValue Value, OverflowCmp;
3255   SDValue LHS = Op.getOperand(0);
3256   SDValue RHS = Op.getOperand(1);
3257   SDLoc dl(Op);
3258
3259   // FIXME: We are currently always generating CMPs because we don't support
3260   // generating CMN through the backend. This is not as good as the natural
3261   // CMP case because it causes a register dependency and cannot be folded
3262   // later.
3263
3264   switch (Op.getOpcode()) {
3265   default:
3266     llvm_unreachable("Unknown overflow instruction!");
3267   case ISD::SADDO:
3268     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3269     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3270     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3271     break;
3272   case ISD::UADDO:
3273     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3274     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3275     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3276     break;
3277   case ISD::SSUBO:
3278     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3279     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3280     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3281     break;
3282   case ISD::USUBO:
3283     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3284     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3285     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3286     break;
3287   } // switch (...)
3288
3289   return std::make_pair(Value, OverflowCmp);
3290 }
3291
3292
3293 SDValue
3294 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3295   // Let legalize expand this if it isn't a legal type yet.
3296   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3297     return SDValue();
3298
3299   SDValue Value, OverflowCmp;
3300   SDValue ARMcc;
3301   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3302   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3303   SDLoc dl(Op);
3304   // We use 0 and 1 as false and true values.
3305   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3306   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3307   EVT VT = Op.getValueType();
3308
3309   SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
3310                                  ARMcc, CCR, OverflowCmp);
3311
3312   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3313   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
3314 }
3315
3316
3317 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3318   SDValue Cond = Op.getOperand(0);
3319   SDValue SelectTrue = Op.getOperand(1);
3320   SDValue SelectFalse = Op.getOperand(2);
3321   SDLoc dl(Op);
3322   unsigned Opc = Cond.getOpcode();
3323
3324   if (Cond.getResNo() == 1 &&
3325       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3326        Opc == ISD::USUBO)) {
3327     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3328       return SDValue();
3329
3330     SDValue Value, OverflowCmp;
3331     SDValue ARMcc;
3332     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3333     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3334     EVT VT = Op.getValueType();
3335
3336     return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
3337                    OverflowCmp, DAG);
3338   }
3339
3340   // Convert:
3341   //
3342   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3343   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3344   //
3345   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3346     const ConstantSDNode *CMOVTrue =
3347       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3348     const ConstantSDNode *CMOVFalse =
3349       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3350
3351     if (CMOVTrue && CMOVFalse) {
3352       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3353       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3354
3355       SDValue True;
3356       SDValue False;
3357       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3358         True = SelectTrue;
3359         False = SelectFalse;
3360       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3361         True = SelectFalse;
3362         False = SelectTrue;
3363       }
3364
3365       if (True.getNode() && False.getNode()) {
3366         EVT VT = Op.getValueType();
3367         SDValue ARMcc = Cond.getOperand(2);
3368         SDValue CCR = Cond.getOperand(3);
3369         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3370         assert(True.getValueType() == VT);
3371         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3372       }
3373     }
3374   }
3375
3376   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3377   // undefined bits before doing a full-word comparison with zero.
3378   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3379                      DAG.getConstant(1, dl, Cond.getValueType()));
3380
3381   return DAG.getSelectCC(dl, Cond,
3382                          DAG.getConstant(0, dl, Cond.getValueType()),
3383                          SelectTrue, SelectFalse, ISD::SETNE);
3384 }
3385
3386 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3387                                  bool &swpCmpOps, bool &swpVselOps) {
3388   // Start by selecting the GE condition code for opcodes that return true for
3389   // 'equality'
3390   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3391       CC == ISD::SETULE)
3392     CondCode = ARMCC::GE;
3393
3394   // and GT for opcodes that return false for 'equality'.
3395   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3396            CC == ISD::SETULT)
3397     CondCode = ARMCC::GT;
3398
3399   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3400   // to swap the compare operands.
3401   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3402       CC == ISD::SETULT)
3403     swpCmpOps = true;
3404
3405   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3406   // If we have an unordered opcode, we need to swap the operands to the VSEL
3407   // instruction (effectively negating the condition).
3408   //
3409   // This also has the effect of swapping which one of 'less' or 'greater'
3410   // returns true, so we also swap the compare operands. It also switches
3411   // whether we return true for 'equality', so we compensate by picking the
3412   // opposite condition code to our original choice.
3413   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3414       CC == ISD::SETUGT) {
3415     swpCmpOps = !swpCmpOps;
3416     swpVselOps = !swpVselOps;
3417     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3418   }
3419
3420   // 'ordered' is 'anything but unordered', so use the VS condition code and
3421   // swap the VSEL operands.
3422   if (CC == ISD::SETO) {
3423     CondCode = ARMCC::VS;
3424     swpVselOps = true;
3425   }
3426
3427   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3428   // code and swap the VSEL operands.
3429   if (CC == ISD::SETUNE) {
3430     CondCode = ARMCC::EQ;
3431     swpVselOps = true;
3432   }
3433 }
3434
3435 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3436                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3437                                    SDValue Cmp, SelectionDAG &DAG) const {
3438   if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3439     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3440                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3441     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3442                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3443
3444     SDValue TrueLow = TrueVal.getValue(0);
3445     SDValue TrueHigh = TrueVal.getValue(1);
3446     SDValue FalseLow = FalseVal.getValue(0);
3447     SDValue FalseHigh = FalseVal.getValue(1);
3448
3449     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3450                               ARMcc, CCR, Cmp);
3451     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3452                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
3453
3454     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3455   } else {
3456     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3457                        Cmp);
3458   }
3459 }
3460
3461 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3462   EVT VT = Op.getValueType();
3463   SDValue LHS = Op.getOperand(0);
3464   SDValue RHS = Op.getOperand(1);
3465   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3466   SDValue TrueVal = Op.getOperand(2);
3467   SDValue FalseVal = Op.getOperand(3);
3468   SDLoc dl(Op);
3469
3470   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3471     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3472                                                     dl);
3473
3474     // If softenSetCCOperands only returned one value, we should compare it to
3475     // zero.
3476     if (!RHS.getNode()) {
3477       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3478       CC = ISD::SETNE;
3479     }
3480   }
3481
3482   if (LHS.getValueType() == MVT::i32) {
3483     // Try to generate VSEL on ARMv8.
3484     // The VSEL instruction can't use all the usual ARM condition
3485     // codes: it only has two bits to select the condition code, so it's
3486     // constrained to use only GE, GT, VS and EQ.
3487     //
3488     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3489     // swap the operands of the previous compare instruction (effectively
3490     // inverting the compare condition, swapping 'less' and 'greater') and
3491     // sometimes need to swap the operands to the VSEL (which inverts the
3492     // condition in the sense of firing whenever the previous condition didn't)
3493     if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3494                                     TrueVal.getValueType() == MVT::f64)) {
3495       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3496       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3497           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3498         CC = ISD::getSetCCInverse(CC, true);
3499         std::swap(TrueVal, FalseVal);
3500       }
3501     }
3502
3503     SDValue ARMcc;
3504     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3505     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3506     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3507   }
3508
3509   ARMCC::CondCodes CondCode, CondCode2;
3510   FPCCToARMCC(CC, CondCode, CondCode2);
3511
3512   // Try to generate VMAXNM/VMINNM on ARMv8.
3513   if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3514                                   TrueVal.getValueType() == MVT::f64)) {
3515     // We can use VMAXNM/VMINNM for a compare followed by a select with the
3516     // same operands, as follows:
3517     //   c = fcmp [?gt, ?ge, ?lt, ?le] a, b
3518     //   select c, a, b
3519     // In NoNaNsFPMath the CC will have been changed from, e.g., 'ogt' to 'gt'.
3520     // FIXME: There is similar code that allows some extensions in
3521     // AArch64TargetLowering::LowerSELECT_CC that should be shared with this
3522     // code.
3523     bool swapSides = false;
3524     if (!getTargetMachine().Options.NoNaNsFPMath) {
3525       // transformability may depend on which way around we compare
3526       switch (CC) {
3527       default:
3528         break;
3529       case ISD::SETOGT:
3530       case ISD::SETOGE:
3531       case ISD::SETOLT:
3532       case ISD::SETOLE:
3533         // the non-NaN should be RHS
3534         swapSides = DAG.isKnownNeverNaN(LHS) && !DAG.isKnownNeverNaN(RHS);
3535         break;
3536       case ISD::SETUGT:
3537       case ISD::SETUGE:
3538       case ISD::SETULT:
3539       case ISD::SETULE:
3540         // the non-NaN should be LHS
3541         swapSides = DAG.isKnownNeverNaN(RHS) && !DAG.isKnownNeverNaN(LHS);
3542         break;
3543       }
3544     }
3545     swapSides = swapSides || (LHS == FalseVal && RHS == TrueVal);
3546     if (swapSides) {
3547       CC = ISD::getSetCCSwappedOperands(CC);
3548       std::swap(LHS, RHS);
3549     }
3550     if (LHS == TrueVal && RHS == FalseVal) {
3551       bool canTransform = true;
3552       // FIXME: FastMathFlags::noSignedZeros() doesn't appear reachable from here
3553       if (!getTargetMachine().Options.UnsafeFPMath &&
3554           !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
3555         const ConstantFPSDNode *Zero;
3556         switch (CC) {
3557         default:
3558           break;
3559         case ISD::SETOGT:
3560         case ISD::SETUGT:
3561         case ISD::SETGT:
3562           // RHS must not be -0
3563           canTransform = (Zero = dyn_cast<ConstantFPSDNode>(RHS)) &&
3564                          !Zero->isNegative();
3565           break;
3566         case ISD::SETOGE:
3567         case ISD::SETUGE:
3568         case ISD::SETGE:
3569           // LHS must not be -0
3570           canTransform = (Zero = dyn_cast<ConstantFPSDNode>(LHS)) &&
3571                          !Zero->isNegative();
3572           break;
3573         case ISD::SETOLT:
3574         case ISD::SETULT:
3575         case ISD::SETLT:
3576           // RHS must not be +0
3577           canTransform = (Zero = dyn_cast<ConstantFPSDNode>(RHS)) &&
3578                           Zero->isNegative();
3579           break;
3580         case ISD::SETOLE:
3581         case ISD::SETULE:
3582         case ISD::SETLE:
3583           // LHS must not be +0
3584           canTransform = (Zero = dyn_cast<ConstantFPSDNode>(LHS)) &&
3585                           Zero->isNegative();
3586           break;
3587         }
3588       }
3589       if (canTransform) {
3590         // Note: If one of the elements in a pair is a number and the other
3591         // element is NaN, the corresponding result element is the number.
3592         // This is consistent with the IEEE 754-2008 standard.
3593         // Therefore, a > b ? a : b <=> vmax(a,b), if b is constant and a is NaN
3594         switch (CC) {
3595         default:
3596           break;
3597         case ISD::SETOGT:
3598         case ISD::SETOGE:
3599           if (!DAG.isKnownNeverNaN(RHS))
3600             break;
3601           return DAG.getNode(ARMISD::VMAXNM, dl, VT, LHS, RHS);
3602         case ISD::SETUGT:
3603         case ISD::SETUGE:
3604           if (!DAG.isKnownNeverNaN(LHS))
3605             break;
3606         case ISD::SETGT:
3607         case ISD::SETGE:
3608           return DAG.getNode(ARMISD::VMAXNM, dl, VT, LHS, RHS);
3609         case ISD::SETOLT:
3610         case ISD::SETOLE:
3611           if (!DAG.isKnownNeverNaN(RHS))
3612             break;
3613           return DAG.getNode(ARMISD::VMINNM, dl, VT, LHS, RHS);
3614         case ISD::SETULT:
3615         case ISD::SETULE:
3616           if (!DAG.isKnownNeverNaN(LHS))
3617             break;
3618         case ISD::SETLT:
3619         case ISD::SETLE:
3620           return DAG.getNode(ARMISD::VMINNM, dl, VT, LHS, RHS);
3621         }
3622       }
3623     }
3624
3625     bool swpCmpOps = false;
3626     bool swpVselOps = false;
3627     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3628
3629     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3630         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3631       if (swpCmpOps)
3632         std::swap(LHS, RHS);
3633       if (swpVselOps)
3634         std::swap(TrueVal, FalseVal);
3635     }
3636   }
3637
3638   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3639   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3640   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3641   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3642   if (CondCode2 != ARMCC::AL) {
3643     SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
3644     // FIXME: Needs another CMP because flag can have but one use.
3645     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3646     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3647   }
3648   return Result;
3649 }
3650
3651 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3652 /// to morph to an integer compare sequence.
3653 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3654                            const ARMSubtarget *Subtarget) {
3655   SDNode *N = Op.getNode();
3656   if (!N->hasOneUse())
3657     // Otherwise it requires moving the value from fp to integer registers.
3658     return false;
3659   if (!N->getNumValues())
3660     return false;
3661   EVT VT = Op.getValueType();
3662   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3663     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3664     // vmrs are very slow, e.g. cortex-a8.
3665     return false;
3666
3667   if (isFloatingPointZero(Op)) {
3668     SeenZero = true;
3669     return true;
3670   }
3671   return ISD::isNormalLoad(N);
3672 }
3673
3674 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3675   if (isFloatingPointZero(Op))
3676     return DAG.getConstant(0, SDLoc(Op), MVT::i32);
3677
3678   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3679     return DAG.getLoad(MVT::i32, SDLoc(Op),
3680                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3681                        Ld->isVolatile(), Ld->isNonTemporal(),
3682                        Ld->isInvariant(), Ld->getAlignment());
3683
3684   llvm_unreachable("Unknown VFP cmp argument!");
3685 }
3686
3687 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3688                            SDValue &RetVal1, SDValue &RetVal2) {
3689   SDLoc dl(Op);
3690
3691   if (isFloatingPointZero(Op)) {
3692     RetVal1 = DAG.getConstant(0, dl, MVT::i32);
3693     RetVal2 = DAG.getConstant(0, dl, MVT::i32);
3694     return;
3695   }
3696
3697   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3698     SDValue Ptr = Ld->getBasePtr();
3699     RetVal1 = DAG.getLoad(MVT::i32, dl,
3700                           Ld->getChain(), Ptr,
3701                           Ld->getPointerInfo(),
3702                           Ld->isVolatile(), Ld->isNonTemporal(),
3703                           Ld->isInvariant(), Ld->getAlignment());
3704
3705     EVT PtrType = Ptr.getValueType();
3706     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3707     SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
3708                                  PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
3709     RetVal2 = DAG.getLoad(MVT::i32, dl,
3710                           Ld->getChain(), NewPtr,
3711                           Ld->getPointerInfo().getWithOffset(4),
3712                           Ld->isVolatile(), Ld->isNonTemporal(),
3713                           Ld->isInvariant(), NewAlign);
3714     return;
3715   }
3716
3717   llvm_unreachable("Unknown VFP cmp argument!");
3718 }
3719
3720 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3721 /// f32 and even f64 comparisons to integer ones.
3722 SDValue
3723 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3724   SDValue Chain = Op.getOperand(0);
3725   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3726   SDValue LHS = Op.getOperand(2);
3727   SDValue RHS = Op.getOperand(3);
3728   SDValue Dest = Op.getOperand(4);
3729   SDLoc dl(Op);
3730
3731   bool LHSSeenZero = false;
3732   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3733   bool RHSSeenZero = false;
3734   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3735   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3736     // If unsafe fp math optimization is enabled and there are no other uses of
3737     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3738     // to an integer comparison.
3739     if (CC == ISD::SETOEQ)
3740       CC = ISD::SETEQ;
3741     else if (CC == ISD::SETUNE)
3742       CC = ISD::SETNE;
3743
3744     SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
3745     SDValue ARMcc;
3746     if (LHS.getValueType() == MVT::f32) {
3747       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3748                         bitcastf32Toi32(LHS, DAG), Mask);
3749       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3750                         bitcastf32Toi32(RHS, DAG), Mask);
3751       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3752       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3753       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3754                          Chain, Dest, ARMcc, CCR, Cmp);
3755     }
3756
3757     SDValue LHS1, LHS2;
3758     SDValue RHS1, RHS2;
3759     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3760     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3761     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3762     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3763     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3764     ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3765     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3766     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3767     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3768   }
3769
3770   return SDValue();
3771 }
3772
3773 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3774   SDValue Chain = Op.getOperand(0);
3775   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3776   SDValue LHS = Op.getOperand(2);
3777   SDValue RHS = Op.getOperand(3);
3778   SDValue Dest = Op.getOperand(4);
3779   SDLoc dl(Op);
3780
3781   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3782     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3783                                                     dl);
3784
3785     // If softenSetCCOperands only returned one value, we should compare it to
3786     // zero.
3787     if (!RHS.getNode()) {
3788       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3789       CC = ISD::SETNE;
3790     }
3791   }
3792
3793   if (LHS.getValueType() == MVT::i32) {
3794     SDValue ARMcc;
3795     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3796     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3797     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3798                        Chain, Dest, ARMcc, CCR, Cmp);
3799   }
3800
3801   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3802
3803   if (getTargetMachine().Options.UnsafeFPMath &&
3804       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3805        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3806     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3807     if (Result.getNode())
3808       return Result;
3809   }
3810
3811   ARMCC::CondCodes CondCode, CondCode2;
3812   FPCCToARMCC(CC, CondCode, CondCode2);
3813
3814   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3815   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3816   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3817   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3818   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3819   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3820   if (CondCode2 != ARMCC::AL) {
3821     ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
3822     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3823     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3824   }
3825   return Res;
3826 }
3827
3828 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3829   SDValue Chain = Op.getOperand(0);
3830   SDValue Table = Op.getOperand(1);
3831   SDValue Index = Op.getOperand(2);
3832   SDLoc dl(Op);
3833
3834   EVT PTy = getPointerTy();
3835   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3836   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3837   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), dl, PTy);
3838   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3839   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3840   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
3841   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3842   if (Subtarget->isThumb2()) {
3843     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3844     // which does another jump to the destination. This also makes it easier
3845     // to translate it to TBB / TBH later.
3846     // FIXME: This might not work if the function is extremely large.
3847     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3848                        Addr, Op.getOperand(2), JTI, UId);
3849   }
3850   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3851     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3852                        MachinePointerInfo::getJumpTable(),
3853                        false, false, false, 0);
3854     Chain = Addr.getValue(1);
3855     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3856     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3857   } else {
3858     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3859                        MachinePointerInfo::getJumpTable(),
3860                        false, false, false, 0);
3861     Chain = Addr.getValue(1);
3862     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3863   }
3864 }
3865
3866 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3867   EVT VT = Op.getValueType();
3868   SDLoc dl(Op);
3869
3870   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3871     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3872       return Op;
3873     return DAG.UnrollVectorOp(Op.getNode());
3874   }
3875
3876   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3877          "Invalid type for custom lowering!");
3878   if (VT != MVT::v4i16)
3879     return DAG.UnrollVectorOp(Op.getNode());
3880
3881   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3882   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3883 }
3884
3885 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3886   EVT VT = Op.getValueType();
3887   if (VT.isVector())
3888     return LowerVectorFP_TO_INT(Op, DAG);
3889   if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3890     RTLIB::Libcall LC;
3891     if (Op.getOpcode() == ISD::FP_TO_SINT)
3892       LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
3893                               Op.getValueType());
3894     else
3895       LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
3896                               Op.getValueType());
3897     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3898                        /*isSigned*/ false, SDLoc(Op)).first;
3899   }
3900
3901   return Op;
3902 }
3903
3904 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3905   EVT VT = Op.getValueType();
3906   SDLoc dl(Op);
3907
3908   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3909     if (VT.getVectorElementType() == MVT::f32)
3910       return Op;
3911     return DAG.UnrollVectorOp(Op.getNode());
3912   }
3913
3914   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3915          "Invalid type for custom lowering!");
3916   if (VT != MVT::v4f32)
3917     return DAG.UnrollVectorOp(Op.getNode());
3918
3919   unsigned CastOpc;
3920   unsigned Opc;
3921   switch (Op.getOpcode()) {
3922   default: llvm_unreachable("Invalid opcode!");
3923   case ISD::SINT_TO_FP:
3924     CastOpc = ISD::SIGN_EXTEND;
3925     Opc = ISD::SINT_TO_FP;
3926     break;
3927   case ISD::UINT_TO_FP:
3928     CastOpc = ISD::ZERO_EXTEND;
3929     Opc = ISD::UINT_TO_FP;
3930     break;
3931   }
3932
3933   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3934   return DAG.getNode(Opc, dl, VT, Op);
3935 }
3936
3937 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
3938   EVT VT = Op.getValueType();
3939   if (VT.isVector())
3940     return LowerVectorINT_TO_FP(Op, DAG);
3941   if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
3942     RTLIB::Libcall LC;
3943     if (Op.getOpcode() == ISD::SINT_TO_FP)
3944       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
3945                               Op.getValueType());
3946     else
3947       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
3948                               Op.getValueType());
3949     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3950                        /*isSigned*/ false, SDLoc(Op)).first;
3951   }
3952
3953   return Op;
3954 }
3955
3956 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3957   // Implement fcopysign with a fabs and a conditional fneg.
3958   SDValue Tmp0 = Op.getOperand(0);
3959   SDValue Tmp1 = Op.getOperand(1);
3960   SDLoc dl(Op);
3961   EVT VT = Op.getValueType();
3962   EVT SrcVT = Tmp1.getValueType();
3963   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3964     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3965   bool UseNEON = !InGPR && Subtarget->hasNEON();
3966
3967   if (UseNEON) {
3968     // Use VBSL to copy the sign bit.
3969     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3970     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3971                                DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
3972     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3973     if (VT == MVT::f64)
3974       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3975                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3976                          DAG.getConstant(32, dl, MVT::i32));
3977     else /*if (VT == MVT::f32)*/
3978       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3979     if (SrcVT == MVT::f32) {
3980       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3981       if (VT == MVT::f64)
3982         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3983                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3984                            DAG.getConstant(32, dl, MVT::i32));
3985     } else if (VT == MVT::f32)
3986       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3987                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3988                          DAG.getConstant(32, dl, MVT::i32));
3989     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3990     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3991
3992     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3993                                             dl, MVT::i32);
3994     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3995     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3996                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3997
3998     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3999                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4000                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4001     if (VT == MVT::f32) {
4002       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4003       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4004                         DAG.getConstant(0, dl, MVT::i32));
4005     } else {
4006       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4007     }
4008
4009     return Res;
4010   }
4011
4012   // Bitcast operand 1 to i32.
4013   if (SrcVT == MVT::f64)
4014     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4015                        Tmp1).getValue(1);
4016   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4017
4018   // Or in the signbit with integer operations.
4019   SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
4020   SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4021   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4022   if (VT == MVT::f32) {
4023     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4024                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4025     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4026                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4027   }
4028
4029   // f64: Or the high part with signbit and then combine two parts.
4030   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4031                      Tmp0);
4032   SDValue Lo = Tmp0.getValue(0);
4033   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4034   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4035   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4036 }
4037
4038 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4039   MachineFunction &MF = DAG.getMachineFunction();
4040   MachineFrameInfo *MFI = MF.getFrameInfo();
4041   MFI->setReturnAddressIsTaken(true);
4042
4043   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4044     return SDValue();
4045
4046   EVT VT = Op.getValueType();
4047   SDLoc dl(Op);
4048   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4049   if (Depth) {
4050     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4051     SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
4052     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4053                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4054                        MachinePointerInfo(), false, false, false, 0);
4055   }
4056
4057   // Return LR, which contains the return address. Mark it an implicit live-in.
4058   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4059   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4060 }
4061
4062 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4063   const ARMBaseRegisterInfo &ARI =
4064     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4065   MachineFunction &MF = DAG.getMachineFunction();
4066   MachineFrameInfo *MFI = MF.getFrameInfo();
4067   MFI->setFrameAddressIsTaken(true);
4068
4069   EVT VT = Op.getValueType();
4070   SDLoc dl(Op);  // FIXME probably not meaningful
4071   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4072   unsigned FrameReg = ARI.getFrameRegister(MF);
4073   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4074   while (Depth--)
4075     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4076                             MachinePointerInfo(),
4077                             false, false, false, 0);
4078   return FrameAddr;
4079 }
4080
4081 // FIXME? Maybe this could be a TableGen attribute on some registers and
4082 // this table could be generated automatically from RegInfo.
4083 unsigned ARMTargetLowering::getRegisterByName(const char* RegName,
4084                                               EVT VT) const {
4085   unsigned Reg = StringSwitch<unsigned>(RegName)
4086                        .Case("sp", ARM::SP)
4087                        .Default(0);
4088   if (Reg)
4089     return Reg;
4090   report_fatal_error("Invalid register name global variable");
4091 }
4092
4093 /// ExpandBITCAST - If the target supports VFP, this function is called to
4094 /// expand a bit convert where either the source or destination type is i64 to
4095 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
4096 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4097 /// vectors), since the legalizer won't know what to do with that.
4098 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4099   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4100   SDLoc dl(N);
4101   SDValue Op = N->getOperand(0);
4102
4103   // This function is only supposed to be called for i64 types, either as the
4104   // source or destination of the bit convert.
4105   EVT SrcVT = Op.getValueType();
4106   EVT DstVT = N->getValueType(0);
4107   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4108          "ExpandBITCAST called for non-i64 type");
4109
4110   // Turn i64->f64 into VMOVDRR.
4111   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4112     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4113                              DAG.getConstant(0, dl, MVT::i32));
4114     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4115                              DAG.getConstant(1, dl, MVT::i32));
4116     return DAG.getNode(ISD::BITCAST, dl, DstVT,
4117                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4118   }
4119
4120   // Turn f64->i64 into VMOVRRD.
4121   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4122     SDValue Cvt;
4123     if (TLI.isBigEndian() && SrcVT.isVector() &&
4124         SrcVT.getVectorNumElements() > 1)
4125       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4126                         DAG.getVTList(MVT::i32, MVT::i32),
4127                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4128     else
4129       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4130                         DAG.getVTList(MVT::i32, MVT::i32), Op);
4131     // Merge the pieces into a single i64 value.
4132     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4133   }
4134
4135   return SDValue();
4136 }
4137
4138 /// getZeroVector - Returns a vector of specified type with all zero elements.
4139 /// Zero vectors are used to represent vector negation and in those cases
4140 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
4141 /// not support i64 elements, so sometimes the zero vectors will need to be
4142 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
4143 /// zero vector.
4144 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4145   assert(VT.isVector() && "Expected a vector type");
4146   // The canonical modified immediate encoding of a zero vector is....0!
4147   SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
4148   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4149   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4150   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4151 }
4152
4153 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4154 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4155 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4156                                                 SelectionDAG &DAG) const {
4157   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4158   EVT VT = Op.getValueType();
4159   unsigned VTBits = VT.getSizeInBits();
4160   SDLoc dl(Op);
4161   SDValue ShOpLo = Op.getOperand(0);
4162   SDValue ShOpHi = Op.getOperand(1);
4163   SDValue ShAmt  = Op.getOperand(2);
4164   SDValue ARMcc;
4165   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4166
4167   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4168
4169   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4170                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4171   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4172   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4173                                    DAG.getConstant(VTBits, dl, MVT::i32));
4174   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4175   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4176   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4177
4178   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4179   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4180                           ISD::SETGE, ARMcc, DAG, dl);
4181   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4182   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4183                            CCR, Cmp);
4184
4185   SDValue Ops[2] = { Lo, Hi };
4186   return DAG.getMergeValues(Ops, dl);
4187 }
4188
4189 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4190 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4191 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4192                                                SelectionDAG &DAG) const {
4193   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4194   EVT VT = Op.getValueType();
4195   unsigned VTBits = VT.getSizeInBits();
4196   SDLoc dl(Op);
4197   SDValue ShOpLo = Op.getOperand(0);
4198   SDValue ShOpHi = Op.getOperand(1);
4199   SDValue ShAmt  = Op.getOperand(2);
4200   SDValue ARMcc;
4201
4202   assert(Op.getOpcode() == ISD::SHL_PARTS);
4203   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4204                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4205   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4206   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4207                                    DAG.getConstant(VTBits, dl, MVT::i32));
4208   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4209   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4210
4211   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4212   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4213   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4214                           ISD::SETGE, ARMcc, DAG, dl);
4215   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4216   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4217                            CCR, Cmp);
4218
4219   SDValue Ops[2] = { Lo, Hi };
4220   return DAG.getMergeValues(Ops, dl);
4221 }
4222
4223 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4224                                             SelectionDAG &DAG) const {
4225   // The rounding mode is in bits 23:22 of the FPSCR.
4226   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4227   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4228   // so that the shift + and get folded into a bitfield extract.
4229   SDLoc dl(Op);
4230   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4231                               DAG.getConstant(Intrinsic::arm_get_fpscr, dl,
4232                                               MVT::i32));
4233   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4234                                   DAG.getConstant(1U << 22, dl, MVT::i32));
4235   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4236                               DAG.getConstant(22, dl, MVT::i32));
4237   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4238                      DAG.getConstant(3, dl, MVT::i32));
4239 }
4240
4241 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4242                          const ARMSubtarget *ST) {
4243   EVT VT = N->getValueType(0);
4244   SDLoc dl(N);
4245
4246   if (!ST->hasV6T2Ops())
4247     return SDValue();
4248
4249   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4250   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4251 }
4252
4253 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4254 /// for each 16-bit element from operand, repeated.  The basic idea is to
4255 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4256 ///
4257 /// Trace for v4i16:
4258 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
4259 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4260 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4261 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4262 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
4263 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
4264 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4265 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
4266 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4267   EVT VT = N->getValueType(0);
4268   SDLoc DL(N);
4269
4270   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4271   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4272   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4273   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4274   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4275   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4276 }
4277
4278 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4279 /// bit-count for each 16-bit element from the operand.  We need slightly
4280 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4281 /// 64/128-bit registers.
4282 ///
4283 /// Trace for v4i16:
4284 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
4285 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4286 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
4287 /// v4i16:Extracted = [k0    k1    k2    k3    ]
4288 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4289   EVT VT = N->getValueType(0);
4290   SDLoc DL(N);
4291
4292   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4293   if (VT.is64BitVector()) {
4294     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4295     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4296                        DAG.getIntPtrConstant(0, DL));
4297   } else {
4298     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4299                                     BitCounts, DAG.getIntPtrConstant(0, DL));
4300     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4301   }
4302 }
4303
4304 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4305 /// bit-count for each 32-bit element from the operand.  The idea here is
4306 /// to split the vector into 16-bit elements, leverage the 16-bit count
4307 /// routine, and then combine the results.
4308 ///
4309 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4310 /// input    = [v0    v1    ] (vi: 32-bit elements)
4311 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4312 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4313 /// vrev: N0 = [k1 k0 k3 k2 ]
4314 ///            [k0 k1 k2 k3 ]
4315 ///       N1 =+[k1 k0 k3 k2 ]
4316 ///            [k0 k2 k1 k3 ]
4317 ///       N2 =+[k1 k3 k0 k2 ]
4318 ///            [k0    k2    k1    k3    ]
4319 /// Extended =+[k1    k3    k0    k2    ]
4320 ///            [k0    k2    ]
4321 /// Extracted=+[k1    k3    ]
4322 ///
4323 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4324   EVT VT = N->getValueType(0);
4325   SDLoc DL(N);
4326
4327   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4328
4329   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4330   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4331   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4332   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4333   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4334
4335   if (VT.is64BitVector()) {
4336     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4337     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4338                        DAG.getIntPtrConstant(0, DL));
4339   } else {
4340     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4341                                     DAG.getIntPtrConstant(0, DL));
4342     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4343   }
4344 }
4345
4346 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4347                           const ARMSubtarget *ST) {
4348   EVT VT = N->getValueType(0);
4349
4350   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4351   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4352           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4353          "Unexpected type for custom ctpop lowering");
4354
4355   if (VT.getVectorElementType() == MVT::i32)
4356     return lowerCTPOP32BitElements(N, DAG);
4357   else
4358     return lowerCTPOP16BitElements(N, DAG);
4359 }
4360
4361 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4362                           const ARMSubtarget *ST) {
4363   EVT VT = N->getValueType(0);
4364   SDLoc dl(N);
4365
4366   if (!VT.isVector())
4367     return SDValue();
4368
4369   // Lower vector shifts on NEON to use VSHL.
4370   assert(ST->hasNEON() && "unexpected vector shift");
4371
4372   // Left shifts translate directly to the vshiftu intrinsic.
4373   if (N->getOpcode() == ISD::SHL)
4374     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4375                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
4376                                        MVT::i32),
4377                        N->getOperand(0), N->getOperand(1));
4378
4379   assert((N->getOpcode() == ISD::SRA ||
4380           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4381
4382   // NEON uses the same intrinsics for both left and right shifts.  For
4383   // right shifts, the shift amounts are negative, so negate the vector of
4384   // shift amounts.
4385   EVT ShiftVT = N->getOperand(1).getValueType();
4386   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4387                                      getZeroVector(ShiftVT, DAG, dl),
4388                                      N->getOperand(1));
4389   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4390                              Intrinsic::arm_neon_vshifts :
4391                              Intrinsic::arm_neon_vshiftu);
4392   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4393                      DAG.getConstant(vshiftInt, dl, MVT::i32),
4394                      N->getOperand(0), NegatedCount);
4395 }
4396
4397 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4398                                 const ARMSubtarget *ST) {
4399   EVT VT = N->getValueType(0);
4400   SDLoc dl(N);
4401
4402   // We can get here for a node like i32 = ISD::SHL i32, i64
4403   if (VT != MVT::i64)
4404     return SDValue();
4405
4406   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4407          "Unknown shift to lower!");
4408
4409   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4410   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4411       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4412     return SDValue();
4413
4414   // If we are in thumb mode, we don't have RRX.
4415   if (ST->isThumb1Only()) return SDValue();
4416
4417   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4418   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4419                            DAG.getConstant(0, dl, MVT::i32));
4420   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4421                            DAG.getConstant(1, dl, MVT::i32));
4422
4423   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4424   // captures the result into a carry flag.
4425   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4426   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4427
4428   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4429   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4430
4431   // Merge the pieces into a single i64 value.
4432  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4433 }
4434
4435 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4436   SDValue TmpOp0, TmpOp1;
4437   bool Invert = false;
4438   bool Swap = false;
4439   unsigned Opc = 0;
4440
4441   SDValue Op0 = Op.getOperand(0);
4442   SDValue Op1 = Op.getOperand(1);
4443   SDValue CC = Op.getOperand(2);
4444   EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
4445   EVT VT = Op.getValueType();
4446   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4447   SDLoc dl(Op);
4448
4449   if (Op1.getValueType().isFloatingPoint()) {
4450     switch (SetCCOpcode) {
4451     default: llvm_unreachable("Illegal FP comparison");
4452     case ISD::SETUNE:
4453     case ISD::SETNE:  Invert = true; // Fallthrough
4454     case ISD::SETOEQ:
4455     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4456     case ISD::SETOLT:
4457     case ISD::SETLT: Swap = true; // Fallthrough
4458     case ISD::SETOGT:
4459     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4460     case ISD::SETOLE:
4461     case ISD::SETLE:  Swap = true; // Fallthrough
4462     case ISD::SETOGE:
4463     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4464     case ISD::SETUGE: Swap = true; // Fallthrough
4465     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4466     case ISD::SETUGT: Swap = true; // Fallthrough
4467     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4468     case ISD::SETUEQ: Invert = true; // Fallthrough
4469     case ISD::SETONE:
4470       // Expand this to (OLT | OGT).
4471       TmpOp0 = Op0;
4472       TmpOp1 = Op1;
4473       Opc = ISD::OR;
4474       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4475       Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
4476       break;
4477     case ISD::SETUO: Invert = true; // Fallthrough
4478     case ISD::SETO:
4479       // Expand this to (OLT | OGE).
4480       TmpOp0 = Op0;
4481       TmpOp1 = Op1;
4482       Opc = ISD::OR;
4483       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4484       Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
4485       break;
4486     }
4487   } else {
4488     // Integer comparisons.
4489     switch (SetCCOpcode) {
4490     default: llvm_unreachable("Illegal integer comparison");
4491     case ISD::SETNE:  Invert = true;
4492     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4493     case ISD::SETLT:  Swap = true;
4494     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4495     case ISD::SETLE:  Swap = true;
4496     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4497     case ISD::SETULT: Swap = true;
4498     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4499     case ISD::SETULE: Swap = true;
4500     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4501     }
4502
4503     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4504     if (Opc == ARMISD::VCEQ) {
4505
4506       SDValue AndOp;
4507       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4508         AndOp = Op0;
4509       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4510         AndOp = Op1;
4511
4512       // Ignore bitconvert.
4513       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4514         AndOp = AndOp.getOperand(0);
4515
4516       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4517         Opc = ARMISD::VTST;
4518         Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
4519         Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
4520         Invert = !Invert;
4521       }
4522     }
4523   }
4524
4525   if (Swap)
4526     std::swap(Op0, Op1);
4527
4528   // If one of the operands is a constant vector zero, attempt to fold the
4529   // comparison to a specialized compare-against-zero form.
4530   SDValue SingleOp;
4531   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4532     SingleOp = Op0;
4533   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4534     if (Opc == ARMISD::VCGE)
4535       Opc = ARMISD::VCLEZ;
4536     else if (Opc == ARMISD::VCGT)
4537       Opc = ARMISD::VCLTZ;
4538     SingleOp = Op1;
4539   }
4540
4541   SDValue Result;
4542   if (SingleOp.getNode()) {
4543     switch (Opc) {
4544     case ARMISD::VCEQ:
4545       Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
4546     case ARMISD::VCGE:
4547       Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
4548     case ARMISD::VCLEZ:
4549       Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
4550     case ARMISD::VCGT:
4551       Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
4552     case ARMISD::VCLTZ:
4553       Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
4554     default:
4555       Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4556     }
4557   } else {
4558      Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4559   }
4560
4561   Result = DAG.getSExtOrTrunc(Result, dl, VT);
4562
4563   if (Invert)
4564     Result = DAG.getNOT(dl, Result, VT);
4565
4566   return Result;
4567 }
4568
4569 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4570 /// valid vector constant for a NEON instruction with a "modified immediate"
4571 /// operand (e.g., VMOV).  If so, return the encoded value.
4572 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4573                                  unsigned SplatBitSize, SelectionDAG &DAG,
4574                                  SDLoc dl, EVT &VT, bool is128Bits,
4575                                  NEONModImmType type) {
4576   unsigned OpCmode, Imm;
4577
4578   // SplatBitSize is set to the smallest size that splats the vector, so a
4579   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4580   // immediate instructions others than VMOV do not support the 8-bit encoding
4581   // of a zero vector, and the default encoding of zero is supposed to be the
4582   // 32-bit version.
4583   if (SplatBits == 0)
4584     SplatBitSize = 32;
4585
4586   switch (SplatBitSize) {
4587   case 8:
4588     if (type != VMOVModImm)
4589       return SDValue();
4590     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4591     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4592     OpCmode = 0xe;
4593     Imm = SplatBits;
4594     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4595     break;
4596
4597   case 16:
4598     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4599     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4600     if ((SplatBits & ~0xff) == 0) {
4601       // Value = 0x00nn: Op=x, Cmode=100x.
4602       OpCmode = 0x8;
4603       Imm = SplatBits;
4604       break;
4605     }
4606     if ((SplatBits & ~0xff00) == 0) {
4607       // Value = 0xnn00: Op=x, Cmode=101x.
4608       OpCmode = 0xa;
4609       Imm = SplatBits >> 8;
4610       break;
4611     }
4612     return SDValue();
4613
4614   case 32:
4615     // NEON's 32-bit VMOV supports splat values where:
4616     // * only one byte is nonzero, or
4617     // * the least significant byte is 0xff and the second byte is nonzero, or
4618     // * the least significant 2 bytes are 0xff and the third is nonzero.
4619     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4620     if ((SplatBits & ~0xff) == 0) {
4621       // Value = 0x000000nn: Op=x, Cmode=000x.
4622       OpCmode = 0;
4623       Imm = SplatBits;
4624       break;
4625     }
4626     if ((SplatBits & ~0xff00) == 0) {
4627       // Value = 0x0000nn00: Op=x, Cmode=001x.
4628       OpCmode = 0x2;
4629       Imm = SplatBits >> 8;
4630       break;
4631     }
4632     if ((SplatBits & ~0xff0000) == 0) {
4633       // Value = 0x00nn0000: Op=x, Cmode=010x.
4634       OpCmode = 0x4;
4635       Imm = SplatBits >> 16;
4636       break;
4637     }
4638     if ((SplatBits & ~0xff000000) == 0) {
4639       // Value = 0xnn000000: Op=x, Cmode=011x.
4640       OpCmode = 0x6;
4641       Imm = SplatBits >> 24;
4642       break;
4643     }
4644
4645     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4646     if (type == OtherModImm) return SDValue();
4647
4648     if ((SplatBits & ~0xffff) == 0 &&
4649         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4650       // Value = 0x0000nnff: Op=x, Cmode=1100.
4651       OpCmode = 0xc;
4652       Imm = SplatBits >> 8;
4653       break;
4654     }
4655
4656     if ((SplatBits & ~0xffffff) == 0 &&
4657         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4658       // Value = 0x00nnffff: Op=x, Cmode=1101.
4659       OpCmode = 0xd;
4660       Imm = SplatBits >> 16;
4661       break;
4662     }
4663
4664     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4665     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4666     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4667     // and fall through here to test for a valid 64-bit splat.  But, then the
4668     // caller would also need to check and handle the change in size.
4669     return SDValue();
4670
4671   case 64: {
4672     if (type != VMOVModImm)
4673       return SDValue();
4674     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4675     uint64_t BitMask = 0xff;
4676     uint64_t Val = 0;
4677     unsigned ImmMask = 1;
4678     Imm = 0;
4679     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4680       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4681         Val |= BitMask;
4682         Imm |= ImmMask;
4683       } else if ((SplatBits & BitMask) != 0) {
4684         return SDValue();
4685       }
4686       BitMask <<= 8;
4687       ImmMask <<= 1;
4688     }
4689
4690     if (DAG.getTargetLoweringInfo().isBigEndian())
4691       // swap higher and lower 32 bit word
4692       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4693
4694     // Op=1, Cmode=1110.
4695     OpCmode = 0x1e;
4696     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4697     break;
4698   }
4699
4700   default:
4701     llvm_unreachable("unexpected size for isNEONModifiedImm");
4702   }
4703
4704   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4705   return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
4706 }
4707
4708 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4709                                            const ARMSubtarget *ST) const {
4710   if (!ST->hasVFP3())
4711     return SDValue();
4712
4713   bool IsDouble = Op.getValueType() == MVT::f64;
4714   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4715
4716   // Use the default (constant pool) lowering for double constants when we have
4717   // an SP-only FPU
4718   if (IsDouble && Subtarget->isFPOnlySP())
4719     return SDValue();
4720
4721   // Try splatting with a VMOV.f32...
4722   APFloat FPVal = CFP->getValueAPF();
4723   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4724
4725   if (ImmVal != -1) {
4726     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4727       // We have code in place to select a valid ConstantFP already, no need to
4728       // do any mangling.
4729       return Op;
4730     }
4731
4732     // It's a float and we are trying to use NEON operations where
4733     // possible. Lower it to a splat followed by an extract.
4734     SDLoc DL(Op);
4735     SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
4736     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4737                                       NewVal);
4738     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4739                        DAG.getConstant(0, DL, MVT::i32));
4740   }
4741
4742   // The rest of our options are NEON only, make sure that's allowed before
4743   // proceeding..
4744   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4745     return SDValue();
4746
4747   EVT VMovVT;
4748   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4749
4750   // It wouldn't really be worth bothering for doubles except for one very
4751   // important value, which does happen to match: 0.0. So make sure we don't do
4752   // anything stupid.
4753   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4754     return SDValue();
4755
4756   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4757   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
4758                                      VMovVT, false, VMOVModImm);
4759   if (NewVal != SDValue()) {
4760     SDLoc DL(Op);
4761     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4762                                       NewVal);
4763     if (IsDouble)
4764       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4765
4766     // It's a float: cast and extract a vector element.
4767     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4768                                        VecConstant);
4769     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4770                        DAG.getConstant(0, DL, MVT::i32));
4771   }
4772
4773   // Finally, try a VMVN.i32
4774   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
4775                              false, VMVNModImm);
4776   if (NewVal != SDValue()) {
4777     SDLoc DL(Op);
4778     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4779
4780     if (IsDouble)
4781       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4782
4783     // It's a float: cast and extract a vector element.
4784     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4785                                        VecConstant);
4786     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4787                        DAG.getConstant(0, DL, MVT::i32));
4788   }
4789
4790   return SDValue();
4791 }
4792
4793 // check if an VEXT instruction can handle the shuffle mask when the
4794 // vector sources of the shuffle are the same.
4795 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4796   unsigned NumElts = VT.getVectorNumElements();
4797
4798   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4799   if (M[0] < 0)
4800     return false;
4801
4802   Imm = M[0];
4803
4804   // If this is a VEXT shuffle, the immediate value is the index of the first
4805   // element.  The other shuffle indices must be the successive elements after
4806   // the first one.
4807   unsigned ExpectedElt = Imm;
4808   for (unsigned i = 1; i < NumElts; ++i) {
4809     // Increment the expected index.  If it wraps around, just follow it
4810     // back to index zero and keep going.
4811     ++ExpectedElt;
4812     if (ExpectedElt == NumElts)
4813       ExpectedElt = 0;
4814
4815     if (M[i] < 0) continue; // ignore UNDEF indices
4816     if (ExpectedElt != static_cast<unsigned>(M[i]))
4817       return false;
4818   }
4819
4820   return true;
4821 }
4822
4823
4824 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4825                        bool &ReverseVEXT, unsigned &Imm) {
4826   unsigned NumElts = VT.getVectorNumElements();
4827   ReverseVEXT = false;
4828
4829   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4830   if (M[0] < 0)
4831     return false;
4832
4833   Imm = M[0];
4834
4835   // If this is a VEXT shuffle, the immediate value is the index of the first
4836   // element.  The other shuffle indices must be the successive elements after
4837   // the first one.
4838   unsigned ExpectedElt = Imm;
4839   for (unsigned i = 1; i < NumElts; ++i) {
4840     // Increment the expected index.  If it wraps around, it may still be
4841     // a VEXT but the source vectors must be swapped.
4842     ExpectedElt += 1;
4843     if (ExpectedElt == NumElts * 2) {
4844       ExpectedElt = 0;
4845       ReverseVEXT = true;
4846     }
4847
4848     if (M[i] < 0) continue; // ignore UNDEF indices
4849     if (ExpectedElt != static_cast<unsigned>(M[i]))
4850       return false;
4851   }
4852
4853   // Adjust the index value if the source operands will be swapped.
4854   if (ReverseVEXT)
4855     Imm -= NumElts;
4856
4857   return true;
4858 }
4859
4860 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4861 /// instruction with the specified blocksize.  (The order of the elements
4862 /// within each block of the vector is reversed.)
4863 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4864   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4865          "Only possible block sizes for VREV are: 16, 32, 64");
4866
4867   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4868   if (EltSz == 64)
4869     return false;
4870
4871   unsigned NumElts = VT.getVectorNumElements();
4872   unsigned BlockElts = M[0] + 1;
4873   // If the first shuffle index is UNDEF, be optimistic.
4874   if (M[0] < 0)
4875     BlockElts = BlockSize / EltSz;
4876
4877   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4878     return false;
4879
4880   for (unsigned i = 0; i < NumElts; ++i) {
4881     if (M[i] < 0) continue; // ignore UNDEF indices
4882     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4883       return false;
4884   }
4885
4886   return true;
4887 }
4888
4889 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4890   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4891   // range, then 0 is placed into the resulting vector. So pretty much any mask
4892   // of 8 elements can work here.
4893   return VT == MVT::v8i8 && M.size() == 8;
4894 }
4895
4896 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4897   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4898   if (EltSz == 64)
4899     return false;
4900
4901   unsigned NumElts = VT.getVectorNumElements();
4902   WhichResult = (M[0] == 0 ? 0 : 1);
4903   for (unsigned i = 0; i < NumElts; i += 2) {
4904     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4905         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4906       return false;
4907   }
4908   return true;
4909 }
4910
4911 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4912 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4913 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4914 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4915   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4916   if (EltSz == 64)
4917     return false;
4918
4919   unsigned NumElts = VT.getVectorNumElements();
4920   WhichResult = (M[0] == 0 ? 0 : 1);
4921   for (unsigned i = 0; i < NumElts; i += 2) {
4922     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4923         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4924       return false;
4925   }
4926   return true;
4927 }
4928
4929 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4930   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4931   if (EltSz == 64)
4932     return false;
4933
4934   unsigned NumElts = VT.getVectorNumElements();
4935   WhichResult = (M[0] == 0 ? 0 : 1);
4936   for (unsigned i = 0; i != NumElts; ++i) {
4937     if (M[i] < 0) continue; // ignore UNDEF indices
4938     if ((unsigned) M[i] != 2 * i + WhichResult)
4939       return false;
4940   }
4941
4942   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4943   if (VT.is64BitVector() && EltSz == 32)
4944     return false;
4945
4946   return true;
4947 }
4948
4949 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4950 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4951 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4952 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4953   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4954   if (EltSz == 64)
4955     return false;
4956
4957   unsigned Half = VT.getVectorNumElements() / 2;
4958   WhichResult = (M[0] == 0 ? 0 : 1);
4959   for (unsigned j = 0; j != 2; ++j) {
4960     unsigned Idx = WhichResult;
4961     for (unsigned i = 0; i != Half; ++i) {
4962       int MIdx = M[i + j * Half];
4963       if (MIdx >= 0 && (unsigned) MIdx != Idx)
4964         return false;
4965       Idx += 2;
4966     }
4967   }
4968
4969   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4970   if (VT.is64BitVector() && EltSz == 32)
4971     return false;
4972
4973   return true;
4974 }
4975
4976 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4977   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4978   if (EltSz == 64)
4979     return false;
4980
4981   unsigned NumElts = VT.getVectorNumElements();
4982   WhichResult = (M[0] == 0 ? 0 : 1);
4983   unsigned Idx = WhichResult * NumElts / 2;
4984   for (unsigned i = 0; i != NumElts; i += 2) {
4985     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4986         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4987       return false;
4988     Idx += 1;
4989   }
4990
4991   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4992   if (VT.is64BitVector() && EltSz == 32)
4993     return false;
4994
4995   return true;
4996 }
4997
4998 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4999 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5000 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5001 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5002   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5003   if (EltSz == 64)
5004     return false;
5005
5006   unsigned NumElts = VT.getVectorNumElements();
5007   WhichResult = (M[0] == 0 ? 0 : 1);
5008   unsigned Idx = WhichResult * NumElts / 2;
5009   for (unsigned i = 0; i != NumElts; i += 2) {
5010     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
5011         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
5012       return false;
5013     Idx += 1;
5014   }
5015
5016   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5017   if (VT.is64BitVector() && EltSz == 32)
5018     return false;
5019
5020   return true;
5021 }
5022
5023 /// \return true if this is a reverse operation on an vector.
5024 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5025   unsigned NumElts = VT.getVectorNumElements();
5026   // Make sure the mask has the right size.
5027   if (NumElts != M.size())
5028       return false;
5029
5030   // Look for <15, ..., 3, -1, 1, 0>.
5031   for (unsigned i = 0; i != NumElts; ++i)
5032     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5033       return false;
5034
5035   return true;
5036 }
5037
5038 // If N is an integer constant that can be moved into a register in one
5039 // instruction, return an SDValue of such a constant (will become a MOV
5040 // instruction).  Otherwise return null.
5041 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5042                                      const ARMSubtarget *ST, SDLoc dl) {
5043   uint64_t Val;
5044   if (!isa<ConstantSDNode>(N))
5045     return SDValue();
5046   Val = cast<ConstantSDNode>(N)->getZExtValue();
5047
5048   if (ST->isThumb1Only()) {
5049     if (Val <= 255 || ~Val <= 255)
5050       return DAG.getConstant(Val, dl, MVT::i32);
5051   } else {
5052     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5053       return DAG.getConstant(Val, dl, MVT::i32);
5054   }
5055   return SDValue();
5056 }
5057
5058 // If this is a case we can't handle, return null and let the default
5059 // expansion code take care of it.
5060 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5061                                              const ARMSubtarget *ST) const {
5062   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5063   SDLoc dl(Op);
5064   EVT VT = Op.getValueType();
5065
5066   APInt SplatBits, SplatUndef;
5067   unsigned SplatBitSize;
5068   bool HasAnyUndefs;
5069   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5070     if (SplatBitSize <= 64) {
5071       // Check if an immediate VMOV works.
5072       EVT VmovVT;
5073       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5074                                       SplatUndef.getZExtValue(), SplatBitSize,
5075                                       DAG, dl, VmovVT, VT.is128BitVector(),
5076                                       VMOVModImm);
5077       if (Val.getNode()) {
5078         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5079         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5080       }
5081
5082       // Try an immediate VMVN.
5083       uint64_t NegatedImm = (~SplatBits).getZExtValue();
5084       Val = isNEONModifiedImm(NegatedImm,
5085                                       SplatUndef.getZExtValue(), SplatBitSize,
5086                                       DAG, dl, VmovVT, VT.is128BitVector(),
5087                                       VMVNModImm);
5088       if (Val.getNode()) {
5089         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5090         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5091       }
5092
5093       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5094       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5095         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5096         if (ImmVal != -1) {
5097           SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
5098           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5099         }
5100       }
5101     }
5102   }
5103
5104   // Scan through the operands to see if only one value is used.
5105   //
5106   // As an optimisation, even if more than one value is used it may be more
5107   // profitable to splat with one value then change some lanes.
5108   //
5109   // Heuristically we decide to do this if the vector has a "dominant" value,
5110   // defined as splatted to more than half of the lanes.
5111   unsigned NumElts = VT.getVectorNumElements();
5112   bool isOnlyLowElement = true;
5113   bool usesOnlyOneValue = true;
5114   bool hasDominantValue = false;
5115   bool isConstant = true;
5116
5117   // Map of the number of times a particular SDValue appears in the
5118   // element list.
5119   DenseMap<SDValue, unsigned> ValueCounts;
5120   SDValue Value;
5121   for (unsigned i = 0; i < NumElts; ++i) {
5122     SDValue V = Op.getOperand(i);
5123     if (V.getOpcode() == ISD::UNDEF)
5124       continue;
5125     if (i > 0)
5126       isOnlyLowElement = false;
5127     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5128       isConstant = false;
5129
5130     ValueCounts.insert(std::make_pair(V, 0));
5131     unsigned &Count = ValueCounts[V];
5132
5133     // Is this value dominant? (takes up more than half of the lanes)
5134     if (++Count > (NumElts / 2)) {
5135       hasDominantValue = true;
5136       Value = V;
5137     }
5138   }
5139   if (ValueCounts.size() != 1)
5140     usesOnlyOneValue = false;
5141   if (!Value.getNode() && ValueCounts.size() > 0)
5142     Value = ValueCounts.begin()->first;
5143
5144   if (ValueCounts.size() == 0)
5145     return DAG.getUNDEF(VT);
5146
5147   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5148   // Keep going if we are hitting this case.
5149   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5150     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5151
5152   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5153
5154   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
5155   // i32 and try again.
5156   if (hasDominantValue && EltSize <= 32) {
5157     if (!isConstant) {
5158       SDValue N;
5159
5160       // If we are VDUPing a value that comes directly from a vector, that will
5161       // cause an unnecessary move to and from a GPR, where instead we could
5162       // just use VDUPLANE. We can only do this if the lane being extracted
5163       // is at a constant index, as the VDUP from lane instructions only have
5164       // constant-index forms.
5165       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5166           isa<ConstantSDNode>(Value->getOperand(1))) {
5167         // We need to create a new undef vector to use for the VDUPLANE if the
5168         // size of the vector from which we get the value is different than the
5169         // size of the vector that we need to create. We will insert the element
5170         // such that the register coalescer will remove unnecessary copies.
5171         if (VT != Value->getOperand(0).getValueType()) {
5172           ConstantSDNode *constIndex;
5173           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5174           assert(constIndex && "The index is not a constant!");
5175           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5176                              VT.getVectorNumElements();
5177           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5178                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5179                         Value, DAG.getConstant(index, dl, MVT::i32)),
5180                            DAG.getConstant(index, dl, MVT::i32));
5181         } else
5182           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5183                         Value->getOperand(0), Value->getOperand(1));
5184       } else
5185         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5186
5187       if (!usesOnlyOneValue) {
5188         // The dominant value was splatted as 'N', but we now have to insert
5189         // all differing elements.
5190         for (unsigned I = 0; I < NumElts; ++I) {
5191           if (Op.getOperand(I) == Value)
5192             continue;
5193           SmallVector<SDValue, 3> Ops;
5194           Ops.push_back(N);
5195           Ops.push_back(Op.getOperand(I));
5196           Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
5197           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5198         }
5199       }
5200       return N;
5201     }
5202     if (VT.getVectorElementType().isFloatingPoint()) {
5203       SmallVector<SDValue, 8> Ops;
5204       for (unsigned i = 0; i < NumElts; ++i)
5205         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5206                                   Op.getOperand(i)));
5207       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5208       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5209       Val = LowerBUILD_VECTOR(Val, DAG, ST);
5210       if (Val.getNode())
5211         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5212     }
5213     if (usesOnlyOneValue) {
5214       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5215       if (isConstant && Val.getNode())
5216         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5217     }
5218   }
5219
5220   // If all elements are constants and the case above didn't get hit, fall back
5221   // to the default expansion, which will generate a load from the constant
5222   // pool.
5223   if (isConstant)
5224     return SDValue();
5225
5226   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5227   if (NumElts >= 4) {
5228     SDValue shuffle = ReconstructShuffle(Op, DAG);
5229     if (shuffle != SDValue())
5230       return shuffle;
5231   }
5232
5233   // Vectors with 32- or 64-bit elements can be built by directly assigning
5234   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
5235   // will be legalized.
5236   if (EltSize >= 32) {
5237     // Do the expansion with floating-point types, since that is what the VFP
5238     // registers are defined to use, and since i64 is not legal.
5239     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5240     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5241     SmallVector<SDValue, 8> Ops;
5242     for (unsigned i = 0; i < NumElts; ++i)
5243       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5244     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5245     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5246   }
5247
5248   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5249   // know the default expansion would otherwise fall back on something even
5250   // worse. For a vector with one or two non-undef values, that's
5251   // scalar_to_vector for the elements followed by a shuffle (provided the
5252   // shuffle is valid for the target) and materialization element by element
5253   // on the stack followed by a load for everything else.
5254   if (!isConstant && !usesOnlyOneValue) {
5255     SDValue Vec = DAG.getUNDEF(VT);
5256     for (unsigned i = 0 ; i < NumElts; ++i) {
5257       SDValue V = Op.getOperand(i);
5258       if (V.getOpcode() == ISD::UNDEF)
5259         continue;
5260       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
5261       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5262     }
5263     return Vec;
5264   }
5265
5266   return SDValue();
5267 }
5268
5269 // Gather data to see if the operation can be modelled as a
5270 // shuffle in combination with VEXTs.
5271 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5272                                               SelectionDAG &DAG) const {
5273   SDLoc dl(Op);
5274   EVT VT = Op.getValueType();
5275   unsigned NumElts = VT.getVectorNumElements();
5276
5277   SmallVector<SDValue, 2> SourceVecs;
5278   SmallVector<unsigned, 2> MinElts;
5279   SmallVector<unsigned, 2> MaxElts;
5280
5281   for (unsigned i = 0; i < NumElts; ++i) {
5282     SDValue V = Op.getOperand(i);
5283     if (V.getOpcode() == ISD::UNDEF)
5284       continue;
5285     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5286       // A shuffle can only come from building a vector from various
5287       // elements of other vectors.
5288       return SDValue();
5289     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5290                VT.getVectorElementType()) {
5291       // This code doesn't know how to handle shuffles where the vector
5292       // element types do not match (this happens because type legalization
5293       // promotes the return type of EXTRACT_VECTOR_ELT).
5294       // FIXME: It might be appropriate to extend this code to handle
5295       // mismatched types.
5296       return SDValue();
5297     }
5298
5299     // Record this extraction against the appropriate vector if possible...
5300     SDValue SourceVec = V.getOperand(0);
5301     // If the element number isn't a constant, we can't effectively
5302     // analyze what's going on.
5303     if (!isa<ConstantSDNode>(V.getOperand(1)))
5304       return SDValue();
5305     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5306     bool FoundSource = false;
5307     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5308       if (SourceVecs[j] == SourceVec) {
5309         if (MinElts[j] > EltNo)
5310           MinElts[j] = EltNo;
5311         if (MaxElts[j] < EltNo)
5312           MaxElts[j] = EltNo;
5313         FoundSource = true;
5314         break;
5315       }
5316     }
5317
5318     // Or record a new source if not...
5319     if (!FoundSource) {
5320       SourceVecs.push_back(SourceVec);
5321       MinElts.push_back(EltNo);
5322       MaxElts.push_back(EltNo);
5323     }
5324   }
5325
5326   // Currently only do something sane when at most two source vectors
5327   // involved.
5328   if (SourceVecs.size() > 2)
5329     return SDValue();
5330
5331   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5332   int VEXTOffsets[2] = {0, 0};
5333
5334   // This loop extracts the usage patterns of the source vectors
5335   // and prepares appropriate SDValues for a shuffle if possible.
5336   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5337     if (SourceVecs[i].getValueType() == VT) {
5338       // No VEXT necessary
5339       ShuffleSrcs[i] = SourceVecs[i];
5340       VEXTOffsets[i] = 0;
5341       continue;
5342     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5343       // It probably isn't worth padding out a smaller vector just to
5344       // break it down again in a shuffle.
5345       return SDValue();
5346     }
5347
5348     // Since only 64-bit and 128-bit vectors are legal on ARM and
5349     // we've eliminated the other cases...
5350     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5351            "unexpected vector sizes in ReconstructShuffle");
5352
5353     if (MaxElts[i] - MinElts[i] >= NumElts) {
5354       // Span too large for a VEXT to cope
5355       return SDValue();
5356     }
5357
5358     if (MinElts[i] >= NumElts) {
5359       // The extraction can just take the second half
5360       VEXTOffsets[i] = NumElts;
5361       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5362                                    SourceVecs[i],
5363                                    DAG.getIntPtrConstant(NumElts, dl));
5364     } else if (MaxElts[i] < NumElts) {
5365       // The extraction can just take the first half
5366       VEXTOffsets[i] = 0;
5367       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5368                                    SourceVecs[i],
5369                                    DAG.getIntPtrConstant(0, dl));
5370     } else {
5371       // An actual VEXT is needed
5372       VEXTOffsets[i] = MinElts[i];
5373       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5374                                      SourceVecs[i],
5375                                      DAG.getIntPtrConstant(0, dl));
5376       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5377                                      SourceVecs[i],
5378                                      DAG.getIntPtrConstant(NumElts, dl));
5379       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5380                                    DAG.getConstant(VEXTOffsets[i], dl,
5381                                                    MVT::i32));
5382     }
5383   }
5384
5385   SmallVector<int, 8> Mask;
5386
5387   for (unsigned i = 0; i < NumElts; ++i) {
5388     SDValue Entry = Op.getOperand(i);
5389     if (Entry.getOpcode() == ISD::UNDEF) {
5390       Mask.push_back(-1);
5391       continue;
5392     }
5393
5394     SDValue ExtractVec = Entry.getOperand(0);
5395     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5396                                           .getOperand(1))->getSExtValue();
5397     if (ExtractVec == SourceVecs[0]) {
5398       Mask.push_back(ExtractElt - VEXTOffsets[0]);
5399     } else {
5400       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5401     }
5402   }
5403
5404   // Final check before we try to produce nonsense...
5405   if (isShuffleMaskLegal(Mask, VT))
5406     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5407                                 &Mask[0]);
5408
5409   return SDValue();
5410 }
5411
5412 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5413 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5414 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5415 /// are assumed to be legal.
5416 bool
5417 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5418                                       EVT VT) const {
5419   if (VT.getVectorNumElements() == 4 &&
5420       (VT.is128BitVector() || VT.is64BitVector())) {
5421     unsigned PFIndexes[4];
5422     for (unsigned i = 0; i != 4; ++i) {
5423       if (M[i] < 0)
5424         PFIndexes[i] = 8;
5425       else
5426         PFIndexes[i] = M[i];
5427     }
5428
5429     // Compute the index in the perfect shuffle table.
5430     unsigned PFTableIndex =
5431       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5432     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5433     unsigned Cost = (PFEntry >> 30);
5434
5435     if (Cost <= 4)
5436       return true;
5437   }
5438
5439   bool ReverseVEXT;
5440   unsigned Imm, WhichResult;
5441
5442   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5443   return (EltSize >= 32 ||
5444           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5445           isVREVMask(M, VT, 64) ||
5446           isVREVMask(M, VT, 32) ||
5447           isVREVMask(M, VT, 16) ||
5448           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5449           isVTBLMask(M, VT) ||
5450           isVTRNMask(M, VT, WhichResult) ||
5451           isVUZPMask(M, VT, WhichResult) ||
5452           isVZIPMask(M, VT, WhichResult) ||
5453           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5454           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5455           isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5456           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5457 }
5458
5459 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5460 /// the specified operations to build the shuffle.
5461 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5462                                       SDValue RHS, SelectionDAG &DAG,
5463                                       SDLoc dl) {
5464   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5465   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5466   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5467
5468   enum {
5469     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5470     OP_VREV,
5471     OP_VDUP0,
5472     OP_VDUP1,
5473     OP_VDUP2,
5474     OP_VDUP3,
5475     OP_VEXT1,
5476     OP_VEXT2,
5477     OP_VEXT3,
5478     OP_VUZPL, // VUZP, left result
5479     OP_VUZPR, // VUZP, right result
5480     OP_VZIPL, // VZIP, left result
5481     OP_VZIPR, // VZIP, right result
5482     OP_VTRNL, // VTRN, left result
5483     OP_VTRNR  // VTRN, right result
5484   };
5485
5486   if (OpNum == OP_COPY) {
5487     if (LHSID == (1*9+2)*9+3) return LHS;
5488     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5489     return RHS;
5490   }
5491
5492   SDValue OpLHS, OpRHS;
5493   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5494   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5495   EVT VT = OpLHS.getValueType();
5496
5497   switch (OpNum) {
5498   default: llvm_unreachable("Unknown shuffle opcode!");
5499   case OP_VREV:
5500     // VREV divides the vector in half and swaps within the half.
5501     if (VT.getVectorElementType() == MVT::i32 ||
5502         VT.getVectorElementType() == MVT::f32)
5503       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5504     // vrev <4 x i16> -> VREV32
5505     if (VT.getVectorElementType() == MVT::i16)
5506       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5507     // vrev <4 x i8> -> VREV16
5508     assert(VT.getVectorElementType() == MVT::i8);
5509     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5510   case OP_VDUP0:
5511   case OP_VDUP1:
5512   case OP_VDUP2:
5513   case OP_VDUP3:
5514     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5515                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
5516   case OP_VEXT1:
5517   case OP_VEXT2:
5518   case OP_VEXT3:
5519     return DAG.getNode(ARMISD::VEXT, dl, VT,
5520                        OpLHS, OpRHS,
5521                        DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
5522   case OP_VUZPL:
5523   case OP_VUZPR:
5524     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5525                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5526   case OP_VZIPL:
5527   case OP_VZIPR:
5528     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5529                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5530   case OP_VTRNL:
5531   case OP_VTRNR:
5532     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5533                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5534   }
5535 }
5536
5537 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5538                                        ArrayRef<int> ShuffleMask,
5539                                        SelectionDAG &DAG) {
5540   // Check to see if we can use the VTBL instruction.
5541   SDValue V1 = Op.getOperand(0);
5542   SDValue V2 = Op.getOperand(1);
5543   SDLoc DL(Op);
5544
5545   SmallVector<SDValue, 8> VTBLMask;
5546   for (ArrayRef<int>::iterator
5547          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5548     VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
5549
5550   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5551     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5552                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5553
5554   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5555                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5556 }
5557
5558 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5559                                                       SelectionDAG &DAG) {
5560   SDLoc DL(Op);
5561   SDValue OpLHS = Op.getOperand(0);
5562   EVT VT = OpLHS.getValueType();
5563
5564   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5565          "Expect an v8i16/v16i8 type");
5566   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5567   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5568   // extract the first 8 bytes into the top double word and the last 8 bytes
5569   // into the bottom double word. The v8i16 case is similar.
5570   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5571   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5572                      DAG.getConstant(ExtractNum, DL, MVT::i32));
5573 }
5574
5575 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5576   SDValue V1 = Op.getOperand(0);
5577   SDValue V2 = Op.getOperand(1);
5578   SDLoc dl(Op);
5579   EVT VT = Op.getValueType();
5580   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5581
5582   // Convert shuffles that are directly supported on NEON to target-specific
5583   // DAG nodes, instead of keeping them as shuffles and matching them again
5584   // during code selection.  This is more efficient and avoids the possibility
5585   // of inconsistencies between legalization and selection.
5586   // FIXME: floating-point vectors should be canonicalized to integer vectors
5587   // of the same time so that they get CSEd properly.
5588   ArrayRef<int> ShuffleMask = SVN->getMask();
5589
5590   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5591   if (EltSize <= 32) {
5592     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5593       int Lane = SVN->getSplatIndex();
5594       // If this is undef splat, generate it via "just" vdup, if possible.
5595       if (Lane == -1) Lane = 0;
5596
5597       // Test if V1 is a SCALAR_TO_VECTOR.
5598       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5599         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5600       }
5601       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5602       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5603       // reaches it).
5604       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5605           !isa<ConstantSDNode>(V1.getOperand(0))) {
5606         bool IsScalarToVector = true;
5607         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5608           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5609             IsScalarToVector = false;
5610             break;
5611           }
5612         if (IsScalarToVector)
5613           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5614       }
5615       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5616                          DAG.getConstant(Lane, dl, MVT::i32));
5617     }
5618
5619     bool ReverseVEXT;
5620     unsigned Imm;
5621     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5622       if (ReverseVEXT)
5623         std::swap(V1, V2);
5624       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5625                          DAG.getConstant(Imm, dl, MVT::i32));
5626     }
5627
5628     if (isVREVMask(ShuffleMask, VT, 64))
5629       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5630     if (isVREVMask(ShuffleMask, VT, 32))
5631       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5632     if (isVREVMask(ShuffleMask, VT, 16))
5633       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5634
5635     if (V2->getOpcode() == ISD::UNDEF &&
5636         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5637       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5638                          DAG.getConstant(Imm, dl, MVT::i32));
5639     }
5640
5641     // Check for Neon shuffles that modify both input vectors in place.
5642     // If both results are used, i.e., if there are two shuffles with the same
5643     // source operands and with masks corresponding to both results of one of
5644     // these operations, DAG memoization will ensure that a single node is
5645     // used for both shuffles.
5646     unsigned WhichResult;
5647     if (isVTRNMask(ShuffleMask, VT, WhichResult))
5648       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5649                          V1, V2).getValue(WhichResult);
5650     if (isVUZPMask(ShuffleMask, VT, WhichResult))
5651       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5652                          V1, V2).getValue(WhichResult);
5653     if (isVZIPMask(ShuffleMask, VT, WhichResult))
5654       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5655                          V1, V2).getValue(WhichResult);
5656
5657     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5658       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5659                          V1, V1).getValue(WhichResult);
5660     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5661       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5662                          V1, V1).getValue(WhichResult);
5663     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5664       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5665                          V1, V1).getValue(WhichResult);
5666   }
5667
5668   // If the shuffle is not directly supported and it has 4 elements, use
5669   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5670   unsigned NumElts = VT.getVectorNumElements();
5671   if (NumElts == 4) {
5672     unsigned PFIndexes[4];
5673     for (unsigned i = 0; i != 4; ++i) {
5674       if (ShuffleMask[i] < 0)
5675         PFIndexes[i] = 8;
5676       else
5677         PFIndexes[i] = ShuffleMask[i];
5678     }
5679
5680     // Compute the index in the perfect shuffle table.
5681     unsigned PFTableIndex =
5682       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5683     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5684     unsigned Cost = (PFEntry >> 30);
5685
5686     if (Cost <= 4)
5687       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5688   }
5689
5690   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5691   if (EltSize >= 32) {
5692     // Do the expansion with floating-point types, since that is what the VFP
5693     // registers are defined to use, and since i64 is not legal.
5694     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5695     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5696     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5697     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5698     SmallVector<SDValue, 8> Ops;
5699     for (unsigned i = 0; i < NumElts; ++i) {
5700       if (ShuffleMask[i] < 0)
5701         Ops.push_back(DAG.getUNDEF(EltVT));
5702       else
5703         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5704                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
5705                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5706                                                   dl, MVT::i32)));
5707     }
5708     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5709     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5710   }
5711
5712   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5713     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5714
5715   if (VT == MVT::v8i8) {
5716     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5717     if (NewOp.getNode())
5718       return NewOp;
5719   }
5720
5721   return SDValue();
5722 }
5723
5724 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5725   // INSERT_VECTOR_ELT is legal only for immediate indexes.
5726   SDValue Lane = Op.getOperand(2);
5727   if (!isa<ConstantSDNode>(Lane))
5728     return SDValue();
5729
5730   return Op;
5731 }
5732
5733 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5734   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5735   SDValue Lane = Op.getOperand(1);
5736   if (!isa<ConstantSDNode>(Lane))
5737     return SDValue();
5738
5739   SDValue Vec = Op.getOperand(0);
5740   if (Op.getValueType() == MVT::i32 &&
5741       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5742     SDLoc dl(Op);
5743     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5744   }
5745
5746   return Op;
5747 }
5748
5749 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5750   // The only time a CONCAT_VECTORS operation can have legal types is when
5751   // two 64-bit vectors are concatenated to a 128-bit vector.
5752   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5753          "unexpected CONCAT_VECTORS");
5754   SDLoc dl(Op);
5755   SDValue Val = DAG.getUNDEF(MVT::v2f64);
5756   SDValue Op0 = Op.getOperand(0);
5757   SDValue Op1 = Op.getOperand(1);
5758   if (Op0.getOpcode() != ISD::UNDEF)
5759     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5760                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5761                       DAG.getIntPtrConstant(0, dl));
5762   if (Op1.getOpcode() != ISD::UNDEF)
5763     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5764                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5765                       DAG.getIntPtrConstant(1, dl));
5766   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5767 }
5768
5769 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5770 /// element has been zero/sign-extended, depending on the isSigned parameter,
5771 /// from an integer type half its size.
5772 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5773                                    bool isSigned) {
5774   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5775   EVT VT = N->getValueType(0);
5776   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5777     SDNode *BVN = N->getOperand(0).getNode();
5778     if (BVN->getValueType(0) != MVT::v4i32 ||
5779         BVN->getOpcode() != ISD::BUILD_VECTOR)
5780       return false;
5781     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5782     unsigned HiElt = 1 - LoElt;
5783     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5784     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5785     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5786     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5787     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5788       return false;
5789     if (isSigned) {
5790       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5791           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5792         return true;
5793     } else {
5794       if (Hi0->isNullValue() && Hi1->isNullValue())
5795         return true;
5796     }
5797     return false;
5798   }
5799
5800   if (N->getOpcode() != ISD::BUILD_VECTOR)
5801     return false;
5802
5803   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5804     SDNode *Elt = N->getOperand(i).getNode();
5805     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5806       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5807       unsigned HalfSize = EltSize / 2;
5808       if (isSigned) {
5809         if (!isIntN(HalfSize, C->getSExtValue()))
5810           return false;
5811       } else {
5812         if (!isUIntN(HalfSize, C->getZExtValue()))
5813           return false;
5814       }
5815       continue;
5816     }
5817     return false;
5818   }
5819
5820   return true;
5821 }
5822
5823 /// isSignExtended - Check if a node is a vector value that is sign-extended
5824 /// or a constant BUILD_VECTOR with sign-extended elements.
5825 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5826   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5827     return true;
5828   if (isExtendedBUILD_VECTOR(N, DAG, true))
5829     return true;
5830   return false;
5831 }
5832
5833 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5834 /// or a constant BUILD_VECTOR with zero-extended elements.
5835 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5836   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5837     return true;
5838   if (isExtendedBUILD_VECTOR(N, DAG, false))
5839     return true;
5840   return false;
5841 }
5842
5843 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5844   if (OrigVT.getSizeInBits() >= 64)
5845     return OrigVT;
5846
5847   assert(OrigVT.isSimple() && "Expecting a simple value type");
5848
5849   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5850   switch (OrigSimpleTy) {
5851   default: llvm_unreachable("Unexpected Vector Type");
5852   case MVT::v2i8:
5853   case MVT::v2i16:
5854      return MVT::v2i32;
5855   case MVT::v4i8:
5856     return  MVT::v4i16;
5857   }
5858 }
5859
5860 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5861 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5862 /// We insert the required extension here to get the vector to fill a D register.
5863 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5864                                             const EVT &OrigTy,
5865                                             const EVT &ExtTy,
5866                                             unsigned ExtOpcode) {
5867   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5868   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5869   // 64-bits we need to insert a new extension so that it will be 64-bits.
5870   assert(ExtTy.is128BitVector() && "Unexpected extension size");
5871   if (OrigTy.getSizeInBits() >= 64)
5872     return N;
5873
5874   // Must extend size to at least 64 bits to be used as an operand for VMULL.
5875   EVT NewVT = getExtensionTo64Bits(OrigTy);
5876
5877   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5878 }
5879
5880 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5881 /// does not do any sign/zero extension. If the original vector is less
5882 /// than 64 bits, an appropriate extension will be added after the load to
5883 /// reach a total size of 64 bits. We have to add the extension separately
5884 /// because ARM does not have a sign/zero extending load for vectors.
5885 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5886   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5887
5888   // The load already has the right type.
5889   if (ExtendedTy == LD->getMemoryVT())
5890     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5891                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5892                 LD->isNonTemporal(), LD->isInvariant(),
5893                 LD->getAlignment());
5894
5895   // We need to create a zextload/sextload. We cannot just create a load
5896   // followed by a zext/zext node because LowerMUL is also run during normal
5897   // operation legalization where we can't create illegal types.
5898   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5899                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5900                         LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
5901                         LD->isNonTemporal(), LD->getAlignment());
5902 }
5903
5904 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5905 /// extending load, or BUILD_VECTOR with extended elements, return the
5906 /// unextended value. The unextended vector should be 64 bits so that it can
5907 /// be used as an operand to a VMULL instruction. If the original vector size
5908 /// before extension is less than 64 bits we add a an extension to resize
5909 /// the vector to 64 bits.
5910 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5911   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5912     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5913                                         N->getOperand(0)->getValueType(0),
5914                                         N->getValueType(0),
5915                                         N->getOpcode());
5916
5917   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5918     return SkipLoadExtensionForVMULL(LD, DAG);
5919
5920   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
5921   // have been legalized as a BITCAST from v4i32.
5922   if (N->getOpcode() == ISD::BITCAST) {
5923     SDNode *BVN = N->getOperand(0).getNode();
5924     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5925            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5926     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5927     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5928                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5929   }
5930   // Construct a new BUILD_VECTOR with elements truncated to half the size.
5931   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5932   EVT VT = N->getValueType(0);
5933   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5934   unsigned NumElts = VT.getVectorNumElements();
5935   MVT TruncVT = MVT::getIntegerVT(EltSize);
5936   SmallVector<SDValue, 8> Ops;
5937   SDLoc dl(N);
5938   for (unsigned i = 0; i != NumElts; ++i) {
5939     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5940     const APInt &CInt = C->getAPIntValue();
5941     // Element types smaller than 32 bits are not legal, so use i32 elements.
5942     // The values are implicitly truncated so sext vs. zext doesn't matter.
5943     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
5944   }
5945   return DAG.getNode(ISD::BUILD_VECTOR, dl,
5946                      MVT::getVectorVT(TruncVT, NumElts), Ops);
5947 }
5948
5949 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5950   unsigned Opcode = N->getOpcode();
5951   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5952     SDNode *N0 = N->getOperand(0).getNode();
5953     SDNode *N1 = N->getOperand(1).getNode();
5954     return N0->hasOneUse() && N1->hasOneUse() &&
5955       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5956   }
5957   return false;
5958 }
5959
5960 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5961   unsigned Opcode = N->getOpcode();
5962   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5963     SDNode *N0 = N->getOperand(0).getNode();
5964     SDNode *N1 = N->getOperand(1).getNode();
5965     return N0->hasOneUse() && N1->hasOneUse() &&
5966       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5967   }
5968   return false;
5969 }
5970
5971 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5972   // Multiplications are only custom-lowered for 128-bit vectors so that
5973   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
5974   EVT VT = Op.getValueType();
5975   assert(VT.is128BitVector() && VT.isInteger() &&
5976          "unexpected type for custom-lowering ISD::MUL");
5977   SDNode *N0 = Op.getOperand(0).getNode();
5978   SDNode *N1 = Op.getOperand(1).getNode();
5979   unsigned NewOpc = 0;
5980   bool isMLA = false;
5981   bool isN0SExt = isSignExtended(N0, DAG);
5982   bool isN1SExt = isSignExtended(N1, DAG);
5983   if (isN0SExt && isN1SExt)
5984     NewOpc = ARMISD::VMULLs;
5985   else {
5986     bool isN0ZExt = isZeroExtended(N0, DAG);
5987     bool isN1ZExt = isZeroExtended(N1, DAG);
5988     if (isN0ZExt && isN1ZExt)
5989       NewOpc = ARMISD::VMULLu;
5990     else if (isN1SExt || isN1ZExt) {
5991       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5992       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5993       if (isN1SExt && isAddSubSExt(N0, DAG)) {
5994         NewOpc = ARMISD::VMULLs;
5995         isMLA = true;
5996       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5997         NewOpc = ARMISD::VMULLu;
5998         isMLA = true;
5999       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
6000         std::swap(N0, N1);
6001         NewOpc = ARMISD::VMULLu;
6002         isMLA = true;
6003       }
6004     }
6005
6006     if (!NewOpc) {
6007       if (VT == MVT::v2i64)
6008         // Fall through to expand this.  It is not legal.
6009         return SDValue();
6010       else
6011         // Other vector multiplications are legal.
6012         return Op;
6013     }
6014   }
6015
6016   // Legalize to a VMULL instruction.
6017   SDLoc DL(Op);
6018   SDValue Op0;
6019   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
6020   if (!isMLA) {
6021     Op0 = SkipExtensionForVMULL(N0, DAG);
6022     assert(Op0.getValueType().is64BitVector() &&
6023            Op1.getValueType().is64BitVector() &&
6024            "unexpected types for extended operands to VMULL");
6025     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
6026   }
6027
6028   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
6029   // isel lowering to take advantage of no-stall back to back vmul + vmla.
6030   //   vmull q0, d4, d6
6031   //   vmlal q0, d5, d6
6032   // is faster than
6033   //   vaddl q0, d4, d5
6034   //   vmovl q1, d6
6035   //   vmul  q0, q0, q1
6036   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
6037   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
6038   EVT Op1VT = Op1.getValueType();
6039   return DAG.getNode(N0->getOpcode(), DL, VT,
6040                      DAG.getNode(NewOpc, DL, VT,
6041                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
6042                      DAG.getNode(NewOpc, DL, VT,
6043                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
6044 }
6045
6046 static SDValue
6047 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
6048   // Convert to float
6049   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
6050   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
6051   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
6052   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
6053   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
6054   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
6055   // Get reciprocal estimate.
6056   // float4 recip = vrecpeq_f32(yf);
6057   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6058                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6059                    Y);
6060   // Because char has a smaller range than uchar, we can actually get away
6061   // without any newton steps.  This requires that we use a weird bias
6062   // of 0xb000, however (again, this has been exhaustively tested).
6063   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
6064   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
6065   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
6066   Y = DAG.getConstant(0xb000, dl, MVT::i32);
6067   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
6068   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6069   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6070   // Convert back to short.
6071   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6072   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6073   return X;
6074 }
6075
6076 static SDValue
6077 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
6078   SDValue N2;
6079   // Convert to float.
6080   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6081   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6082   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6083   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6084   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6085   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6086
6087   // Use reciprocal estimate and one refinement step.
6088   // float4 recip = vrecpeq_f32(yf);
6089   // recip *= vrecpsq_f32(yf, recip);
6090   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6091                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6092                    N1);
6093   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6094                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6095                    N1, N2);
6096   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6097   // Because short has a smaller range than ushort, we can actually get away
6098   // with only a single newton step.  This requires that we use a weird bias
6099   // of 89, however (again, this has been exhaustively tested).
6100   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6101   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6102   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6103   N1 = DAG.getConstant(0x89, dl, MVT::i32);
6104   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6105   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6106   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6107   // Convert back to integer and return.
6108   // return vmovn_s32(vcvt_s32_f32(result));
6109   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6110   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6111   return N0;
6112 }
6113
6114 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6115   EVT VT = Op.getValueType();
6116   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6117          "unexpected type for custom-lowering ISD::SDIV");
6118
6119   SDLoc dl(Op);
6120   SDValue N0 = Op.getOperand(0);
6121   SDValue N1 = Op.getOperand(1);
6122   SDValue N2, N3;
6123
6124   if (VT == MVT::v8i8) {
6125     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6126     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6127
6128     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6129                      DAG.getIntPtrConstant(4, dl));
6130     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6131                      DAG.getIntPtrConstant(4, dl));
6132     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6133                      DAG.getIntPtrConstant(0, dl));
6134     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6135                      DAG.getIntPtrConstant(0, dl));
6136
6137     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6138     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6139
6140     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6141     N0 = LowerCONCAT_VECTORS(N0, DAG);
6142
6143     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6144     return N0;
6145   }
6146   return LowerSDIV_v4i16(N0, N1, dl, DAG);
6147 }
6148
6149 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6150   EVT VT = Op.getValueType();
6151   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6152          "unexpected type for custom-lowering ISD::UDIV");
6153
6154   SDLoc dl(Op);
6155   SDValue N0 = Op.getOperand(0);
6156   SDValue N1 = Op.getOperand(1);
6157   SDValue N2, N3;
6158
6159   if (VT == MVT::v8i8) {
6160     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6161     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6162
6163     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6164                      DAG.getIntPtrConstant(4, dl));
6165     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6166                      DAG.getIntPtrConstant(4, dl));
6167     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6168                      DAG.getIntPtrConstant(0, dl));
6169     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6170                      DAG.getIntPtrConstant(0, dl));
6171
6172     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6173     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6174
6175     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6176     N0 = LowerCONCAT_VECTORS(N0, DAG);
6177
6178     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6179                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
6180                                      MVT::i32),
6181                      N0);
6182     return N0;
6183   }
6184
6185   // v4i16 sdiv ... Convert to float.
6186   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6187   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6188   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6189   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6190   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6191   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6192
6193   // Use reciprocal estimate and two refinement steps.
6194   // float4 recip = vrecpeq_f32(yf);
6195   // recip *= vrecpsq_f32(yf, recip);
6196   // recip *= vrecpsq_f32(yf, recip);
6197   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6198                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6199                    BN1);
6200   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6201                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6202                    BN1, N2);
6203   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6204   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6205                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6206                    BN1, N2);
6207   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6208   // Simply multiplying by the reciprocal estimate can leave us a few ulps
6209   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6210   // and that it will never cause us to return an answer too large).
6211   // float4 result = as_float4(as_int4(xf*recip) + 2);
6212   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6213   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6214   N1 = DAG.getConstant(2, dl, MVT::i32);
6215   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6216   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6217   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6218   // Convert back to integer and return.
6219   // return vmovn_u32(vcvt_s32_f32(result));
6220   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6221   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6222   return N0;
6223 }
6224
6225 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6226   EVT VT = Op.getNode()->getValueType(0);
6227   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6228
6229   unsigned Opc;
6230   bool ExtraOp = false;
6231   switch (Op.getOpcode()) {
6232   default: llvm_unreachable("Invalid code");
6233   case ISD::ADDC: Opc = ARMISD::ADDC; break;
6234   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6235   case ISD::SUBC: Opc = ARMISD::SUBC; break;
6236   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6237   }
6238
6239   if (!ExtraOp)
6240     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6241                        Op.getOperand(1));
6242   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6243                      Op.getOperand(1), Op.getOperand(2));
6244 }
6245
6246 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6247   assert(Subtarget->isTargetDarwin());
6248
6249   // For iOS, we want to call an alternative entry point: __sincos_stret,
6250   // return values are passed via sret.
6251   SDLoc dl(Op);
6252   SDValue Arg = Op.getOperand(0);
6253   EVT ArgVT = Arg.getValueType();
6254   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6255
6256   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6257   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6258
6259   // Pair of floats / doubles used to pass the result.
6260   StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
6261
6262   // Create stack object for sret.
6263   const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
6264   const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
6265   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6266   SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
6267
6268   ArgListTy Args;
6269   ArgListEntry Entry;
6270
6271   Entry.Node = SRet;
6272   Entry.Ty = RetTy->getPointerTo();
6273   Entry.isSExt = false;
6274   Entry.isZExt = false;
6275   Entry.isSRet = true;
6276   Args.push_back(Entry);
6277
6278   Entry.Node = Arg;
6279   Entry.Ty = ArgTy;
6280   Entry.isSExt = false;
6281   Entry.isZExt = false;
6282   Args.push_back(Entry);
6283
6284   const char *LibcallName  = (ArgVT == MVT::f64)
6285   ? "__sincos_stret" : "__sincosf_stret";
6286   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
6287
6288   TargetLowering::CallLoweringInfo CLI(DAG);
6289   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6290     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6291                std::move(Args), 0)
6292     .setDiscardResult();
6293
6294   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6295
6296   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6297                                 MachinePointerInfo(), false, false, false, 0);
6298
6299   // Address of cos field.
6300   SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
6301                             DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
6302   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6303                                 MachinePointerInfo(), false, false, false, 0);
6304
6305   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6306   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6307                      LoadSin.getValue(0), LoadCos.getValue(0));
6308 }
6309
6310 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6311   // Monotonic load/store is legal for all targets
6312   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6313     return Op;
6314
6315   // Acquire/Release load/store is not legal for targets without a
6316   // dmb or equivalent available.
6317   return SDValue();
6318 }
6319
6320 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6321                                     SmallVectorImpl<SDValue> &Results,
6322                                     SelectionDAG &DAG,
6323                                     const ARMSubtarget *Subtarget) {
6324   SDLoc DL(N);
6325   SDValue Cycles32, OutChain;
6326
6327   if (Subtarget->hasPerfMon()) {
6328     // Under Power Management extensions, the cycle-count is:
6329     //    mrc p15, #0, <Rt>, c9, c13, #0
6330     SDValue Ops[] = { N->getOperand(0), // Chain
6331                       DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
6332                       DAG.getConstant(15, DL, MVT::i32),
6333                       DAG.getConstant(0, DL, MVT::i32),
6334                       DAG.getConstant(9, DL, MVT::i32),
6335                       DAG.getConstant(13, DL, MVT::i32),
6336                       DAG.getConstant(0, DL, MVT::i32)
6337     };
6338
6339     Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6340                            DAG.getVTList(MVT::i32, MVT::Other), Ops);
6341     OutChain = Cycles32.getValue(1);
6342   } else {
6343     // Intrinsic is defined to return 0 on unsupported platforms. Technically
6344     // there are older ARM CPUs that have implementation-specific ways of
6345     // obtaining this information (FIXME!).
6346     Cycles32 = DAG.getConstant(0, DL, MVT::i32);
6347     OutChain = DAG.getEntryNode();
6348   }
6349
6350
6351   SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6352                                  Cycles32, DAG.getConstant(0, DL, MVT::i32));
6353   Results.push_back(Cycles64);
6354   Results.push_back(OutChain);
6355 }
6356
6357 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6358   switch (Op.getOpcode()) {
6359   default: llvm_unreachable("Don't know how to custom lower this!");
6360   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6361   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6362   case ISD::GlobalAddress:
6363     switch (Subtarget->getTargetTriple().getObjectFormat()) {
6364     default: llvm_unreachable("unknown object format");
6365     case Triple::COFF:
6366       return LowerGlobalAddressWindows(Op, DAG);
6367     case Triple::ELF:
6368       return LowerGlobalAddressELF(Op, DAG);
6369     case Triple::MachO:
6370       return LowerGlobalAddressDarwin(Op, DAG);
6371     }
6372   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6373   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6374   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6375   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6376   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6377   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6378   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6379   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6380   case ISD::SINT_TO_FP:
6381   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6382   case ISD::FP_TO_SINT:
6383   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6384   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6385   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6386   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6387   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6388   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6389   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6390   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6391                                                                Subtarget);
6392   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6393   case ISD::SHL:
6394   case ISD::SRL:
6395   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6396   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6397   case ISD::SRL_PARTS:
6398   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6399   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6400   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6401   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6402   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6403   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6404   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6405   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6406   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6407   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6408   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6409   case ISD::MUL:           return LowerMUL(Op, DAG);
6410   case ISD::SDIV:          return LowerSDIV(Op, DAG);
6411   case ISD::UDIV:          return LowerUDIV(Op, DAG);
6412   case ISD::ADDC:
6413   case ISD::ADDE:
6414   case ISD::SUBC:
6415   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6416   case ISD::SADDO:
6417   case ISD::UADDO:
6418   case ISD::SSUBO:
6419   case ISD::USUBO:
6420     return LowerXALUO(Op, DAG);
6421   case ISD::ATOMIC_LOAD:
6422   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6423   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6424   case ISD::SDIVREM:
6425   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6426   case ISD::DYNAMIC_STACKALLOC:
6427     if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6428       return LowerDYNAMIC_STACKALLOC(Op, DAG);
6429     llvm_unreachable("Don't know how to custom lower this!");
6430   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6431   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6432   }
6433 }
6434
6435 /// ReplaceNodeResults - Replace the results of node with an illegal result
6436 /// type with new values built out of custom code.
6437 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6438                                            SmallVectorImpl<SDValue>&Results,
6439                                            SelectionDAG &DAG) const {
6440   SDValue Res;
6441   switch (N->getOpcode()) {
6442   default:
6443     llvm_unreachable("Don't know how to custom expand this!");
6444   case ISD::BITCAST:
6445     Res = ExpandBITCAST(N, DAG);
6446     break;
6447   case ISD::SRL:
6448   case ISD::SRA:
6449     Res = Expand64BitShift(N, DAG, Subtarget);
6450     break;
6451   case ISD::READCYCLECOUNTER:
6452     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6453     return;
6454   }
6455   if (Res.getNode())
6456     Results.push_back(Res);
6457 }
6458
6459 //===----------------------------------------------------------------------===//
6460 //                           ARM Scheduler Hooks
6461 //===----------------------------------------------------------------------===//
6462
6463 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6464 /// registers the function context.
6465 void ARMTargetLowering::
6466 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6467                        MachineBasicBlock *DispatchBB, int FI) const {
6468   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6469   DebugLoc dl = MI->getDebugLoc();
6470   MachineFunction *MF = MBB->getParent();
6471   MachineRegisterInfo *MRI = &MF->getRegInfo();
6472   MachineConstantPool *MCP = MF->getConstantPool();
6473   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6474   const Function *F = MF->getFunction();
6475
6476   bool isThumb = Subtarget->isThumb();
6477   bool isThumb2 = Subtarget->isThumb2();
6478
6479   unsigned PCLabelId = AFI->createPICLabelUId();
6480   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6481   ARMConstantPoolValue *CPV =
6482     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6483   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6484
6485   const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
6486                                            : &ARM::GPRRegClass;
6487
6488   // Grab constant pool and fixed stack memory operands.
6489   MachineMemOperand *CPMMO =
6490     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6491                              MachineMemOperand::MOLoad, 4, 4);
6492
6493   MachineMemOperand *FIMMOSt =
6494     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6495                              MachineMemOperand::MOStore, 4, 4);
6496
6497   // Load the address of the dispatch MBB into the jump buffer.
6498   if (isThumb2) {
6499     // Incoming value: jbuf
6500     //   ldr.n  r5, LCPI1_1
6501     //   orr    r5, r5, #1
6502     //   add    r5, pc
6503     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6504     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6505     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6506                    .addConstantPoolIndex(CPI)
6507                    .addMemOperand(CPMMO));
6508     // Set the low bit because of thumb mode.
6509     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6510     AddDefaultCC(
6511       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6512                      .addReg(NewVReg1, RegState::Kill)
6513                      .addImm(0x01)));
6514     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6515     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6516       .addReg(NewVReg2, RegState::Kill)
6517       .addImm(PCLabelId);
6518     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6519                    .addReg(NewVReg3, RegState::Kill)
6520                    .addFrameIndex(FI)
6521                    .addImm(36)  // &jbuf[1] :: pc
6522                    .addMemOperand(FIMMOSt));
6523   } else if (isThumb) {
6524     // Incoming value: jbuf
6525     //   ldr.n  r1, LCPI1_4
6526     //   add    r1, pc
6527     //   mov    r2, #1
6528     //   orrs   r1, r2
6529     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6530     //   str    r1, [r2]
6531     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6532     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6533                    .addConstantPoolIndex(CPI)
6534                    .addMemOperand(CPMMO));
6535     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6536     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6537       .addReg(NewVReg1, RegState::Kill)
6538       .addImm(PCLabelId);
6539     // Set the low bit because of thumb mode.
6540     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6541     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6542                    .addReg(ARM::CPSR, RegState::Define)
6543                    .addImm(1));
6544     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6545     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6546                    .addReg(ARM::CPSR, RegState::Define)
6547                    .addReg(NewVReg2, RegState::Kill)
6548                    .addReg(NewVReg3, RegState::Kill));
6549     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6550     BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
6551             .addFrameIndex(FI)
6552             .addImm(36); // &jbuf[1] :: pc
6553     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6554                    .addReg(NewVReg4, RegState::Kill)
6555                    .addReg(NewVReg5, RegState::Kill)
6556                    .addImm(0)
6557                    .addMemOperand(FIMMOSt));
6558   } else {
6559     // Incoming value: jbuf
6560     //   ldr  r1, LCPI1_1
6561     //   add  r1, pc, r1
6562     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6563     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6564     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6565                    .addConstantPoolIndex(CPI)
6566                    .addImm(0)
6567                    .addMemOperand(CPMMO));
6568     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6569     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6570                    .addReg(NewVReg1, RegState::Kill)
6571                    .addImm(PCLabelId));
6572     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6573                    .addReg(NewVReg2, RegState::Kill)
6574                    .addFrameIndex(FI)
6575                    .addImm(36)  // &jbuf[1] :: pc
6576                    .addMemOperand(FIMMOSt));
6577   }
6578 }
6579
6580 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr *MI,
6581                                               MachineBasicBlock *MBB) const {
6582   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6583   DebugLoc dl = MI->getDebugLoc();
6584   MachineFunction *MF = MBB->getParent();
6585   MachineRegisterInfo *MRI = &MF->getRegInfo();
6586   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6587   MachineFrameInfo *MFI = MF->getFrameInfo();
6588   int FI = MFI->getFunctionContextIndex();
6589
6590   const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
6591                                                         : &ARM::GPRnopcRegClass;
6592
6593   // Get a mapping of the call site numbers to all of the landing pads they're
6594   // associated with.
6595   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6596   unsigned MaxCSNum = 0;
6597   MachineModuleInfo &MMI = MF->getMMI();
6598   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6599        ++BB) {
6600     if (!BB->isLandingPad()) continue;
6601
6602     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6603     // pad.
6604     for (MachineBasicBlock::iterator
6605            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6606       if (!II->isEHLabel()) continue;
6607
6608       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6609       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6610
6611       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6612       for (SmallVectorImpl<unsigned>::iterator
6613              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6614            CSI != CSE; ++CSI) {
6615         CallSiteNumToLPad[*CSI].push_back(BB);
6616         MaxCSNum = std::max(MaxCSNum, *CSI);
6617       }
6618       break;
6619     }
6620   }
6621
6622   // Get an ordered list of the machine basic blocks for the jump table.
6623   std::vector<MachineBasicBlock*> LPadList;
6624   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6625   LPadList.reserve(CallSiteNumToLPad.size());
6626   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6627     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6628     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6629            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6630       LPadList.push_back(*II);
6631       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6632     }
6633   }
6634
6635   assert(!LPadList.empty() &&
6636          "No landing pad destinations for the dispatch jump table!");
6637
6638   // Create the jump table and associated information.
6639   MachineJumpTableInfo *JTI =
6640     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6641   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6642   unsigned UId = AFI->createJumpTableUId();
6643   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6644
6645   // Create the MBBs for the dispatch code.
6646
6647   // Shove the dispatch's address into the return slot in the function context.
6648   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6649   DispatchBB->setIsLandingPad();
6650
6651   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6652   unsigned trap_opcode;
6653   if (Subtarget->isThumb())
6654     trap_opcode = ARM::tTRAP;
6655   else
6656     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6657
6658   BuildMI(TrapBB, dl, TII->get(trap_opcode));
6659   DispatchBB->addSuccessor(TrapBB);
6660
6661   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6662   DispatchBB->addSuccessor(DispContBB);
6663
6664   // Insert and MBBs.
6665   MF->insert(MF->end(), DispatchBB);
6666   MF->insert(MF->end(), DispContBB);
6667   MF->insert(MF->end(), TrapBB);
6668
6669   // Insert code into the entry block that creates and registers the function
6670   // context.
6671   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6672
6673   MachineMemOperand *FIMMOLd =
6674     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6675                              MachineMemOperand::MOLoad |
6676                              MachineMemOperand::MOVolatile, 4, 4);
6677
6678   MachineInstrBuilder MIB;
6679   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6680
6681   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6682   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6683
6684   // Add a register mask with no preserved registers.  This results in all
6685   // registers being marked as clobbered.
6686   MIB.addRegMask(RI.getNoPreservedMask());
6687
6688   unsigned NumLPads = LPadList.size();
6689   if (Subtarget->isThumb2()) {
6690     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6691     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6692                    .addFrameIndex(FI)
6693                    .addImm(4)
6694                    .addMemOperand(FIMMOLd));
6695
6696     if (NumLPads < 256) {
6697       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6698                      .addReg(NewVReg1)
6699                      .addImm(LPadList.size()));
6700     } else {
6701       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6702       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6703                      .addImm(NumLPads & 0xFFFF));
6704
6705       unsigned VReg2 = VReg1;
6706       if ((NumLPads & 0xFFFF0000) != 0) {
6707         VReg2 = MRI->createVirtualRegister(TRC);
6708         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6709                        .addReg(VReg1)
6710                        .addImm(NumLPads >> 16));
6711       }
6712
6713       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6714                      .addReg(NewVReg1)
6715                      .addReg(VReg2));
6716     }
6717
6718     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6719       .addMBB(TrapBB)
6720       .addImm(ARMCC::HI)
6721       .addReg(ARM::CPSR);
6722
6723     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6724     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6725                    .addJumpTableIndex(MJTI)
6726                    .addImm(UId));
6727
6728     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6729     AddDefaultCC(
6730       AddDefaultPred(
6731         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6732         .addReg(NewVReg3, RegState::Kill)
6733         .addReg(NewVReg1)
6734         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6735
6736     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6737       .addReg(NewVReg4, RegState::Kill)
6738       .addReg(NewVReg1)
6739       .addJumpTableIndex(MJTI)
6740       .addImm(UId);
6741   } else if (Subtarget->isThumb()) {
6742     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6743     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6744                    .addFrameIndex(FI)
6745                    .addImm(1)
6746                    .addMemOperand(FIMMOLd));
6747
6748     if (NumLPads < 256) {
6749       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6750                      .addReg(NewVReg1)
6751                      .addImm(NumLPads));
6752     } else {
6753       MachineConstantPool *ConstantPool = MF->getConstantPool();
6754       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6755       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6756
6757       // MachineConstantPool wants an explicit alignment.
6758       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6759       if (Align == 0)
6760         Align = getDataLayout()->getTypeAllocSize(C->getType());
6761       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6762
6763       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6764       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6765                      .addReg(VReg1, RegState::Define)
6766                      .addConstantPoolIndex(Idx));
6767       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6768                      .addReg(NewVReg1)
6769                      .addReg(VReg1));
6770     }
6771
6772     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6773       .addMBB(TrapBB)
6774       .addImm(ARMCC::HI)
6775       .addReg(ARM::CPSR);
6776
6777     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6778     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6779                    .addReg(ARM::CPSR, RegState::Define)
6780                    .addReg(NewVReg1)
6781                    .addImm(2));
6782
6783     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6784     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6785                    .addJumpTableIndex(MJTI)
6786                    .addImm(UId));
6787
6788     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6789     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6790                    .addReg(ARM::CPSR, RegState::Define)
6791                    .addReg(NewVReg2, RegState::Kill)
6792                    .addReg(NewVReg3));
6793
6794     MachineMemOperand *JTMMOLd =
6795       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6796                                MachineMemOperand::MOLoad, 4, 4);
6797
6798     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6799     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6800                    .addReg(NewVReg4, RegState::Kill)
6801                    .addImm(0)
6802                    .addMemOperand(JTMMOLd));
6803
6804     unsigned NewVReg6 = NewVReg5;
6805     if (RelocM == Reloc::PIC_) {
6806       NewVReg6 = MRI->createVirtualRegister(TRC);
6807       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6808                      .addReg(ARM::CPSR, RegState::Define)
6809                      .addReg(NewVReg5, RegState::Kill)
6810                      .addReg(NewVReg3));
6811     }
6812
6813     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6814       .addReg(NewVReg6, RegState::Kill)
6815       .addJumpTableIndex(MJTI)
6816       .addImm(UId);
6817   } else {
6818     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6819     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6820                    .addFrameIndex(FI)
6821                    .addImm(4)
6822                    .addMemOperand(FIMMOLd));
6823
6824     if (NumLPads < 256) {
6825       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6826                      .addReg(NewVReg1)
6827                      .addImm(NumLPads));
6828     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6829       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6830       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6831                      .addImm(NumLPads & 0xFFFF));
6832
6833       unsigned VReg2 = VReg1;
6834       if ((NumLPads & 0xFFFF0000) != 0) {
6835         VReg2 = MRI->createVirtualRegister(TRC);
6836         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6837                        .addReg(VReg1)
6838                        .addImm(NumLPads >> 16));
6839       }
6840
6841       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6842                      .addReg(NewVReg1)
6843                      .addReg(VReg2));
6844     } else {
6845       MachineConstantPool *ConstantPool = MF->getConstantPool();
6846       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6847       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6848
6849       // MachineConstantPool wants an explicit alignment.
6850       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6851       if (Align == 0)
6852         Align = getDataLayout()->getTypeAllocSize(C->getType());
6853       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6854
6855       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6856       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6857                      .addReg(VReg1, RegState::Define)
6858                      .addConstantPoolIndex(Idx)
6859                      .addImm(0));
6860       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6861                      .addReg(NewVReg1)
6862                      .addReg(VReg1, RegState::Kill));
6863     }
6864
6865     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6866       .addMBB(TrapBB)
6867       .addImm(ARMCC::HI)
6868       .addReg(ARM::CPSR);
6869
6870     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6871     AddDefaultCC(
6872       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6873                      .addReg(NewVReg1)
6874                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6875     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6876     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6877                    .addJumpTableIndex(MJTI)
6878                    .addImm(UId));
6879
6880     MachineMemOperand *JTMMOLd =
6881       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6882                                MachineMemOperand::MOLoad, 4, 4);
6883     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6884     AddDefaultPred(
6885       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6886       .addReg(NewVReg3, RegState::Kill)
6887       .addReg(NewVReg4)
6888       .addImm(0)
6889       .addMemOperand(JTMMOLd));
6890
6891     if (RelocM == Reloc::PIC_) {
6892       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6893         .addReg(NewVReg5, RegState::Kill)
6894         .addReg(NewVReg4)
6895         .addJumpTableIndex(MJTI)
6896         .addImm(UId);
6897     } else {
6898       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6899         .addReg(NewVReg5, RegState::Kill)
6900         .addJumpTableIndex(MJTI)
6901         .addImm(UId);
6902     }
6903   }
6904
6905   // Add the jump table entries as successors to the MBB.
6906   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6907   for (std::vector<MachineBasicBlock*>::iterator
6908          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6909     MachineBasicBlock *CurMBB = *I;
6910     if (SeenMBBs.insert(CurMBB).second)
6911       DispContBB->addSuccessor(CurMBB);
6912   }
6913
6914   // N.B. the order the invoke BBs are processed in doesn't matter here.
6915   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
6916   SmallVector<MachineBasicBlock*, 64> MBBLPads;
6917   for (MachineBasicBlock *BB : InvokeBBs) {
6918
6919     // Remove the landing pad successor from the invoke block and replace it
6920     // with the new dispatch block.
6921     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6922                                                   BB->succ_end());
6923     while (!Successors.empty()) {
6924       MachineBasicBlock *SMBB = Successors.pop_back_val();
6925       if (SMBB->isLandingPad()) {
6926         BB->removeSuccessor(SMBB);
6927         MBBLPads.push_back(SMBB);
6928       }
6929     }
6930
6931     BB->addSuccessor(DispatchBB);
6932
6933     // Find the invoke call and mark all of the callee-saved registers as
6934     // 'implicit defined' so that they're spilled. This prevents code from
6935     // moving instructions to before the EH block, where they will never be
6936     // executed.
6937     for (MachineBasicBlock::reverse_iterator
6938            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6939       if (!II->isCall()) continue;
6940
6941       DenseMap<unsigned, bool> DefRegs;
6942       for (MachineInstr::mop_iterator
6943              OI = II->operands_begin(), OE = II->operands_end();
6944            OI != OE; ++OI) {
6945         if (!OI->isReg()) continue;
6946         DefRegs[OI->getReg()] = true;
6947       }
6948
6949       MachineInstrBuilder MIB(*MF, &*II);
6950
6951       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6952         unsigned Reg = SavedRegs[i];
6953         if (Subtarget->isThumb2() &&
6954             !ARM::tGPRRegClass.contains(Reg) &&
6955             !ARM::hGPRRegClass.contains(Reg))
6956           continue;
6957         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6958           continue;
6959         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6960           continue;
6961         if (!DefRegs[Reg])
6962           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6963       }
6964
6965       break;
6966     }
6967   }
6968
6969   // Mark all former landing pads as non-landing pads. The dispatch is the only
6970   // landing pad now.
6971   for (SmallVectorImpl<MachineBasicBlock*>::iterator
6972          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6973     (*I)->setIsLandingPad(false);
6974
6975   // The instruction is gone now.
6976   MI->eraseFromParent();
6977 }
6978
6979 static
6980 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6981   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6982        E = MBB->succ_end(); I != E; ++I)
6983     if (*I != Succ)
6984       return *I;
6985   llvm_unreachable("Expecting a BB with two successors!");
6986 }
6987
6988 /// Return the load opcode for a given load size. If load size >= 8,
6989 /// neon opcode will be returned.
6990 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
6991   if (LdSize >= 8)
6992     return LdSize == 16 ? ARM::VLD1q32wb_fixed
6993                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
6994   if (IsThumb1)
6995     return LdSize == 4 ? ARM::tLDRi
6996                        : LdSize == 2 ? ARM::tLDRHi
6997                                      : LdSize == 1 ? ARM::tLDRBi : 0;
6998   if (IsThumb2)
6999     return LdSize == 4 ? ARM::t2LDR_POST
7000                        : LdSize == 2 ? ARM::t2LDRH_POST
7001                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7002   return LdSize == 4 ? ARM::LDR_POST_IMM
7003                      : LdSize == 2 ? ARM::LDRH_POST
7004                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7005 }
7006
7007 /// Return the store opcode for a given store size. If store size >= 8,
7008 /// neon opcode will be returned.
7009 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7010   if (StSize >= 8)
7011     return StSize == 16 ? ARM::VST1q32wb_fixed
7012                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7013   if (IsThumb1)
7014     return StSize == 4 ? ARM::tSTRi
7015                        : StSize == 2 ? ARM::tSTRHi
7016                                      : StSize == 1 ? ARM::tSTRBi : 0;
7017   if (IsThumb2)
7018     return StSize == 4 ? ARM::t2STR_POST
7019                        : StSize == 2 ? ARM::t2STRH_POST
7020                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
7021   return StSize == 4 ? ARM::STR_POST_IMM
7022                      : StSize == 2 ? ARM::STRH_POST
7023                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7024 }
7025
7026 /// Emit a post-increment load operation with given size. The instructions
7027 /// will be added to BB at Pos.
7028 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7029                        const TargetInstrInfo *TII, DebugLoc dl,
7030                        unsigned LdSize, unsigned Data, unsigned AddrIn,
7031                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7032   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7033   assert(LdOpc != 0 && "Should have a load opcode");
7034   if (LdSize >= 8) {
7035     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7036                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7037                        .addImm(0));
7038   } else if (IsThumb1) {
7039     // load + update AddrIn
7040     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7041                        .addReg(AddrIn).addImm(0));
7042     MachineInstrBuilder MIB =
7043         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7044     MIB = AddDefaultT1CC(MIB);
7045     MIB.addReg(AddrIn).addImm(LdSize);
7046     AddDefaultPred(MIB);
7047   } else if (IsThumb2) {
7048     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7049                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7050                        .addImm(LdSize));
7051   } else { // arm
7052     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7053                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7054                        .addReg(0).addImm(LdSize));
7055   }
7056 }
7057
7058 /// Emit a post-increment store operation with given size. The instructions
7059 /// will be added to BB at Pos.
7060 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7061                        const TargetInstrInfo *TII, DebugLoc dl,
7062                        unsigned StSize, unsigned Data, unsigned AddrIn,
7063                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7064   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7065   assert(StOpc != 0 && "Should have a store opcode");
7066   if (StSize >= 8) {
7067     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7068                        .addReg(AddrIn).addImm(0).addReg(Data));
7069   } else if (IsThumb1) {
7070     // store + update AddrIn
7071     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7072                        .addReg(AddrIn).addImm(0));
7073     MachineInstrBuilder MIB =
7074         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7075     MIB = AddDefaultT1CC(MIB);
7076     MIB.addReg(AddrIn).addImm(StSize);
7077     AddDefaultPred(MIB);
7078   } else if (IsThumb2) {
7079     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7080                        .addReg(Data).addReg(AddrIn).addImm(StSize));
7081   } else { // arm
7082     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7083                        .addReg(Data).addReg(AddrIn).addReg(0)
7084                        .addImm(StSize));
7085   }
7086 }
7087
7088 MachineBasicBlock *
7089 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7090                                    MachineBasicBlock *BB) const {
7091   // This pseudo instruction has 3 operands: dst, src, size
7092   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7093   // Otherwise, we will generate unrolled scalar copies.
7094   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7095   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7096   MachineFunction::iterator It = BB;
7097   ++It;
7098
7099   unsigned dest = MI->getOperand(0).getReg();
7100   unsigned src = MI->getOperand(1).getReg();
7101   unsigned SizeVal = MI->getOperand(2).getImm();
7102   unsigned Align = MI->getOperand(3).getImm();
7103   DebugLoc dl = MI->getDebugLoc();
7104
7105   MachineFunction *MF = BB->getParent();
7106   MachineRegisterInfo &MRI = MF->getRegInfo();
7107   unsigned UnitSize = 0;
7108   const TargetRegisterClass *TRC = nullptr;
7109   const TargetRegisterClass *VecTRC = nullptr;
7110
7111   bool IsThumb1 = Subtarget->isThumb1Only();
7112   bool IsThumb2 = Subtarget->isThumb2();
7113
7114   if (Align & 1) {
7115     UnitSize = 1;
7116   } else if (Align & 2) {
7117     UnitSize = 2;
7118   } else {
7119     // Check whether we can use NEON instructions.
7120     if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
7121         Subtarget->hasNEON()) {
7122       if ((Align % 16 == 0) && SizeVal >= 16)
7123         UnitSize = 16;
7124       else if ((Align % 8 == 0) && SizeVal >= 8)
7125         UnitSize = 8;
7126     }
7127     // Can't use NEON instructions.
7128     if (UnitSize == 0)
7129       UnitSize = 4;
7130   }
7131
7132   // Select the correct opcode and register class for unit size load/store
7133   bool IsNeon = UnitSize >= 8;
7134   TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
7135   if (IsNeon)
7136     VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
7137                             : UnitSize == 8 ? &ARM::DPRRegClass
7138                                             : nullptr;
7139
7140   unsigned BytesLeft = SizeVal % UnitSize;
7141   unsigned LoopSize = SizeVal - BytesLeft;
7142
7143   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7144     // Use LDR and STR to copy.
7145     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7146     // [destOut] = STR_POST(scratch, destIn, UnitSize)
7147     unsigned srcIn = src;
7148     unsigned destIn = dest;
7149     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7150       unsigned srcOut = MRI.createVirtualRegister(TRC);
7151       unsigned destOut = MRI.createVirtualRegister(TRC);
7152       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7153       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7154                  IsThumb1, IsThumb2);
7155       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7156                  IsThumb1, IsThumb2);
7157       srcIn = srcOut;
7158       destIn = destOut;
7159     }
7160
7161     // Handle the leftover bytes with LDRB and STRB.
7162     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7163     // [destOut] = STRB_POST(scratch, destIn, 1)
7164     for (unsigned i = 0; i < BytesLeft; i++) {
7165       unsigned srcOut = MRI.createVirtualRegister(TRC);
7166       unsigned destOut = MRI.createVirtualRegister(TRC);
7167       unsigned scratch = MRI.createVirtualRegister(TRC);
7168       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7169                  IsThumb1, IsThumb2);
7170       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7171                  IsThumb1, IsThumb2);
7172       srcIn = srcOut;
7173       destIn = destOut;
7174     }
7175     MI->eraseFromParent();   // The instruction is gone now.
7176     return BB;
7177   }
7178
7179   // Expand the pseudo op to a loop.
7180   // thisMBB:
7181   //   ...
7182   //   movw varEnd, # --> with thumb2
7183   //   movt varEnd, #
7184   //   ldrcp varEnd, idx --> without thumb2
7185   //   fallthrough --> loopMBB
7186   // loopMBB:
7187   //   PHI varPhi, varEnd, varLoop
7188   //   PHI srcPhi, src, srcLoop
7189   //   PHI destPhi, dst, destLoop
7190   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7191   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7192   //   subs varLoop, varPhi, #UnitSize
7193   //   bne loopMBB
7194   //   fallthrough --> exitMBB
7195   // exitMBB:
7196   //   epilogue to handle left-over bytes
7197   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7198   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7199   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7200   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7201   MF->insert(It, loopMBB);
7202   MF->insert(It, exitMBB);
7203
7204   // Transfer the remainder of BB and its successor edges to exitMBB.
7205   exitMBB->splice(exitMBB->begin(), BB,
7206                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7207   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7208
7209   // Load an immediate to varEnd.
7210   unsigned varEnd = MRI.createVirtualRegister(TRC);
7211   if (Subtarget->useMovt(*MF)) {
7212     unsigned Vtmp = varEnd;
7213     if ((LoopSize & 0xFFFF0000) != 0)
7214       Vtmp = MRI.createVirtualRegister(TRC);
7215     AddDefaultPred(BuildMI(BB, dl,
7216                            TII->get(IsThumb2 ? ARM::t2MOVi16 : ARM::MOVi16),
7217                            Vtmp).addImm(LoopSize & 0xFFFF));
7218
7219     if ((LoopSize & 0xFFFF0000) != 0)
7220       AddDefaultPred(BuildMI(BB, dl,
7221                              TII->get(IsThumb2 ? ARM::t2MOVTi16 : ARM::MOVTi16),
7222                              varEnd)
7223                          .addReg(Vtmp)
7224                          .addImm(LoopSize >> 16));
7225   } else {
7226     MachineConstantPool *ConstantPool = MF->getConstantPool();
7227     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7228     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7229
7230     // MachineConstantPool wants an explicit alignment.
7231     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7232     if (Align == 0)
7233       Align = getDataLayout()->getTypeAllocSize(C->getType());
7234     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7235
7236     if (IsThumb1)
7237       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7238           varEnd, RegState::Define).addConstantPoolIndex(Idx));
7239     else
7240       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7241           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7242   }
7243   BB->addSuccessor(loopMBB);
7244
7245   // Generate the loop body:
7246   //   varPhi = PHI(varLoop, varEnd)
7247   //   srcPhi = PHI(srcLoop, src)
7248   //   destPhi = PHI(destLoop, dst)
7249   MachineBasicBlock *entryBB = BB;
7250   BB = loopMBB;
7251   unsigned varLoop = MRI.createVirtualRegister(TRC);
7252   unsigned varPhi = MRI.createVirtualRegister(TRC);
7253   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7254   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7255   unsigned destLoop = MRI.createVirtualRegister(TRC);
7256   unsigned destPhi = MRI.createVirtualRegister(TRC);
7257
7258   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7259     .addReg(varLoop).addMBB(loopMBB)
7260     .addReg(varEnd).addMBB(entryBB);
7261   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7262     .addReg(srcLoop).addMBB(loopMBB)
7263     .addReg(src).addMBB(entryBB);
7264   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7265     .addReg(destLoop).addMBB(loopMBB)
7266     .addReg(dest).addMBB(entryBB);
7267
7268   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7269   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7270   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7271   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7272              IsThumb1, IsThumb2);
7273   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7274              IsThumb1, IsThumb2);
7275
7276   // Decrement loop variable by UnitSize.
7277   if (IsThumb1) {
7278     MachineInstrBuilder MIB =
7279         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7280     MIB = AddDefaultT1CC(MIB);
7281     MIB.addReg(varPhi).addImm(UnitSize);
7282     AddDefaultPred(MIB);
7283   } else {
7284     MachineInstrBuilder MIB =
7285         BuildMI(*BB, BB->end(), dl,
7286                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7287     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7288     MIB->getOperand(5).setReg(ARM::CPSR);
7289     MIB->getOperand(5).setIsDef(true);
7290   }
7291   BuildMI(*BB, BB->end(), dl,
7292           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7293       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7294
7295   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7296   BB->addSuccessor(loopMBB);
7297   BB->addSuccessor(exitMBB);
7298
7299   // Add epilogue to handle BytesLeft.
7300   BB = exitMBB;
7301   MachineInstr *StartOfExit = exitMBB->begin();
7302
7303   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7304   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7305   unsigned srcIn = srcLoop;
7306   unsigned destIn = destLoop;
7307   for (unsigned i = 0; i < BytesLeft; i++) {
7308     unsigned srcOut = MRI.createVirtualRegister(TRC);
7309     unsigned destOut = MRI.createVirtualRegister(TRC);
7310     unsigned scratch = MRI.createVirtualRegister(TRC);
7311     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7312                IsThumb1, IsThumb2);
7313     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7314                IsThumb1, IsThumb2);
7315     srcIn = srcOut;
7316     destIn = destOut;
7317   }
7318
7319   MI->eraseFromParent();   // The instruction is gone now.
7320   return BB;
7321 }
7322
7323 MachineBasicBlock *
7324 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7325                                        MachineBasicBlock *MBB) const {
7326   const TargetMachine &TM = getTargetMachine();
7327   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
7328   DebugLoc DL = MI->getDebugLoc();
7329
7330   assert(Subtarget->isTargetWindows() &&
7331          "__chkstk is only supported on Windows");
7332   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7333
7334   // __chkstk takes the number of words to allocate on the stack in R4, and
7335   // returns the stack adjustment in number of bytes in R4.  This will not
7336   // clober any other registers (other than the obvious lr).
7337   //
7338   // Although, technically, IP should be considered a register which may be
7339   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
7340   // thumb-2 environment, so there is no interworking required.  As a result, we
7341   // do not expect a veneer to be emitted by the linker, clobbering IP.
7342   //
7343   // Each module receives its own copy of __chkstk, so no import thunk is
7344   // required, again, ensuring that IP is not clobbered.
7345   //
7346   // Finally, although some linkers may theoretically provide a trampoline for
7347   // out of range calls (which is quite common due to a 32M range limitation of
7348   // branches for Thumb), we can generate the long-call version via
7349   // -mcmodel=large, alleviating the need for the trampoline which may clobber
7350   // IP.
7351
7352   switch (TM.getCodeModel()) {
7353   case CodeModel::Small:
7354   case CodeModel::Medium:
7355   case CodeModel::Default:
7356   case CodeModel::Kernel:
7357     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7358       .addImm((unsigned)ARMCC::AL).addReg(0)
7359       .addExternalSymbol("__chkstk")
7360       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7361       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7362       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7363     break;
7364   case CodeModel::Large:
7365   case CodeModel::JITDefault: {
7366     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7367     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7368
7369     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7370       .addExternalSymbol("__chkstk");
7371     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7372       .addImm((unsigned)ARMCC::AL).addReg(0)
7373       .addReg(Reg, RegState::Kill)
7374       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7375       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7376       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7377     break;
7378   }
7379   }
7380
7381   AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7382                                       ARM::SP)
7383                               .addReg(ARM::SP).addReg(ARM::R4)));
7384
7385   MI->eraseFromParent();
7386   return MBB;
7387 }
7388
7389 MachineBasicBlock *
7390 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7391                                                MachineBasicBlock *BB) const {
7392   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7393   DebugLoc dl = MI->getDebugLoc();
7394   bool isThumb2 = Subtarget->isThumb2();
7395   switch (MI->getOpcode()) {
7396   default: {
7397     MI->dump();
7398     llvm_unreachable("Unexpected instr type to insert");
7399   }
7400   // The Thumb2 pre-indexed stores have the same MI operands, they just
7401   // define them differently in the .td files from the isel patterns, so
7402   // they need pseudos.
7403   case ARM::t2STR_preidx:
7404     MI->setDesc(TII->get(ARM::t2STR_PRE));
7405     return BB;
7406   case ARM::t2STRB_preidx:
7407     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7408     return BB;
7409   case ARM::t2STRH_preidx:
7410     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7411     return BB;
7412
7413   case ARM::STRi_preidx:
7414   case ARM::STRBi_preidx: {
7415     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7416       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7417     // Decode the offset.
7418     unsigned Offset = MI->getOperand(4).getImm();
7419     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7420     Offset = ARM_AM::getAM2Offset(Offset);
7421     if (isSub)
7422       Offset = -Offset;
7423
7424     MachineMemOperand *MMO = *MI->memoperands_begin();
7425     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7426       .addOperand(MI->getOperand(0))  // Rn_wb
7427       .addOperand(MI->getOperand(1))  // Rt
7428       .addOperand(MI->getOperand(2))  // Rn
7429       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7430       .addOperand(MI->getOperand(5))  // pred
7431       .addOperand(MI->getOperand(6))
7432       .addMemOperand(MMO);
7433     MI->eraseFromParent();
7434     return BB;
7435   }
7436   case ARM::STRr_preidx:
7437   case ARM::STRBr_preidx:
7438   case ARM::STRH_preidx: {
7439     unsigned NewOpc;
7440     switch (MI->getOpcode()) {
7441     default: llvm_unreachable("unexpected opcode!");
7442     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7443     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7444     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7445     }
7446     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7447     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7448       MIB.addOperand(MI->getOperand(i));
7449     MI->eraseFromParent();
7450     return BB;
7451   }
7452
7453   case ARM::tMOVCCr_pseudo: {
7454     // To "insert" a SELECT_CC instruction, we actually have to insert the
7455     // diamond control-flow pattern.  The incoming instruction knows the
7456     // destination vreg to set, the condition code register to branch on, the
7457     // true/false values to select between, and a branch opcode to use.
7458     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7459     MachineFunction::iterator It = BB;
7460     ++It;
7461
7462     //  thisMBB:
7463     //  ...
7464     //   TrueVal = ...
7465     //   cmpTY ccX, r1, r2
7466     //   bCC copy1MBB
7467     //   fallthrough --> copy0MBB
7468     MachineBasicBlock *thisMBB  = BB;
7469     MachineFunction *F = BB->getParent();
7470     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7471     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7472     F->insert(It, copy0MBB);
7473     F->insert(It, sinkMBB);
7474
7475     // Transfer the remainder of BB and its successor edges to sinkMBB.
7476     sinkMBB->splice(sinkMBB->begin(), BB,
7477                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7478     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7479
7480     BB->addSuccessor(copy0MBB);
7481     BB->addSuccessor(sinkMBB);
7482
7483     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7484       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7485
7486     //  copy0MBB:
7487     //   %FalseValue = ...
7488     //   # fallthrough to sinkMBB
7489     BB = copy0MBB;
7490
7491     // Update machine-CFG edges
7492     BB->addSuccessor(sinkMBB);
7493
7494     //  sinkMBB:
7495     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7496     //  ...
7497     BB = sinkMBB;
7498     BuildMI(*BB, BB->begin(), dl,
7499             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7500       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7501       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7502
7503     MI->eraseFromParent();   // The pseudo instruction is gone now.
7504     return BB;
7505   }
7506
7507   case ARM::BCCi64:
7508   case ARM::BCCZi64: {
7509     // If there is an unconditional branch to the other successor, remove it.
7510     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7511
7512     // Compare both parts that make up the double comparison separately for
7513     // equality.
7514     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7515
7516     unsigned LHS1 = MI->getOperand(1).getReg();
7517     unsigned LHS2 = MI->getOperand(2).getReg();
7518     if (RHSisZero) {
7519       AddDefaultPred(BuildMI(BB, dl,
7520                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7521                      .addReg(LHS1).addImm(0));
7522       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7523         .addReg(LHS2).addImm(0)
7524         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7525     } else {
7526       unsigned RHS1 = MI->getOperand(3).getReg();
7527       unsigned RHS2 = MI->getOperand(4).getReg();
7528       AddDefaultPred(BuildMI(BB, dl,
7529                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7530                      .addReg(LHS1).addReg(RHS1));
7531       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7532         .addReg(LHS2).addReg(RHS2)
7533         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7534     }
7535
7536     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7537     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7538     if (MI->getOperand(0).getImm() == ARMCC::NE)
7539       std::swap(destMBB, exitMBB);
7540
7541     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7542       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7543     if (isThumb2)
7544       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7545     else
7546       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7547
7548     MI->eraseFromParent();   // The pseudo instruction is gone now.
7549     return BB;
7550   }
7551
7552   case ARM::Int_eh_sjlj_setjmp:
7553   case ARM::Int_eh_sjlj_setjmp_nofp:
7554   case ARM::tInt_eh_sjlj_setjmp:
7555   case ARM::t2Int_eh_sjlj_setjmp:
7556   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7557     EmitSjLjDispatchBlock(MI, BB);
7558     return BB;
7559
7560   case ARM::ABS:
7561   case ARM::t2ABS: {
7562     // To insert an ABS instruction, we have to insert the
7563     // diamond control-flow pattern.  The incoming instruction knows the
7564     // source vreg to test against 0, the destination vreg to set,
7565     // the condition code register to branch on, the
7566     // true/false values to select between, and a branch opcode to use.
7567     // It transforms
7568     //     V1 = ABS V0
7569     // into
7570     //     V2 = MOVS V0
7571     //     BCC                      (branch to SinkBB if V0 >= 0)
7572     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7573     //     SinkBB: V1 = PHI(V2, V3)
7574     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7575     MachineFunction::iterator BBI = BB;
7576     ++BBI;
7577     MachineFunction *Fn = BB->getParent();
7578     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7579     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7580     Fn->insert(BBI, RSBBB);
7581     Fn->insert(BBI, SinkBB);
7582
7583     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7584     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7585     bool ABSSrcKIll = MI->getOperand(1).isKill();
7586     bool isThumb2 = Subtarget->isThumb2();
7587     MachineRegisterInfo &MRI = Fn->getRegInfo();
7588     // In Thumb mode S must not be specified if source register is the SP or
7589     // PC and if destination register is the SP, so restrict register class
7590     unsigned NewRsbDstReg =
7591       MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
7592
7593     // Transfer the remainder of BB and its successor edges to sinkMBB.
7594     SinkBB->splice(SinkBB->begin(), BB,
7595                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
7596     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7597
7598     BB->addSuccessor(RSBBB);
7599     BB->addSuccessor(SinkBB);
7600
7601     // fall through to SinkMBB
7602     RSBBB->addSuccessor(SinkBB);
7603
7604     // insert a cmp at the end of BB
7605     AddDefaultPred(BuildMI(BB, dl,
7606                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7607                    .addReg(ABSSrcReg).addImm(0));
7608
7609     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7610     BuildMI(BB, dl,
7611       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7612       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7613
7614     // insert rsbri in RSBBB
7615     // Note: BCC and rsbri will be converted into predicated rsbmi
7616     // by if-conversion pass
7617     BuildMI(*RSBBB, RSBBB->begin(), dl,
7618       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7619       .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
7620       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7621
7622     // insert PHI in SinkBB,
7623     // reuse ABSDstReg to not change uses of ABS instruction
7624     BuildMI(*SinkBB, SinkBB->begin(), dl,
7625       TII->get(ARM::PHI), ABSDstReg)
7626       .addReg(NewRsbDstReg).addMBB(RSBBB)
7627       .addReg(ABSSrcReg).addMBB(BB);
7628
7629     // remove ABS instruction
7630     MI->eraseFromParent();
7631
7632     // return last added BB
7633     return SinkBB;
7634   }
7635   case ARM::COPY_STRUCT_BYVAL_I32:
7636     ++NumLoopByVals;
7637     return EmitStructByval(MI, BB);
7638   case ARM::WIN__CHKSTK:
7639     return EmitLowered__chkstk(MI, BB);
7640   }
7641 }
7642
7643 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7644                                                       SDNode *Node) const {
7645   const MCInstrDesc *MCID = &MI->getDesc();
7646   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7647   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7648   // operand is still set to noreg. If needed, set the optional operand's
7649   // register to CPSR, and remove the redundant implicit def.
7650   //
7651   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7652
7653   // Rename pseudo opcodes.
7654   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7655   if (NewOpc) {
7656     const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
7657     MCID = &TII->get(NewOpc);
7658
7659     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7660            "converted opcode should be the same except for cc_out");
7661
7662     MI->setDesc(*MCID);
7663
7664     // Add the optional cc_out operand
7665     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7666   }
7667   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7668
7669   // Any ARM instruction that sets the 's' bit should specify an optional
7670   // "cc_out" operand in the last operand position.
7671   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7672     assert(!NewOpc && "Optional cc_out operand required");
7673     return;
7674   }
7675   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7676   // since we already have an optional CPSR def.
7677   bool definesCPSR = false;
7678   bool deadCPSR = false;
7679   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7680        i != e; ++i) {
7681     const MachineOperand &MO = MI->getOperand(i);
7682     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7683       definesCPSR = true;
7684       if (MO.isDead())
7685         deadCPSR = true;
7686       MI->RemoveOperand(i);
7687       break;
7688     }
7689   }
7690   if (!definesCPSR) {
7691     assert(!NewOpc && "Optional cc_out operand required");
7692     return;
7693   }
7694   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7695   if (deadCPSR) {
7696     assert(!MI->getOperand(ccOutIdx).getReg() &&
7697            "expect uninitialized optional cc_out operand");
7698     return;
7699   }
7700
7701   // If this instruction was defined with an optional CPSR def and its dag node
7702   // had a live implicit CPSR def, then activate the optional CPSR def.
7703   MachineOperand &MO = MI->getOperand(ccOutIdx);
7704   MO.setReg(ARM::CPSR);
7705   MO.setIsDef(true);
7706 }
7707
7708 //===----------------------------------------------------------------------===//
7709 //                           ARM Optimization Hooks
7710 //===----------------------------------------------------------------------===//
7711
7712 // Helper function that checks if N is a null or all ones constant.
7713 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7714   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7715   if (!C)
7716     return false;
7717   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7718 }
7719
7720 // Return true if N is conditionally 0 or all ones.
7721 // Detects these expressions where cc is an i1 value:
7722 //
7723 //   (select cc 0, y)   [AllOnes=0]
7724 //   (select cc y, 0)   [AllOnes=0]
7725 //   (zext cc)          [AllOnes=0]
7726 //   (sext cc)          [AllOnes=0/1]
7727 //   (select cc -1, y)  [AllOnes=1]
7728 //   (select cc y, -1)  [AllOnes=1]
7729 //
7730 // Invert is set when N is the null/all ones constant when CC is false.
7731 // OtherOp is set to the alternative value of N.
7732 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7733                                        SDValue &CC, bool &Invert,
7734                                        SDValue &OtherOp,
7735                                        SelectionDAG &DAG) {
7736   switch (N->getOpcode()) {
7737   default: return false;
7738   case ISD::SELECT: {
7739     CC = N->getOperand(0);
7740     SDValue N1 = N->getOperand(1);
7741     SDValue N2 = N->getOperand(2);
7742     if (isZeroOrAllOnes(N1, AllOnes)) {
7743       Invert = false;
7744       OtherOp = N2;
7745       return true;
7746     }
7747     if (isZeroOrAllOnes(N2, AllOnes)) {
7748       Invert = true;
7749       OtherOp = N1;
7750       return true;
7751     }
7752     return false;
7753   }
7754   case ISD::ZERO_EXTEND:
7755     // (zext cc) can never be the all ones value.
7756     if (AllOnes)
7757       return false;
7758     // Fall through.
7759   case ISD::SIGN_EXTEND: {
7760     SDLoc dl(N);
7761     EVT VT = N->getValueType(0);
7762     CC = N->getOperand(0);
7763     if (CC.getValueType() != MVT::i1)
7764       return false;
7765     Invert = !AllOnes;
7766     if (AllOnes)
7767       // When looking for an AllOnes constant, N is an sext, and the 'other'
7768       // value is 0.
7769       OtherOp = DAG.getConstant(0, dl, VT);
7770     else if (N->getOpcode() == ISD::ZERO_EXTEND)
7771       // When looking for a 0 constant, N can be zext or sext.
7772       OtherOp = DAG.getConstant(1, dl, VT);
7773     else
7774       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
7775                                 VT);
7776     return true;
7777   }
7778   }
7779 }
7780
7781 // Combine a constant select operand into its use:
7782 //
7783 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
7784 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
7785 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
7786 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
7787 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
7788 //
7789 // The transform is rejected if the select doesn't have a constant operand that
7790 // is null, or all ones when AllOnes is set.
7791 //
7792 // Also recognize sext/zext from i1:
7793 //
7794 //   (add (zext cc), x) -> (select cc (add x, 1), x)
7795 //   (add (sext cc), x) -> (select cc (add x, -1), x)
7796 //
7797 // These transformations eventually create predicated instructions.
7798 //
7799 // @param N       The node to transform.
7800 // @param Slct    The N operand that is a select.
7801 // @param OtherOp The other N operand (x above).
7802 // @param DCI     Context.
7803 // @param AllOnes Require the select constant to be all ones instead of null.
7804 // @returns The new node, or SDValue() on failure.
7805 static
7806 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7807                             TargetLowering::DAGCombinerInfo &DCI,
7808                             bool AllOnes = false) {
7809   SelectionDAG &DAG = DCI.DAG;
7810   EVT VT = N->getValueType(0);
7811   SDValue NonConstantVal;
7812   SDValue CCOp;
7813   bool SwapSelectOps;
7814   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7815                                   NonConstantVal, DAG))
7816     return SDValue();
7817
7818   // Slct is now know to be the desired identity constant when CC is true.
7819   SDValue TrueVal = OtherOp;
7820   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7821                                  OtherOp, NonConstantVal);
7822   // Unless SwapSelectOps says CC should be false.
7823   if (SwapSelectOps)
7824     std::swap(TrueVal, FalseVal);
7825
7826   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7827                      CCOp, TrueVal, FalseVal);
7828 }
7829
7830 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7831 static
7832 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7833                                        TargetLowering::DAGCombinerInfo &DCI) {
7834   SDValue N0 = N->getOperand(0);
7835   SDValue N1 = N->getOperand(1);
7836   if (N0.getNode()->hasOneUse()) {
7837     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7838     if (Result.getNode())
7839       return Result;
7840   }
7841   if (N1.getNode()->hasOneUse()) {
7842     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7843     if (Result.getNode())
7844       return Result;
7845   }
7846   return SDValue();
7847 }
7848
7849 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7850 // (only after legalization).
7851 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7852                                  TargetLowering::DAGCombinerInfo &DCI,
7853                                  const ARMSubtarget *Subtarget) {
7854
7855   // Only perform optimization if after legalize, and if NEON is available. We
7856   // also expected both operands to be BUILD_VECTORs.
7857   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7858       || N0.getOpcode() != ISD::BUILD_VECTOR
7859       || N1.getOpcode() != ISD::BUILD_VECTOR)
7860     return SDValue();
7861
7862   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7863   EVT VT = N->getValueType(0);
7864   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7865     return SDValue();
7866
7867   // Check that the vector operands are of the right form.
7868   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7869   // operands, where N is the size of the formed vector.
7870   // Each EXTRACT_VECTOR should have the same input vector and odd or even
7871   // index such that we have a pair wise add pattern.
7872
7873   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7874   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7875     return SDValue();
7876   SDValue Vec = N0->getOperand(0)->getOperand(0);
7877   SDNode *V = Vec.getNode();
7878   unsigned nextIndex = 0;
7879
7880   // For each operands to the ADD which are BUILD_VECTORs,
7881   // check to see if each of their operands are an EXTRACT_VECTOR with
7882   // the same vector and appropriate index.
7883   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7884     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7885         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7886
7887       SDValue ExtVec0 = N0->getOperand(i);
7888       SDValue ExtVec1 = N1->getOperand(i);
7889
7890       // First operand is the vector, verify its the same.
7891       if (V != ExtVec0->getOperand(0).getNode() ||
7892           V != ExtVec1->getOperand(0).getNode())
7893         return SDValue();
7894
7895       // Second is the constant, verify its correct.
7896       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7897       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7898
7899       // For the constant, we want to see all the even or all the odd.
7900       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7901           || C1->getZExtValue() != nextIndex+1)
7902         return SDValue();
7903
7904       // Increment index.
7905       nextIndex+=2;
7906     } else
7907       return SDValue();
7908   }
7909
7910   // Create VPADDL node.
7911   SelectionDAG &DAG = DCI.DAG;
7912   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7913
7914   SDLoc dl(N);
7915
7916   // Build operand list.
7917   SmallVector<SDValue, 8> Ops;
7918   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
7919                                 TLI.getPointerTy()));
7920
7921   // Input is the vector.
7922   Ops.push_back(Vec);
7923
7924   // Get widened type and narrowed type.
7925   MVT widenType;
7926   unsigned numElem = VT.getVectorNumElements();
7927   
7928   EVT inputLaneType = Vec.getValueType().getVectorElementType();
7929   switch (inputLaneType.getSimpleVT().SimpleTy) {
7930     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7931     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7932     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7933     default:
7934       llvm_unreachable("Invalid vector element type for padd optimization.");
7935   }
7936
7937   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
7938   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
7939   return DAG.getNode(ExtOp, dl, VT, tmp);
7940 }
7941
7942 static SDValue findMUL_LOHI(SDValue V) {
7943   if (V->getOpcode() == ISD::UMUL_LOHI ||
7944       V->getOpcode() == ISD::SMUL_LOHI)
7945     return V;
7946   return SDValue();
7947 }
7948
7949 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7950                                      TargetLowering::DAGCombinerInfo &DCI,
7951                                      const ARMSubtarget *Subtarget) {
7952
7953   if (Subtarget->isThumb1Only()) return SDValue();
7954
7955   // Only perform the checks after legalize when the pattern is available.
7956   if (DCI.isBeforeLegalize()) return SDValue();
7957
7958   // Look for multiply add opportunities.
7959   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7960   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7961   // a glue link from the first add to the second add.
7962   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7963   // a S/UMLAL instruction.
7964   //          loAdd   UMUL_LOHI
7965   //            \    / :lo    \ :hi
7966   //             \  /          \          [no multiline comment]
7967   //              ADDC         |  hiAdd
7968   //                 \ :glue  /  /
7969   //                  \      /  /
7970   //                    ADDE
7971   //
7972   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7973   SDValue AddcOp0 = AddcNode->getOperand(0);
7974   SDValue AddcOp1 = AddcNode->getOperand(1);
7975
7976   // Check if the two operands are from the same mul_lohi node.
7977   if (AddcOp0.getNode() == AddcOp1.getNode())
7978     return SDValue();
7979
7980   assert(AddcNode->getNumValues() == 2 &&
7981          AddcNode->getValueType(0) == MVT::i32 &&
7982          "Expect ADDC with two result values. First: i32");
7983
7984   // Check that we have a glued ADDC node.
7985   if (AddcNode->getValueType(1) != MVT::Glue)
7986     return SDValue();
7987
7988   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7989   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7990       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7991       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7992       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7993     return SDValue();
7994
7995   // Look for the glued ADDE.
7996   SDNode* AddeNode = AddcNode->getGluedUser();
7997   if (!AddeNode)
7998     return SDValue();
7999
8000   // Make sure it is really an ADDE.
8001   if (AddeNode->getOpcode() != ISD::ADDE)
8002     return SDValue();
8003
8004   assert(AddeNode->getNumOperands() == 3 &&
8005          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8006          "ADDE node has the wrong inputs");
8007
8008   // Check for the triangle shape.
8009   SDValue AddeOp0 = AddeNode->getOperand(0);
8010   SDValue AddeOp1 = AddeNode->getOperand(1);
8011
8012   // Make sure that the ADDE operands are not coming from the same node.
8013   if (AddeOp0.getNode() == AddeOp1.getNode())
8014     return SDValue();
8015
8016   // Find the MUL_LOHI node walking up ADDE's operands.
8017   bool IsLeftOperandMUL = false;
8018   SDValue MULOp = findMUL_LOHI(AddeOp0);
8019   if (MULOp == SDValue())
8020    MULOp = findMUL_LOHI(AddeOp1);
8021   else
8022     IsLeftOperandMUL = true;
8023   if (MULOp == SDValue())
8024     return SDValue();
8025
8026   // Figure out the right opcode.
8027   unsigned Opc = MULOp->getOpcode();
8028   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8029
8030   // Figure out the high and low input values to the MLAL node.
8031   SDValue* HiAdd = nullptr;
8032   SDValue* LoMul = nullptr;
8033   SDValue* LowAdd = nullptr;
8034
8035   // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
8036   if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
8037     return SDValue();
8038
8039   if (IsLeftOperandMUL)
8040     HiAdd = &AddeOp1;
8041   else
8042     HiAdd = &AddeOp0;
8043
8044
8045   // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
8046   // whose low result is fed to the ADDC we are checking.
8047
8048   if (AddcOp0 == MULOp.getValue(0)) {
8049     LoMul = &AddcOp0;
8050     LowAdd = &AddcOp1;
8051   }
8052   if (AddcOp1 == MULOp.getValue(0)) {
8053     LoMul = &AddcOp1;
8054     LowAdd = &AddcOp0;
8055   }
8056
8057   if (!LoMul)
8058     return SDValue();
8059
8060   // Create the merged node.
8061   SelectionDAG &DAG = DCI.DAG;
8062
8063   // Build operand list.
8064   SmallVector<SDValue, 8> Ops;
8065   Ops.push_back(LoMul->getOperand(0));
8066   Ops.push_back(LoMul->getOperand(1));
8067   Ops.push_back(*LowAdd);
8068   Ops.push_back(*HiAdd);
8069
8070   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
8071                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
8072
8073   // Replace the ADDs' nodes uses by the MLA node's values.
8074   SDValue HiMLALResult(MLALNode.getNode(), 1);
8075   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8076
8077   SDValue LoMLALResult(MLALNode.getNode(), 0);
8078   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8079
8080   // Return original node to notify the driver to stop replacing.
8081   SDValue resNode(AddcNode, 0);
8082   return resNode;
8083 }
8084
8085 /// PerformADDCCombine - Target-specific dag combine transform from
8086 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8087 static SDValue PerformADDCCombine(SDNode *N,
8088                                  TargetLowering::DAGCombinerInfo &DCI,
8089                                  const ARMSubtarget *Subtarget) {
8090
8091   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8092
8093 }
8094
8095 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8096 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
8097 /// called with the default operands, and if that fails, with commuted
8098 /// operands.
8099 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8100                                           TargetLowering::DAGCombinerInfo &DCI,
8101                                           const ARMSubtarget *Subtarget){
8102
8103   // Attempt to create vpaddl for this add.
8104   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8105   if (Result.getNode())
8106     return Result;
8107
8108   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8109   if (N0.getNode()->hasOneUse()) {
8110     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8111     if (Result.getNode()) return Result;
8112   }
8113   return SDValue();
8114 }
8115
8116 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8117 ///
8118 static SDValue PerformADDCombine(SDNode *N,
8119                                  TargetLowering::DAGCombinerInfo &DCI,
8120                                  const ARMSubtarget *Subtarget) {
8121   SDValue N0 = N->getOperand(0);
8122   SDValue N1 = N->getOperand(1);
8123
8124   // First try with the default operand order.
8125   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8126   if (Result.getNode())
8127     return Result;
8128
8129   // If that didn't work, try again with the operands commuted.
8130   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8131 }
8132
8133 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8134 ///
8135 static SDValue PerformSUBCombine(SDNode *N,
8136                                  TargetLowering::DAGCombinerInfo &DCI) {
8137   SDValue N0 = N->getOperand(0);
8138   SDValue N1 = N->getOperand(1);
8139
8140   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8141   if (N1.getNode()->hasOneUse()) {
8142     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8143     if (Result.getNode()) return Result;
8144   }
8145
8146   return SDValue();
8147 }
8148
8149 /// PerformVMULCombine
8150 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8151 /// special multiplier accumulator forwarding.
8152 ///   vmul d3, d0, d2
8153 ///   vmla d3, d1, d2
8154 /// is faster than
8155 ///   vadd d3, d0, d1
8156 ///   vmul d3, d3, d2
8157 //  However, for (A + B) * (A + B),
8158 //    vadd d2, d0, d1
8159 //    vmul d3, d0, d2
8160 //    vmla d3, d1, d2
8161 //  is slower than
8162 //    vadd d2, d0, d1
8163 //    vmul d3, d2, d2
8164 static SDValue PerformVMULCombine(SDNode *N,
8165                                   TargetLowering::DAGCombinerInfo &DCI,
8166                                   const ARMSubtarget *Subtarget) {
8167   if (!Subtarget->hasVMLxForwarding())
8168     return SDValue();
8169
8170   SelectionDAG &DAG = DCI.DAG;
8171   SDValue N0 = N->getOperand(0);
8172   SDValue N1 = N->getOperand(1);
8173   unsigned Opcode = N0.getOpcode();
8174   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8175       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8176     Opcode = N1.getOpcode();
8177     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8178         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8179       return SDValue();
8180     std::swap(N0, N1);
8181   }
8182
8183   if (N0 == N1)
8184     return SDValue();
8185
8186   EVT VT = N->getValueType(0);
8187   SDLoc DL(N);
8188   SDValue N00 = N0->getOperand(0);
8189   SDValue N01 = N0->getOperand(1);
8190   return DAG.getNode(Opcode, DL, VT,
8191                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8192                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8193 }
8194
8195 static SDValue PerformMULCombine(SDNode *N,
8196                                  TargetLowering::DAGCombinerInfo &DCI,
8197                                  const ARMSubtarget *Subtarget) {
8198   SelectionDAG &DAG = DCI.DAG;
8199
8200   if (Subtarget->isThumb1Only())
8201     return SDValue();
8202
8203   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8204     return SDValue();
8205
8206   EVT VT = N->getValueType(0);
8207   if (VT.is64BitVector() || VT.is128BitVector())
8208     return PerformVMULCombine(N, DCI, Subtarget);
8209   if (VT != MVT::i32)
8210     return SDValue();
8211
8212   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8213   if (!C)
8214     return SDValue();
8215
8216   int64_t MulAmt = C->getSExtValue();
8217   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8218
8219   ShiftAmt = ShiftAmt & (32 - 1);
8220   SDValue V = N->getOperand(0);
8221   SDLoc DL(N);
8222
8223   SDValue Res;
8224   MulAmt >>= ShiftAmt;
8225
8226   if (MulAmt >= 0) {
8227     if (isPowerOf2_32(MulAmt - 1)) {
8228       // (mul x, 2^N + 1) => (add (shl x, N), x)
8229       Res = DAG.getNode(ISD::ADD, DL, VT,
8230                         V,
8231                         DAG.getNode(ISD::SHL, DL, VT,
8232                                     V,
8233                                     DAG.getConstant(Log2_32(MulAmt - 1), DL,
8234                                                     MVT::i32)));
8235     } else if (isPowerOf2_32(MulAmt + 1)) {
8236       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8237       Res = DAG.getNode(ISD::SUB, DL, VT,
8238                         DAG.getNode(ISD::SHL, DL, VT,
8239                                     V,
8240                                     DAG.getConstant(Log2_32(MulAmt + 1), DL,
8241                                                     MVT::i32)),
8242                         V);
8243     } else
8244       return SDValue();
8245   } else {
8246     uint64_t MulAmtAbs = -MulAmt;
8247     if (isPowerOf2_32(MulAmtAbs + 1)) {
8248       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8249       Res = DAG.getNode(ISD::SUB, DL, VT,
8250                         V,
8251                         DAG.getNode(ISD::SHL, DL, VT,
8252                                     V,
8253                                     DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
8254                                                     MVT::i32)));
8255     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8256       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8257       Res = DAG.getNode(ISD::ADD, DL, VT,
8258                         V,
8259                         DAG.getNode(ISD::SHL, DL, VT,
8260                                     V,
8261                                     DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
8262                                                     MVT::i32)));
8263       Res = DAG.getNode(ISD::SUB, DL, VT,
8264                         DAG.getConstant(0, DL, MVT::i32), Res);
8265
8266     } else
8267       return SDValue();
8268   }
8269
8270   if (ShiftAmt != 0)
8271     Res = DAG.getNode(ISD::SHL, DL, VT,
8272                       Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
8273
8274   // Do not add new nodes to DAG combiner worklist.
8275   DCI.CombineTo(N, Res, false);
8276   return SDValue();
8277 }
8278
8279 static SDValue PerformANDCombine(SDNode *N,
8280                                  TargetLowering::DAGCombinerInfo &DCI,
8281                                  const ARMSubtarget *Subtarget) {
8282
8283   // Attempt to use immediate-form VBIC
8284   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8285   SDLoc dl(N);
8286   EVT VT = N->getValueType(0);
8287   SelectionDAG &DAG = DCI.DAG;
8288
8289   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8290     return SDValue();
8291
8292   APInt SplatBits, SplatUndef;
8293   unsigned SplatBitSize;
8294   bool HasAnyUndefs;
8295   if (BVN &&
8296       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8297     if (SplatBitSize <= 64) {
8298       EVT VbicVT;
8299       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8300                                       SplatUndef.getZExtValue(), SplatBitSize,
8301                                       DAG, dl, VbicVT, VT.is128BitVector(),
8302                                       OtherModImm);
8303       if (Val.getNode()) {
8304         SDValue Input =
8305           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8306         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8307         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8308       }
8309     }
8310   }
8311
8312   if (!Subtarget->isThumb1Only()) {
8313     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8314     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8315     if (Result.getNode())
8316       return Result;
8317   }
8318
8319   return SDValue();
8320 }
8321
8322 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8323 static SDValue PerformORCombine(SDNode *N,
8324                                 TargetLowering::DAGCombinerInfo &DCI,
8325                                 const ARMSubtarget *Subtarget) {
8326   // Attempt to use immediate-form VORR
8327   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8328   SDLoc dl(N);
8329   EVT VT = N->getValueType(0);
8330   SelectionDAG &DAG = DCI.DAG;
8331
8332   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8333     return SDValue();
8334
8335   APInt SplatBits, SplatUndef;
8336   unsigned SplatBitSize;
8337   bool HasAnyUndefs;
8338   if (BVN && Subtarget->hasNEON() &&
8339       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8340     if (SplatBitSize <= 64) {
8341       EVT VorrVT;
8342       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8343                                       SplatUndef.getZExtValue(), SplatBitSize,
8344                                       DAG, dl, VorrVT, VT.is128BitVector(),
8345                                       OtherModImm);
8346       if (Val.getNode()) {
8347         SDValue Input =
8348           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8349         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8350         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8351       }
8352     }
8353   }
8354
8355   if (!Subtarget->isThumb1Only()) {
8356     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8357     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8358     if (Result.getNode())
8359       return Result;
8360   }
8361
8362   // The code below optimizes (or (and X, Y), Z).
8363   // The AND operand needs to have a single user to make these optimizations
8364   // profitable.
8365   SDValue N0 = N->getOperand(0);
8366   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8367     return SDValue();
8368   SDValue N1 = N->getOperand(1);
8369
8370   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8371   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8372       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8373     APInt SplatUndef;
8374     unsigned SplatBitSize;
8375     bool HasAnyUndefs;
8376
8377     APInt SplatBits0, SplatBits1;
8378     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8379     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8380     // Ensure that the second operand of both ands are constants
8381     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8382                                       HasAnyUndefs) && !HasAnyUndefs) {
8383         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8384                                           HasAnyUndefs) && !HasAnyUndefs) {
8385             // Ensure that the bit width of the constants are the same and that
8386             // the splat arguments are logical inverses as per the pattern we
8387             // are trying to simplify.
8388             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8389                 SplatBits0 == ~SplatBits1) {
8390                 // Canonicalize the vector type to make instruction selection
8391                 // simpler.
8392                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8393                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8394                                              N0->getOperand(1),
8395                                              N0->getOperand(0),
8396                                              N1->getOperand(0));
8397                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8398             }
8399         }
8400     }
8401   }
8402
8403   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8404   // reasonable.
8405
8406   // BFI is only available on V6T2+
8407   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8408     return SDValue();
8409
8410   SDLoc DL(N);
8411   // 1) or (and A, mask), val => ARMbfi A, val, mask
8412   //      iff (val & mask) == val
8413   //
8414   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8415   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8416   //          && mask == ~mask2
8417   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8418   //          && ~mask == mask2
8419   //  (i.e., copy a bitfield value into another bitfield of the same width)
8420
8421   if (VT != MVT::i32)
8422     return SDValue();
8423
8424   SDValue N00 = N0.getOperand(0);
8425
8426   // The value and the mask need to be constants so we can verify this is
8427   // actually a bitfield set. If the mask is 0xffff, we can do better
8428   // via a movt instruction, so don't use BFI in that case.
8429   SDValue MaskOp = N0.getOperand(1);
8430   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8431   if (!MaskC)
8432     return SDValue();
8433   unsigned Mask = MaskC->getZExtValue();
8434   if (Mask == 0xffff)
8435     return SDValue();
8436   SDValue Res;
8437   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8438   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8439   if (N1C) {
8440     unsigned Val = N1C->getZExtValue();
8441     if ((Val & ~Mask) != Val)
8442       return SDValue();
8443
8444     if (ARM::isBitFieldInvertedMask(Mask)) {
8445       Val >>= countTrailingZeros(~Mask);
8446
8447       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8448                         DAG.getConstant(Val, DL, MVT::i32),
8449                         DAG.getConstant(Mask, DL, MVT::i32));
8450
8451       // Do not add new nodes to DAG combiner worklist.
8452       DCI.CombineTo(N, Res, false);
8453       return SDValue();
8454     }
8455   } else if (N1.getOpcode() == ISD::AND) {
8456     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8457     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8458     if (!N11C)
8459       return SDValue();
8460     unsigned Mask2 = N11C->getZExtValue();
8461
8462     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8463     // as is to match.
8464     if (ARM::isBitFieldInvertedMask(Mask) &&
8465         (Mask == ~Mask2)) {
8466       // The pack halfword instruction works better for masks that fit it,
8467       // so use that when it's available.
8468       if (Subtarget->hasT2ExtractPack() &&
8469           (Mask == 0xffff || Mask == 0xffff0000))
8470         return SDValue();
8471       // 2a
8472       unsigned amt = countTrailingZeros(Mask2);
8473       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8474                         DAG.getConstant(amt, DL, MVT::i32));
8475       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8476                         DAG.getConstant(Mask, DL, MVT::i32));
8477       // Do not add new nodes to DAG combiner worklist.
8478       DCI.CombineTo(N, Res, false);
8479       return SDValue();
8480     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8481                (~Mask == Mask2)) {
8482       // The pack halfword instruction works better for masks that fit it,
8483       // so use that when it's available.
8484       if (Subtarget->hasT2ExtractPack() &&
8485           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8486         return SDValue();
8487       // 2b
8488       unsigned lsb = countTrailingZeros(Mask);
8489       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8490                         DAG.getConstant(lsb, DL, MVT::i32));
8491       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8492                         DAG.getConstant(Mask2, DL, MVT::i32));
8493       // Do not add new nodes to DAG combiner worklist.
8494       DCI.CombineTo(N, Res, false);
8495       return SDValue();
8496     }
8497   }
8498
8499   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8500       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8501       ARM::isBitFieldInvertedMask(~Mask)) {
8502     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8503     // where lsb(mask) == #shamt and masked bits of B are known zero.
8504     SDValue ShAmt = N00.getOperand(1);
8505     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8506     unsigned LSB = countTrailingZeros(Mask);
8507     if (ShAmtC != LSB)
8508       return SDValue();
8509
8510     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8511                       DAG.getConstant(~Mask, DL, MVT::i32));
8512
8513     // Do not add new nodes to DAG combiner worklist.
8514     DCI.CombineTo(N, Res, false);
8515   }
8516
8517   return SDValue();
8518 }
8519
8520 static SDValue PerformXORCombine(SDNode *N,
8521                                  TargetLowering::DAGCombinerInfo &DCI,
8522                                  const ARMSubtarget *Subtarget) {
8523   EVT VT = N->getValueType(0);
8524   SelectionDAG &DAG = DCI.DAG;
8525
8526   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8527     return SDValue();
8528
8529   if (!Subtarget->isThumb1Only()) {
8530     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8531     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8532     if (Result.getNode())
8533       return Result;
8534   }
8535
8536   return SDValue();
8537 }
8538
8539 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8540 /// the bits being cleared by the AND are not demanded by the BFI.
8541 static SDValue PerformBFICombine(SDNode *N,
8542                                  TargetLowering::DAGCombinerInfo &DCI) {
8543   SDValue N1 = N->getOperand(1);
8544   if (N1.getOpcode() == ISD::AND) {
8545     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8546     if (!N11C)
8547       return SDValue();
8548     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8549     unsigned LSB = countTrailingZeros(~InvMask);
8550     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8551     assert(Width <
8552                static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
8553            "undefined behavior");
8554     unsigned Mask = (1u << Width) - 1;
8555     unsigned Mask2 = N11C->getZExtValue();
8556     if ((Mask & (~Mask2)) == 0)
8557       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8558                              N->getOperand(0), N1.getOperand(0),
8559                              N->getOperand(2));
8560   }
8561   return SDValue();
8562 }
8563
8564 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8565 /// ARMISD::VMOVRRD.
8566 static SDValue PerformVMOVRRDCombine(SDNode *N,
8567                                      TargetLowering::DAGCombinerInfo &DCI,
8568                                      const ARMSubtarget *Subtarget) {
8569   // vmovrrd(vmovdrr x, y) -> x,y
8570   SDValue InDouble = N->getOperand(0);
8571   if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
8572     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8573
8574   // vmovrrd(load f64) -> (load i32), (load i32)
8575   SDNode *InNode = InDouble.getNode();
8576   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8577       InNode->getValueType(0) == MVT::f64 &&
8578       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8579       !cast<LoadSDNode>(InNode)->isVolatile()) {
8580     // TODO: Should this be done for non-FrameIndex operands?
8581     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8582
8583     SelectionDAG &DAG = DCI.DAG;
8584     SDLoc DL(LD);
8585     SDValue BasePtr = LD->getBasePtr();
8586     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8587                                  LD->getPointerInfo(), LD->isVolatile(),
8588                                  LD->isNonTemporal(), LD->isInvariant(),
8589                                  LD->getAlignment());
8590
8591     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8592                                     DAG.getConstant(4, DL, MVT::i32));
8593     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8594                                  LD->getPointerInfo(), LD->isVolatile(),
8595                                  LD->isNonTemporal(), LD->isInvariant(),
8596                                  std::min(4U, LD->getAlignment() / 2));
8597
8598     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8599     if (DCI.DAG.getTargetLoweringInfo().isBigEndian())
8600       std::swap (NewLD1, NewLD2);
8601     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8602     return Result;
8603   }
8604
8605   return SDValue();
8606 }
8607
8608 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8609 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8610 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8611   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8612   SDValue Op0 = N->getOperand(0);
8613   SDValue Op1 = N->getOperand(1);
8614   if (Op0.getOpcode() == ISD::BITCAST)
8615     Op0 = Op0.getOperand(0);
8616   if (Op1.getOpcode() == ISD::BITCAST)
8617     Op1 = Op1.getOperand(0);
8618   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8619       Op0.getNode() == Op1.getNode() &&
8620       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8621     return DAG.getNode(ISD::BITCAST, SDLoc(N),
8622                        N->getValueType(0), Op0.getOperand(0));
8623   return SDValue();
8624 }
8625
8626 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8627 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8628 /// i64 vector to have f64 elements, since the value can then be loaded
8629 /// directly into a VFP register.
8630 static bool hasNormalLoadOperand(SDNode *N) {
8631   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8632   for (unsigned i = 0; i < NumElts; ++i) {
8633     SDNode *Elt = N->getOperand(i).getNode();
8634     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8635       return true;
8636   }
8637   return false;
8638 }
8639
8640 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8641 /// ISD::BUILD_VECTOR.
8642 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8643                                           TargetLowering::DAGCombinerInfo &DCI,
8644                                           const ARMSubtarget *Subtarget) {
8645   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8646   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
8647   // into a pair of GPRs, which is fine when the value is used as a scalar,
8648   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8649   SelectionDAG &DAG = DCI.DAG;
8650   if (N->getNumOperands() == 2) {
8651     SDValue RV = PerformVMOVDRRCombine(N, DAG);
8652     if (RV.getNode())
8653       return RV;
8654   }
8655
8656   // Load i64 elements as f64 values so that type legalization does not split
8657   // them up into i32 values.
8658   EVT VT = N->getValueType(0);
8659   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8660     return SDValue();
8661   SDLoc dl(N);
8662   SmallVector<SDValue, 8> Ops;
8663   unsigned NumElts = VT.getVectorNumElements();
8664   for (unsigned i = 0; i < NumElts; ++i) {
8665     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8666     Ops.push_back(V);
8667     // Make the DAGCombiner fold the bitcast.
8668     DCI.AddToWorklist(V.getNode());
8669   }
8670   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8671   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8672   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8673 }
8674
8675 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8676 static SDValue
8677 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8678   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8679   // At that time, we may have inserted bitcasts from integer to float.
8680   // If these bitcasts have survived DAGCombine, change the lowering of this
8681   // BUILD_VECTOR in something more vector friendly, i.e., that does not
8682   // force to use floating point types.
8683
8684   // Make sure we can change the type of the vector.
8685   // This is possible iff:
8686   // 1. The vector is only used in a bitcast to a integer type. I.e.,
8687   //    1.1. Vector is used only once.
8688   //    1.2. Use is a bit convert to an integer type.
8689   // 2. The size of its operands are 32-bits (64-bits are not legal).
8690   EVT VT = N->getValueType(0);
8691   EVT EltVT = VT.getVectorElementType();
8692
8693   // Check 1.1. and 2.
8694   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8695     return SDValue();
8696
8697   // By construction, the input type must be float.
8698   assert(EltVT == MVT::f32 && "Unexpected type!");
8699
8700   // Check 1.2.
8701   SDNode *Use = *N->use_begin();
8702   if (Use->getOpcode() != ISD::BITCAST ||
8703       Use->getValueType(0).isFloatingPoint())
8704     return SDValue();
8705
8706   // Check profitability.
8707   // Model is, if more than half of the relevant operands are bitcast from
8708   // i32, turn the build_vector into a sequence of insert_vector_elt.
8709   // Relevant operands are everything that is not statically
8710   // (i.e., at compile time) bitcasted.
8711   unsigned NumOfBitCastedElts = 0;
8712   unsigned NumElts = VT.getVectorNumElements();
8713   unsigned NumOfRelevantElts = NumElts;
8714   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8715     SDValue Elt = N->getOperand(Idx);
8716     if (Elt->getOpcode() == ISD::BITCAST) {
8717       // Assume only bit cast to i32 will go away.
8718       if (Elt->getOperand(0).getValueType() == MVT::i32)
8719         ++NumOfBitCastedElts;
8720     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8721       // Constants are statically casted, thus do not count them as
8722       // relevant operands.
8723       --NumOfRelevantElts;
8724   }
8725
8726   // Check if more than half of the elements require a non-free bitcast.
8727   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8728     return SDValue();
8729
8730   SelectionDAG &DAG = DCI.DAG;
8731   // Create the new vector type.
8732   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8733   // Check if the type is legal.
8734   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8735   if (!TLI.isTypeLegal(VecVT))
8736     return SDValue();
8737
8738   // Combine:
8739   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8740   // => BITCAST INSERT_VECTOR_ELT
8741   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8742   //                      (BITCAST EN), N.
8743   SDValue Vec = DAG.getUNDEF(VecVT);
8744   SDLoc dl(N);
8745   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8746     SDValue V = N->getOperand(Idx);
8747     if (V.getOpcode() == ISD::UNDEF)
8748       continue;
8749     if (V.getOpcode() == ISD::BITCAST &&
8750         V->getOperand(0).getValueType() == MVT::i32)
8751       // Fold obvious case.
8752       V = V.getOperand(0);
8753     else {
8754       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
8755       // Make the DAGCombiner fold the bitcasts.
8756       DCI.AddToWorklist(V.getNode());
8757     }
8758     SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
8759     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8760   }
8761   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8762   // Make the DAGCombiner fold the bitcasts.
8763   DCI.AddToWorklist(Vec.getNode());
8764   return Vec;
8765 }
8766
8767 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8768 /// ISD::INSERT_VECTOR_ELT.
8769 static SDValue PerformInsertEltCombine(SDNode *N,
8770                                        TargetLowering::DAGCombinerInfo &DCI) {
8771   // Bitcast an i64 load inserted into a vector to f64.
8772   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8773   EVT VT = N->getValueType(0);
8774   SDNode *Elt = N->getOperand(1).getNode();
8775   if (VT.getVectorElementType() != MVT::i64 ||
8776       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8777     return SDValue();
8778
8779   SelectionDAG &DAG = DCI.DAG;
8780   SDLoc dl(N);
8781   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8782                                  VT.getVectorNumElements());
8783   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8784   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8785   // Make the DAGCombiner fold the bitcasts.
8786   DCI.AddToWorklist(Vec.getNode());
8787   DCI.AddToWorklist(V.getNode());
8788   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8789                                Vec, V, N->getOperand(2));
8790   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8791 }
8792
8793 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8794 /// ISD::VECTOR_SHUFFLE.
8795 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8796   // The LLVM shufflevector instruction does not require the shuffle mask
8797   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8798   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
8799   // operands do not match the mask length, they are extended by concatenating
8800   // them with undef vectors.  That is probably the right thing for other
8801   // targets, but for NEON it is better to concatenate two double-register
8802   // size vector operands into a single quad-register size vector.  Do that
8803   // transformation here:
8804   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
8805   //   shuffle(concat(v1, v2), undef)
8806   SDValue Op0 = N->getOperand(0);
8807   SDValue Op1 = N->getOperand(1);
8808   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8809       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8810       Op0.getNumOperands() != 2 ||
8811       Op1.getNumOperands() != 2)
8812     return SDValue();
8813   SDValue Concat0Op1 = Op0.getOperand(1);
8814   SDValue Concat1Op1 = Op1.getOperand(1);
8815   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8816       Concat1Op1.getOpcode() != ISD::UNDEF)
8817     return SDValue();
8818   // Skip the transformation if any of the types are illegal.
8819   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8820   EVT VT = N->getValueType(0);
8821   if (!TLI.isTypeLegal(VT) ||
8822       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8823       !TLI.isTypeLegal(Concat1Op1.getValueType()))
8824     return SDValue();
8825
8826   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
8827                                   Op0.getOperand(0), Op1.getOperand(0));
8828   // Translate the shuffle mask.
8829   SmallVector<int, 16> NewMask;
8830   unsigned NumElts = VT.getVectorNumElements();
8831   unsigned HalfElts = NumElts/2;
8832   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8833   for (unsigned n = 0; n < NumElts; ++n) {
8834     int MaskElt = SVN->getMaskElt(n);
8835     int NewElt = -1;
8836     if (MaskElt < (int)HalfElts)
8837       NewElt = MaskElt;
8838     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8839       NewElt = HalfElts + MaskElt - NumElts;
8840     NewMask.push_back(NewElt);
8841   }
8842   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
8843                               DAG.getUNDEF(VT), NewMask.data());
8844 }
8845
8846 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
8847 /// NEON load/store intrinsics, and generic vector load/stores, to merge
8848 /// base address updates.
8849 /// For generic load/stores, the memory type is assumed to be a vector.
8850 /// The caller is assumed to have checked legality.
8851 static SDValue CombineBaseUpdate(SDNode *N,
8852                                  TargetLowering::DAGCombinerInfo &DCI) {
8853   SelectionDAG &DAG = DCI.DAG;
8854   const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8855                             N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8856   const bool isStore = N->getOpcode() == ISD::STORE;
8857   const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
8858   SDValue Addr = N->getOperand(AddrOpIdx);
8859   MemSDNode *MemN = cast<MemSDNode>(N);
8860   SDLoc dl(N);
8861
8862   // Search for a use of the address operand that is an increment.
8863   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8864          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8865     SDNode *User = *UI;
8866     if (User->getOpcode() != ISD::ADD ||
8867         UI.getUse().getResNo() != Addr.getResNo())
8868       continue;
8869
8870     // Check that the add is independent of the load/store.  Otherwise, folding
8871     // it would create a cycle.
8872     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8873       continue;
8874
8875     // Find the new opcode for the updating load/store.
8876     bool isLoadOp = true;
8877     bool isLaneOp = false;
8878     unsigned NewOpc = 0;
8879     unsigned NumVecs = 0;
8880     if (isIntrinsic) {
8881       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8882       switch (IntNo) {
8883       default: llvm_unreachable("unexpected intrinsic for Neon base update");
8884       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
8885         NumVecs = 1; break;
8886       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
8887         NumVecs = 2; break;
8888       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
8889         NumVecs = 3; break;
8890       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
8891         NumVecs = 4; break;
8892       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8893         NumVecs = 2; isLaneOp = true; break;
8894       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8895         NumVecs = 3; isLaneOp = true; break;
8896       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8897         NumVecs = 4; isLaneOp = true; break;
8898       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
8899         NumVecs = 1; isLoadOp = false; break;
8900       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
8901         NumVecs = 2; isLoadOp = false; break;
8902       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
8903         NumVecs = 3; isLoadOp = false; break;
8904       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
8905         NumVecs = 4; isLoadOp = false; break;
8906       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8907         NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
8908       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8909         NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
8910       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8911         NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
8912       }
8913     } else {
8914       isLaneOp = true;
8915       switch (N->getOpcode()) {
8916       default: llvm_unreachable("unexpected opcode for Neon base update");
8917       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8918       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8919       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8920       case ISD::LOAD:       NewOpc = ARMISD::VLD1_UPD;
8921         NumVecs = 1; isLaneOp = false; break;
8922       case ISD::STORE:      NewOpc = ARMISD::VST1_UPD;
8923         NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
8924       }
8925     }
8926
8927     // Find the size of memory referenced by the load/store.
8928     EVT VecTy;
8929     if (isLoadOp) {
8930       VecTy = N->getValueType(0);
8931     } else if (isIntrinsic) {
8932       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8933     } else {
8934       assert(isStore && "Node has to be a load, a store, or an intrinsic!");
8935       VecTy = N->getOperand(1).getValueType();
8936     }
8937
8938     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8939     if (isLaneOp)
8940       NumBytes /= VecTy.getVectorNumElements();
8941
8942     // If the increment is a constant, it must match the memory ref size.
8943     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8944     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8945       uint64_t IncVal = CInc->getZExtValue();
8946       if (IncVal != NumBytes)
8947         continue;
8948     } else if (NumBytes >= 3 * 16) {
8949       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8950       // separate instructions that make it harder to use a non-constant update.
8951       continue;
8952     }
8953
8954     // OK, we found an ADD we can fold into the base update.
8955     // Now, create a _UPD node, taking care of not breaking alignment.
8956
8957     EVT AlignedVecTy = VecTy;
8958     unsigned Alignment = MemN->getAlignment();
8959
8960     // If this is a less-than-standard-aligned load/store, change the type to
8961     // match the standard alignment.
8962     // The alignment is overlooked when selecting _UPD variants; and it's
8963     // easier to introduce bitcasts here than fix that.
8964     // There are 3 ways to get to this base-update combine:
8965     // - intrinsics: they are assumed to be properly aligned (to the standard
8966     //   alignment of the memory type), so we don't need to do anything.
8967     // - ARMISD::VLDx nodes: they are only generated from the aforementioned
8968     //   intrinsics, so, likewise, there's nothing to do.
8969     // - generic load/store instructions: the alignment is specified as an
8970     //   explicit operand, rather than implicitly as the standard alignment
8971     //   of the memory type (like the intrisics).  We need to change the
8972     //   memory type to match the explicit alignment.  That way, we don't
8973     //   generate non-standard-aligned ARMISD::VLDx nodes.
8974     if (isa<LSBaseSDNode>(N)) {
8975       if (Alignment == 0)
8976         Alignment = 1;
8977       if (Alignment < VecTy.getScalarSizeInBits() / 8) {
8978         MVT EltTy = MVT::getIntegerVT(Alignment * 8);
8979         assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
8980         assert(!isLaneOp && "Unexpected generic load/store lane.");
8981         unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
8982         AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
8983       }
8984       // Don't set an explicit alignment on regular load/stores that we want
8985       // to transform to VLD/VST 1_UPD nodes.
8986       // This matches the behavior of regular load/stores, which only get an
8987       // explicit alignment if the MMO alignment is larger than the standard
8988       // alignment of the memory type.
8989       // Intrinsics, however, always get an explicit alignment, set to the
8990       // alignment of the MMO.
8991       Alignment = 1;
8992     }
8993
8994     // Create the new updating load/store node.
8995     // First, create an SDVTList for the new updating node's results.
8996     EVT Tys[6];
8997     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
8998     unsigned n;
8999     for (n = 0; n < NumResultVecs; ++n)
9000       Tys[n] = AlignedVecTy;
9001     Tys[n++] = MVT::i32;
9002     Tys[n] = MVT::Other;
9003     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
9004
9005     // Then, gather the new node's operands.
9006     SmallVector<SDValue, 8> Ops;
9007     Ops.push_back(N->getOperand(0)); // incoming chain
9008     Ops.push_back(N->getOperand(AddrOpIdx));
9009     Ops.push_back(Inc);
9010
9011     if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
9012       // Try to match the intrinsic's signature
9013       Ops.push_back(StN->getValue());
9014     } else {
9015       // Loads (and of course intrinsics) match the intrinsics' signature,
9016       // so just add all but the alignment operand.
9017       for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
9018         Ops.push_back(N->getOperand(i));
9019     }
9020
9021     // For all node types, the alignment operand is always the last one.
9022     Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
9023
9024     // If this is a non-standard-aligned STORE, the penultimate operand is the
9025     // stored value.  Bitcast it to the aligned type.
9026     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
9027       SDValue &StVal = Ops[Ops.size()-2];
9028       StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
9029     }
9030
9031     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys,
9032                                            Ops, AlignedVecTy,
9033                                            MemN->getMemOperand());
9034
9035     // Update the uses.
9036     SmallVector<SDValue, 5> NewResults;
9037     for (unsigned i = 0; i < NumResultVecs; ++i)
9038       NewResults.push_back(SDValue(UpdN.getNode(), i));
9039
9040     // If this is an non-standard-aligned LOAD, the first result is the loaded
9041     // value.  Bitcast it to the expected result type.
9042     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
9043       SDValue &LdVal = NewResults[0];
9044       LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
9045     }
9046
9047     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9048     DCI.CombineTo(N, NewResults);
9049     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9050
9051     break;
9052   }
9053   return SDValue();
9054 }
9055
9056 static SDValue PerformVLDCombine(SDNode *N,
9057                                  TargetLowering::DAGCombinerInfo &DCI) {
9058   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9059     return SDValue();
9060
9061   return CombineBaseUpdate(N, DCI);
9062 }
9063
9064 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9065 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9066 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
9067 /// return true.
9068 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9069   SelectionDAG &DAG = DCI.DAG;
9070   EVT VT = N->getValueType(0);
9071   // vldN-dup instructions only support 64-bit vectors for N > 1.
9072   if (!VT.is64BitVector())
9073     return false;
9074
9075   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9076   SDNode *VLD = N->getOperand(0).getNode();
9077   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9078     return false;
9079   unsigned NumVecs = 0;
9080   unsigned NewOpc = 0;
9081   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9082   if (IntNo == Intrinsic::arm_neon_vld2lane) {
9083     NumVecs = 2;
9084     NewOpc = ARMISD::VLD2DUP;
9085   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9086     NumVecs = 3;
9087     NewOpc = ARMISD::VLD3DUP;
9088   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9089     NumVecs = 4;
9090     NewOpc = ARMISD::VLD4DUP;
9091   } else {
9092     return false;
9093   }
9094
9095   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9096   // numbers match the load.
9097   unsigned VLDLaneNo =
9098     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9099   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9100        UI != UE; ++UI) {
9101     // Ignore uses of the chain result.
9102     if (UI.getUse().getResNo() == NumVecs)
9103       continue;
9104     SDNode *User = *UI;
9105     if (User->getOpcode() != ARMISD::VDUPLANE ||
9106         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9107       return false;
9108   }
9109
9110   // Create the vldN-dup node.
9111   EVT Tys[5];
9112   unsigned n;
9113   for (n = 0; n < NumVecs; ++n)
9114     Tys[n] = VT;
9115   Tys[n] = MVT::Other;
9116   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9117   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9118   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9119   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9120                                            Ops, VLDMemInt->getMemoryVT(),
9121                                            VLDMemInt->getMemOperand());
9122
9123   // Update the uses.
9124   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9125        UI != UE; ++UI) {
9126     unsigned ResNo = UI.getUse().getResNo();
9127     // Ignore uses of the chain result.
9128     if (ResNo == NumVecs)
9129       continue;
9130     SDNode *User = *UI;
9131     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9132   }
9133
9134   // Now the vldN-lane intrinsic is dead except for its chain result.
9135   // Update uses of the chain.
9136   std::vector<SDValue> VLDDupResults;
9137   for (unsigned n = 0; n < NumVecs; ++n)
9138     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9139   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9140   DCI.CombineTo(VLD, VLDDupResults);
9141
9142   return true;
9143 }
9144
9145 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9146 /// ARMISD::VDUPLANE.
9147 static SDValue PerformVDUPLANECombine(SDNode *N,
9148                                       TargetLowering::DAGCombinerInfo &DCI) {
9149   SDValue Op = N->getOperand(0);
9150
9151   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9152   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9153   if (CombineVLDDUP(N, DCI))
9154     return SDValue(N, 0);
9155
9156   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9157   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9158   while (Op.getOpcode() == ISD::BITCAST)
9159     Op = Op.getOperand(0);
9160   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9161     return SDValue();
9162
9163   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9164   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9165   // The canonical VMOV for a zero vector uses a 32-bit element size.
9166   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9167   unsigned EltBits;
9168   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9169     EltSize = 8;
9170   EVT VT = N->getValueType(0);
9171   if (EltSize > VT.getVectorElementType().getSizeInBits())
9172     return SDValue();
9173
9174   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9175 }
9176
9177 static SDValue PerformLOADCombine(SDNode *N,
9178                                   TargetLowering::DAGCombinerInfo &DCI) {
9179   EVT VT = N->getValueType(0);
9180
9181   // If this is a legal vector load, try to combine it into a VLD1_UPD.
9182   if (ISD::isNormalLoad(N) && VT.isVector() &&
9183       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9184     return CombineBaseUpdate(N, DCI);
9185
9186   return SDValue();
9187 }
9188
9189 /// PerformSTORECombine - Target-specific dag combine xforms for
9190 /// ISD::STORE.
9191 static SDValue PerformSTORECombine(SDNode *N,
9192                                    TargetLowering::DAGCombinerInfo &DCI) {
9193   StoreSDNode *St = cast<StoreSDNode>(N);
9194   if (St->isVolatile())
9195     return SDValue();
9196
9197   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
9198   // pack all of the elements in one place.  Next, store to memory in fewer
9199   // chunks.
9200   SDValue StVal = St->getValue();
9201   EVT VT = StVal.getValueType();
9202   if (St->isTruncatingStore() && VT.isVector()) {
9203     SelectionDAG &DAG = DCI.DAG;
9204     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9205     EVT StVT = St->getMemoryVT();
9206     unsigned NumElems = VT.getVectorNumElements();
9207     assert(StVT != VT && "Cannot truncate to the same type");
9208     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
9209     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
9210
9211     // From, To sizes and ElemCount must be pow of two
9212     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
9213
9214     // We are going to use the original vector elt for storing.
9215     // Accumulated smaller vector elements must be a multiple of the store size.
9216     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
9217
9218     unsigned SizeRatio  = FromEltSz / ToEltSz;
9219     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
9220
9221     // Create a type on which we perform the shuffle.
9222     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9223                                      NumElems*SizeRatio);
9224     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9225
9226     SDLoc DL(St);
9227     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9228     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9229     for (unsigned i = 0; i < NumElems; ++i)
9230       ShuffleVec[i] = TLI.isBigEndian() ? (i+1) * SizeRatio - 1 : i * SizeRatio;
9231
9232     // Can't shuffle using an illegal type.
9233     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9234
9235     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9236                                 DAG.getUNDEF(WideVec.getValueType()),
9237                                 ShuffleVec.data());
9238     // At this point all of the data is stored at the bottom of the
9239     // register. We now need to save it to mem.
9240
9241     // Find the largest store unit
9242     MVT StoreType = MVT::i8;
9243     for (MVT Tp : MVT::integer_valuetypes()) {
9244       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9245         StoreType = Tp;
9246     }
9247     // Didn't find a legal store type.
9248     if (!TLI.isTypeLegal(StoreType))
9249       return SDValue();
9250
9251     // Bitcast the original vector into a vector of store-size units
9252     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9253             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9254     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9255     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9256     SmallVector<SDValue, 8> Chains;
9257     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8, DL,
9258                                         TLI.getPointerTy());
9259     SDValue BasePtr = St->getBasePtr();
9260
9261     // Perform one or more big stores into memory.
9262     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9263     for (unsigned I = 0; I < E; I++) {
9264       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9265                                    StoreType, ShuffWide,
9266                                    DAG.getIntPtrConstant(I, DL));
9267       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9268                                 St->getPointerInfo(), St->isVolatile(),
9269                                 St->isNonTemporal(), St->getAlignment());
9270       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9271                             Increment);
9272       Chains.push_back(Ch);
9273     }
9274     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
9275   }
9276
9277   if (!ISD::isNormalStore(St))
9278     return SDValue();
9279
9280   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9281   // ARM stores of arguments in the same cache line.
9282   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9283       StVal.getNode()->hasOneUse()) {
9284     SelectionDAG  &DAG = DCI.DAG;
9285     bool isBigEndian = DAG.getTargetLoweringInfo().isBigEndian();
9286     SDLoc DL(St);
9287     SDValue BasePtr = St->getBasePtr();
9288     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9289                                   StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
9290                                   BasePtr, St->getPointerInfo(), St->isVolatile(),
9291                                   St->isNonTemporal(), St->getAlignment());
9292
9293     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9294                                     DAG.getConstant(4, DL, MVT::i32));
9295     return DAG.getStore(NewST1.getValue(0), DL,
9296                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
9297                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9298                         St->isNonTemporal(),
9299                         std::min(4U, St->getAlignment() / 2));
9300   }
9301
9302   if (StVal.getValueType() == MVT::i64 &&
9303       StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9304
9305     // Bitcast an i64 store extracted from a vector to f64.
9306     // Otherwise, the i64 value will be legalized to a pair of i32 values.
9307     SelectionDAG &DAG = DCI.DAG;
9308     SDLoc dl(StVal);
9309     SDValue IntVec = StVal.getOperand(0);
9310     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9311                                    IntVec.getValueType().getVectorNumElements());
9312     SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9313     SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9314                                  Vec, StVal.getOperand(1));
9315     dl = SDLoc(N);
9316     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9317     // Make the DAGCombiner fold the bitcasts.
9318     DCI.AddToWorklist(Vec.getNode());
9319     DCI.AddToWorklist(ExtElt.getNode());
9320     DCI.AddToWorklist(V.getNode());
9321     return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9322                         St->getPointerInfo(), St->isVolatile(),
9323                         St->isNonTemporal(), St->getAlignment(),
9324                         St->getAAInfo());
9325   }
9326
9327   // If this is a legal vector store, try to combine it into a VST1_UPD.
9328   if (ISD::isNormalStore(N) && VT.isVector() &&
9329       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9330     return CombineBaseUpdate(N, DCI);
9331
9332   return SDValue();
9333 }
9334
9335 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9336 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9337 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9338 {
9339   integerPart cN;
9340   integerPart c0 = 0;
9341   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9342        I != E; I++) {
9343     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9344     if (!C)
9345       return false;
9346
9347     bool isExact;
9348     APFloat APF = C->getValueAPF();
9349     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9350         != APFloat::opOK || !isExact)
9351       return false;
9352
9353     c0 = (I == 0) ? cN : c0;
9354     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9355       return false;
9356   }
9357   C = c0;
9358   return true;
9359 }
9360
9361 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9362 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9363 /// when the VMUL has a constant operand that is a power of 2.
9364 ///
9365 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9366 ///  vmul.f32        d16, d17, d16
9367 ///  vcvt.s32.f32    d16, d16
9368 /// becomes:
9369 ///  vcvt.s32.f32    d16, d16, #3
9370 static SDValue PerformVCVTCombine(SDNode *N,
9371                                   TargetLowering::DAGCombinerInfo &DCI,
9372                                   const ARMSubtarget *Subtarget) {
9373   SelectionDAG &DAG = DCI.DAG;
9374   SDValue Op = N->getOperand(0);
9375
9376   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9377       Op.getOpcode() != ISD::FMUL)
9378     return SDValue();
9379
9380   uint64_t C;
9381   SDValue N0 = Op->getOperand(0);
9382   SDValue ConstVec = Op->getOperand(1);
9383   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9384
9385   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9386       !isConstVecPow2(ConstVec, isSigned, C))
9387     return SDValue();
9388
9389   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9390   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9391   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9392   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32 ||
9393       NumLanes > 4) {
9394     // These instructions only exist converting from f32 to i32. We can handle
9395     // smaller integers by generating an extra truncate, but larger ones would
9396     // be lossy. We also can't handle more then 4 lanes, since these intructions
9397     // only support v2i32/v4i32 types.
9398     return SDValue();
9399   }
9400
9401   SDLoc dl(N);
9402   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9403     Intrinsic::arm_neon_vcvtfp2fxu;
9404   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9405                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9406                                  DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9407                                  N0,
9408                                  DAG.getConstant(Log2_64(C), dl, MVT::i32));
9409
9410   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9411     FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
9412
9413   return FixConv;
9414 }
9415
9416 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9417 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9418 /// when the VDIV has a constant operand that is a power of 2.
9419 ///
9420 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9421 ///  vcvt.f32.s32    d16, d16
9422 ///  vdiv.f32        d16, d17, d16
9423 /// becomes:
9424 ///  vcvt.f32.s32    d16, d16, #3
9425 static SDValue PerformVDIVCombine(SDNode *N,
9426                                   TargetLowering::DAGCombinerInfo &DCI,
9427                                   const ARMSubtarget *Subtarget) {
9428   SelectionDAG &DAG = DCI.DAG;
9429   SDValue Op = N->getOperand(0);
9430   unsigned OpOpcode = Op.getNode()->getOpcode();
9431
9432   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9433       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9434     return SDValue();
9435
9436   uint64_t C;
9437   SDValue ConstVec = N->getOperand(1);
9438   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9439
9440   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9441       !isConstVecPow2(ConstVec, isSigned, C))
9442     return SDValue();
9443
9444   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9445   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9446   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9447     // These instructions only exist converting from i32 to f32. We can handle
9448     // smaller integers by generating an extra extend, but larger ones would
9449     // be lossy.
9450     return SDValue();
9451   }
9452
9453   SDLoc dl(N);
9454   SDValue ConvInput = Op.getOperand(0);
9455   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9456   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9457     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9458                             dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9459                             ConvInput);
9460
9461   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9462     Intrinsic::arm_neon_vcvtfxu2fp;
9463   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9464                      Op.getValueType(),
9465                      DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9466                      ConvInput, DAG.getConstant(Log2_64(C), dl, MVT::i32));
9467 }
9468
9469 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9470 /// operand of a vector shift operation, where all the elements of the
9471 /// build_vector must have the same constant integer value.
9472 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9473   // Ignore bit_converts.
9474   while (Op.getOpcode() == ISD::BITCAST)
9475     Op = Op.getOperand(0);
9476   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9477   APInt SplatBits, SplatUndef;
9478   unsigned SplatBitSize;
9479   bool HasAnyUndefs;
9480   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9481                                       HasAnyUndefs, ElementBits) ||
9482       SplatBitSize > ElementBits)
9483     return false;
9484   Cnt = SplatBits.getSExtValue();
9485   return true;
9486 }
9487
9488 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9489 /// operand of a vector shift left operation.  That value must be in the range:
9490 ///   0 <= Value < ElementBits for a left shift; or
9491 ///   0 <= Value <= ElementBits for a long left shift.
9492 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9493   assert(VT.isVector() && "vector shift count is not a vector type");
9494   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9495   if (! getVShiftImm(Op, ElementBits, Cnt))
9496     return false;
9497   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9498 }
9499
9500 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9501 /// operand of a vector shift right operation.  For a shift opcode, the value
9502 /// is positive, but for an intrinsic the value count must be negative. The
9503 /// absolute value must be in the range:
9504 ///   1 <= |Value| <= ElementBits for a right shift; or
9505 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9506 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9507                          int64_t &Cnt) {
9508   assert(VT.isVector() && "vector shift count is not a vector type");
9509   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9510   if (! getVShiftImm(Op, ElementBits, Cnt))
9511     return false;
9512   if (isIntrinsic)
9513     Cnt = -Cnt;
9514   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9515 }
9516
9517 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9518 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9519   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9520   switch (IntNo) {
9521   default:
9522     // Don't do anything for most intrinsics.
9523     break;
9524
9525   // Vector shifts: check for immediate versions and lower them.
9526   // Note: This is done during DAG combining instead of DAG legalizing because
9527   // the build_vectors for 64-bit vector element shift counts are generally
9528   // not legal, and it is hard to see their values after they get legalized to
9529   // loads from a constant pool.
9530   case Intrinsic::arm_neon_vshifts:
9531   case Intrinsic::arm_neon_vshiftu:
9532   case Intrinsic::arm_neon_vrshifts:
9533   case Intrinsic::arm_neon_vrshiftu:
9534   case Intrinsic::arm_neon_vrshiftn:
9535   case Intrinsic::arm_neon_vqshifts:
9536   case Intrinsic::arm_neon_vqshiftu:
9537   case Intrinsic::arm_neon_vqshiftsu:
9538   case Intrinsic::arm_neon_vqshiftns:
9539   case Intrinsic::arm_neon_vqshiftnu:
9540   case Intrinsic::arm_neon_vqshiftnsu:
9541   case Intrinsic::arm_neon_vqrshiftns:
9542   case Intrinsic::arm_neon_vqrshiftnu:
9543   case Intrinsic::arm_neon_vqrshiftnsu: {
9544     EVT VT = N->getOperand(1).getValueType();
9545     int64_t Cnt;
9546     unsigned VShiftOpc = 0;
9547
9548     switch (IntNo) {
9549     case Intrinsic::arm_neon_vshifts:
9550     case Intrinsic::arm_neon_vshiftu:
9551       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9552         VShiftOpc = ARMISD::VSHL;
9553         break;
9554       }
9555       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9556         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9557                      ARMISD::VSHRs : ARMISD::VSHRu);
9558         break;
9559       }
9560       return SDValue();
9561
9562     case Intrinsic::arm_neon_vrshifts:
9563     case Intrinsic::arm_neon_vrshiftu:
9564       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9565         break;
9566       return SDValue();
9567
9568     case Intrinsic::arm_neon_vqshifts:
9569     case Intrinsic::arm_neon_vqshiftu:
9570       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9571         break;
9572       return SDValue();
9573
9574     case Intrinsic::arm_neon_vqshiftsu:
9575       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9576         break;
9577       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9578
9579     case Intrinsic::arm_neon_vrshiftn:
9580     case Intrinsic::arm_neon_vqshiftns:
9581     case Intrinsic::arm_neon_vqshiftnu:
9582     case Intrinsic::arm_neon_vqshiftnsu:
9583     case Intrinsic::arm_neon_vqrshiftns:
9584     case Intrinsic::arm_neon_vqrshiftnu:
9585     case Intrinsic::arm_neon_vqrshiftnsu:
9586       // Narrowing shifts require an immediate right shift.
9587       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9588         break;
9589       llvm_unreachable("invalid shift count for narrowing vector shift "
9590                        "intrinsic");
9591
9592     default:
9593       llvm_unreachable("unhandled vector shift");
9594     }
9595
9596     switch (IntNo) {
9597     case Intrinsic::arm_neon_vshifts:
9598     case Intrinsic::arm_neon_vshiftu:
9599       // Opcode already set above.
9600       break;
9601     case Intrinsic::arm_neon_vrshifts:
9602       VShiftOpc = ARMISD::VRSHRs; break;
9603     case Intrinsic::arm_neon_vrshiftu:
9604       VShiftOpc = ARMISD::VRSHRu; break;
9605     case Intrinsic::arm_neon_vrshiftn:
9606       VShiftOpc = ARMISD::VRSHRN; break;
9607     case Intrinsic::arm_neon_vqshifts:
9608       VShiftOpc = ARMISD::VQSHLs; break;
9609     case Intrinsic::arm_neon_vqshiftu:
9610       VShiftOpc = ARMISD::VQSHLu; break;
9611     case Intrinsic::arm_neon_vqshiftsu:
9612       VShiftOpc = ARMISD::VQSHLsu; break;
9613     case Intrinsic::arm_neon_vqshiftns:
9614       VShiftOpc = ARMISD::VQSHRNs; break;
9615     case Intrinsic::arm_neon_vqshiftnu:
9616       VShiftOpc = ARMISD::VQSHRNu; break;
9617     case Intrinsic::arm_neon_vqshiftnsu:
9618       VShiftOpc = ARMISD::VQSHRNsu; break;
9619     case Intrinsic::arm_neon_vqrshiftns:
9620       VShiftOpc = ARMISD::VQRSHRNs; break;
9621     case Intrinsic::arm_neon_vqrshiftnu:
9622       VShiftOpc = ARMISD::VQRSHRNu; break;
9623     case Intrinsic::arm_neon_vqrshiftnsu:
9624       VShiftOpc = ARMISD::VQRSHRNsu; break;
9625     }
9626
9627     SDLoc dl(N);
9628     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
9629                        N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
9630   }
9631
9632   case Intrinsic::arm_neon_vshiftins: {
9633     EVT VT = N->getOperand(1).getValueType();
9634     int64_t Cnt;
9635     unsigned VShiftOpc = 0;
9636
9637     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9638       VShiftOpc = ARMISD::VSLI;
9639     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9640       VShiftOpc = ARMISD::VSRI;
9641     else {
9642       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9643     }
9644
9645     SDLoc dl(N);
9646     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
9647                        N->getOperand(1), N->getOperand(2),
9648                        DAG.getConstant(Cnt, dl, MVT::i32));
9649   }
9650
9651   case Intrinsic::arm_neon_vqrshifts:
9652   case Intrinsic::arm_neon_vqrshiftu:
9653     // No immediate versions of these to check for.
9654     break;
9655   }
9656
9657   return SDValue();
9658 }
9659
9660 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9661 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9662 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9663 /// vector element shift counts are generally not legal, and it is hard to see
9664 /// their values after they get legalized to loads from a constant pool.
9665 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9666                                    const ARMSubtarget *ST) {
9667   EVT VT = N->getValueType(0);
9668   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9669     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9670     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9671     SDValue N1 = N->getOperand(1);
9672     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9673       SDValue N0 = N->getOperand(0);
9674       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9675           DAG.MaskedValueIsZero(N0.getOperand(0),
9676                                 APInt::getHighBitsSet(32, 16)))
9677         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9678     }
9679   }
9680
9681   // Nothing to be done for scalar shifts.
9682   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9683   if (!VT.isVector() || !TLI.isTypeLegal(VT))
9684     return SDValue();
9685
9686   assert(ST->hasNEON() && "unexpected vector shift");
9687   int64_t Cnt;
9688
9689   switch (N->getOpcode()) {
9690   default: llvm_unreachable("unexpected shift opcode");
9691
9692   case ISD::SHL:
9693     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
9694       SDLoc dl(N);
9695       return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
9696                          DAG.getConstant(Cnt, dl, MVT::i32));
9697     }
9698     break;
9699
9700   case ISD::SRA:
9701   case ISD::SRL:
9702     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9703       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9704                             ARMISD::VSHRs : ARMISD::VSHRu);
9705       SDLoc dl(N);
9706       return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
9707                          DAG.getConstant(Cnt, dl, MVT::i32));
9708     }
9709   }
9710   return SDValue();
9711 }
9712
9713 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9714 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9715 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9716                                     const ARMSubtarget *ST) {
9717   SDValue N0 = N->getOperand(0);
9718
9719   // Check for sign- and zero-extensions of vector extract operations of 8-
9720   // and 16-bit vector elements.  NEON supports these directly.  They are
9721   // handled during DAG combining because type legalization will promote them
9722   // to 32-bit types and it is messy to recognize the operations after that.
9723   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9724     SDValue Vec = N0.getOperand(0);
9725     SDValue Lane = N0.getOperand(1);
9726     EVT VT = N->getValueType(0);
9727     EVT EltVT = N0.getValueType();
9728     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9729
9730     if (VT == MVT::i32 &&
9731         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9732         TLI.isTypeLegal(Vec.getValueType()) &&
9733         isa<ConstantSDNode>(Lane)) {
9734
9735       unsigned Opc = 0;
9736       switch (N->getOpcode()) {
9737       default: llvm_unreachable("unexpected opcode");
9738       case ISD::SIGN_EXTEND:
9739         Opc = ARMISD::VGETLANEs;
9740         break;
9741       case ISD::ZERO_EXTEND:
9742       case ISD::ANY_EXTEND:
9743         Opc = ARMISD::VGETLANEu;
9744         break;
9745       }
9746       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9747     }
9748   }
9749
9750   return SDValue();
9751 }
9752
9753 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9754 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9755 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9756                                        const ARMSubtarget *ST) {
9757   // If the target supports NEON, try to use vmax/vmin instructions for f32
9758   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
9759   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
9760   // a NaN; only do the transformation when it matches that behavior.
9761
9762   // For now only do this when using NEON for FP operations; if using VFP, it
9763   // is not obvious that the benefit outweighs the cost of switching to the
9764   // NEON pipeline.
9765   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9766       N->getValueType(0) != MVT::f32)
9767     return SDValue();
9768
9769   SDValue CondLHS = N->getOperand(0);
9770   SDValue CondRHS = N->getOperand(1);
9771   SDValue LHS = N->getOperand(2);
9772   SDValue RHS = N->getOperand(3);
9773   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9774
9775   unsigned Opcode = 0;
9776   bool IsReversed;
9777   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9778     IsReversed = false; // x CC y ? x : y
9779   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9780     IsReversed = true ; // x CC y ? y : x
9781   } else {
9782     return SDValue();
9783   }
9784
9785   bool IsUnordered;
9786   switch (CC) {
9787   default: break;
9788   case ISD::SETOLT:
9789   case ISD::SETOLE:
9790   case ISD::SETLT:
9791   case ISD::SETLE:
9792   case ISD::SETULT:
9793   case ISD::SETULE:
9794     // If LHS is NaN, an ordered comparison will be false and the result will
9795     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
9796     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9797     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9798     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9799       break;
9800     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9801     // will return -0, so vmin can only be used for unsafe math or if one of
9802     // the operands is known to be nonzero.
9803     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9804         !DAG.getTarget().Options.UnsafeFPMath &&
9805         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9806       break;
9807     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9808     break;
9809
9810   case ISD::SETOGT:
9811   case ISD::SETOGE:
9812   case ISD::SETGT:
9813   case ISD::SETGE:
9814   case ISD::SETUGT:
9815   case ISD::SETUGE:
9816     // If LHS is NaN, an ordered comparison will be false and the result will
9817     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
9818     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9819     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9820     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9821       break;
9822     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9823     // will return +0, so vmax can only be used for unsafe math or if one of
9824     // the operands is known to be nonzero.
9825     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9826         !DAG.getTarget().Options.UnsafeFPMath &&
9827         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9828       break;
9829     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9830     break;
9831   }
9832
9833   if (!Opcode)
9834     return SDValue();
9835   return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9836 }
9837
9838 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9839 SDValue
9840 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9841   SDValue Cmp = N->getOperand(4);
9842   if (Cmp.getOpcode() != ARMISD::CMPZ)
9843     // Only looking at EQ and NE cases.
9844     return SDValue();
9845
9846   EVT VT = N->getValueType(0);
9847   SDLoc dl(N);
9848   SDValue LHS = Cmp.getOperand(0);
9849   SDValue RHS = Cmp.getOperand(1);
9850   SDValue FalseVal = N->getOperand(0);
9851   SDValue TrueVal = N->getOperand(1);
9852   SDValue ARMcc = N->getOperand(2);
9853   ARMCC::CondCodes CC =
9854     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9855
9856   // Simplify
9857   //   mov     r1, r0
9858   //   cmp     r1, x
9859   //   mov     r0, y
9860   //   moveq   r0, x
9861   // to
9862   //   cmp     r0, x
9863   //   movne   r0, y
9864   //
9865   //   mov     r1, r0
9866   //   cmp     r1, x
9867   //   mov     r0, x
9868   //   movne   r0, y
9869   // to
9870   //   cmp     r0, x
9871   //   movne   r0, y
9872   /// FIXME: Turn this into a target neutral optimization?
9873   SDValue Res;
9874   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9875     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9876                       N->getOperand(3), Cmp);
9877   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9878     SDValue ARMcc;
9879     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9880     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9881                       N->getOperand(3), NewCmp);
9882   }
9883
9884   if (Res.getNode()) {
9885     APInt KnownZero, KnownOne;
9886     DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
9887     // Capture demanded bits information that would be otherwise lost.
9888     if (KnownZero == 0xfffffffe)
9889       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9890                         DAG.getValueType(MVT::i1));
9891     else if (KnownZero == 0xffffff00)
9892       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9893                         DAG.getValueType(MVT::i8));
9894     else if (KnownZero == 0xffff0000)
9895       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9896                         DAG.getValueType(MVT::i16));
9897   }
9898
9899   return Res;
9900 }
9901
9902 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9903                                              DAGCombinerInfo &DCI) const {
9904   switch (N->getOpcode()) {
9905   default: break;
9906   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
9907   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
9908   case ISD::SUB:        return PerformSUBCombine(N, DCI);
9909   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
9910   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
9911   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
9912   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
9913   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
9914   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
9915   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9916   case ISD::STORE:      return PerformSTORECombine(N, DCI);
9917   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
9918   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9919   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9920   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9921   case ISD::FP_TO_SINT:
9922   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9923   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
9924   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9925   case ISD::SHL:
9926   case ISD::SRA:
9927   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
9928   case ISD::SIGN_EXTEND:
9929   case ISD::ZERO_EXTEND:
9930   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9931   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9932   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9933   case ISD::LOAD:       return PerformLOADCombine(N, DCI);
9934   case ARMISD::VLD2DUP:
9935   case ARMISD::VLD3DUP:
9936   case ARMISD::VLD4DUP:
9937     return PerformVLDCombine(N, DCI);
9938   case ARMISD::BUILD_VECTOR:
9939     return PerformARMBUILD_VECTORCombine(N, DCI);
9940   case ISD::INTRINSIC_VOID:
9941   case ISD::INTRINSIC_W_CHAIN:
9942     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9943     case Intrinsic::arm_neon_vld1:
9944     case Intrinsic::arm_neon_vld2:
9945     case Intrinsic::arm_neon_vld3:
9946     case Intrinsic::arm_neon_vld4:
9947     case Intrinsic::arm_neon_vld2lane:
9948     case Intrinsic::arm_neon_vld3lane:
9949     case Intrinsic::arm_neon_vld4lane:
9950     case Intrinsic::arm_neon_vst1:
9951     case Intrinsic::arm_neon_vst2:
9952     case Intrinsic::arm_neon_vst3:
9953     case Intrinsic::arm_neon_vst4:
9954     case Intrinsic::arm_neon_vst2lane:
9955     case Intrinsic::arm_neon_vst3lane:
9956     case Intrinsic::arm_neon_vst4lane:
9957       return PerformVLDCombine(N, DCI);
9958     default: break;
9959     }
9960     break;
9961   }
9962   return SDValue();
9963 }
9964
9965 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9966                                                           EVT VT) const {
9967   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9968 }
9969
9970 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
9971                                                        unsigned,
9972                                                        unsigned,
9973                                                        bool *Fast) const {
9974   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9975   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9976
9977   switch (VT.getSimpleVT().SimpleTy) {
9978   default:
9979     return false;
9980   case MVT::i8:
9981   case MVT::i16:
9982   case MVT::i32: {
9983     // Unaligned access can use (for example) LRDB, LRDH, LDR
9984     if (AllowsUnaligned) {
9985       if (Fast)
9986         *Fast = Subtarget->hasV7Ops();
9987       return true;
9988     }
9989     return false;
9990   }
9991   case MVT::f64:
9992   case MVT::v2f64: {
9993     // For any little-endian targets with neon, we can support unaligned ld/st
9994     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9995     // A big-endian target may also explicitly support unaligned accesses
9996     if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9997       if (Fast)
9998         *Fast = true;
9999       return true;
10000     }
10001     return false;
10002   }
10003   }
10004 }
10005
10006 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10007                        unsigned AlignCheck) {
10008   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10009           (DstAlign == 0 || DstAlign % AlignCheck == 0));
10010 }
10011
10012 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10013                                            unsigned DstAlign, unsigned SrcAlign,
10014                                            bool IsMemset, bool ZeroMemset,
10015                                            bool MemcpyStrSrc,
10016                                            MachineFunction &MF) const {
10017   const Function *F = MF.getFunction();
10018
10019   // See if we can use NEON instructions for this...
10020   if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
10021       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10022     bool Fast;
10023     if (Size >= 16 &&
10024         (memOpAlign(SrcAlign, DstAlign, 16) ||
10025          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
10026       return MVT::v2f64;
10027     } else if (Size >= 8 &&
10028                (memOpAlign(SrcAlign, DstAlign, 8) ||
10029                 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
10030                  Fast))) {
10031       return MVT::f64;
10032     }
10033   }
10034
10035   // Lowering to i32/i16 if the size permits.
10036   if (Size >= 4)
10037     return MVT::i32;
10038   else if (Size >= 2)
10039     return MVT::i16;
10040
10041   // Let the target-independent logic figure it out.
10042   return MVT::Other;
10043 }
10044
10045 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10046   if (Val.getOpcode() != ISD::LOAD)
10047     return false;
10048
10049   EVT VT1 = Val.getValueType();
10050   if (!VT1.isSimple() || !VT1.isInteger() ||
10051       !VT2.isSimple() || !VT2.isInteger())
10052     return false;
10053
10054   switch (VT1.getSimpleVT().SimpleTy) {
10055   default: break;
10056   case MVT::i1:
10057   case MVT::i8:
10058   case MVT::i16:
10059     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10060     return true;
10061   }
10062
10063   return false;
10064 }
10065
10066 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
10067   EVT VT = ExtVal.getValueType();
10068
10069   if (!isTypeLegal(VT))
10070     return false;
10071
10072   // Don't create a loadext if we can fold the extension into a wide/long
10073   // instruction.
10074   // If there's more than one user instruction, the loadext is desirable no
10075   // matter what.  There can be two uses by the same instruction.
10076   if (ExtVal->use_empty() ||
10077       !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
10078     return true;
10079
10080   SDNode *U = *ExtVal->use_begin();
10081   if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
10082        U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
10083     return false;
10084
10085   return true;
10086 }
10087
10088 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10089   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10090     return false;
10091
10092   if (!isTypeLegal(EVT::getEVT(Ty1)))
10093     return false;
10094
10095   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10096
10097   // Assuming the caller doesn't have a zeroext or signext return parameter,
10098   // truncation all the way down to i1 is valid.
10099   return true;
10100 }
10101
10102
10103 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10104   if (V < 0)
10105     return false;
10106
10107   unsigned Scale = 1;
10108   switch (VT.getSimpleVT().SimpleTy) {
10109   default: return false;
10110   case MVT::i1:
10111   case MVT::i8:
10112     // Scale == 1;
10113     break;
10114   case MVT::i16:
10115     // Scale == 2;
10116     Scale = 2;
10117     break;
10118   case MVT::i32:
10119     // Scale == 4;
10120     Scale = 4;
10121     break;
10122   }
10123
10124   if ((V & (Scale - 1)) != 0)
10125     return false;
10126   V /= Scale;
10127   return V == (V & ((1LL << 5) - 1));
10128 }
10129
10130 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10131                                       const ARMSubtarget *Subtarget) {
10132   bool isNeg = false;
10133   if (V < 0) {
10134     isNeg = true;
10135     V = - V;
10136   }
10137
10138   switch (VT.getSimpleVT().SimpleTy) {
10139   default: return false;
10140   case MVT::i1:
10141   case MVT::i8:
10142   case MVT::i16:
10143   case MVT::i32:
10144     // + imm12 or - imm8
10145     if (isNeg)
10146       return V == (V & ((1LL << 8) - 1));
10147     return V == (V & ((1LL << 12) - 1));
10148   case MVT::f32:
10149   case MVT::f64:
10150     // Same as ARM mode. FIXME: NEON?
10151     if (!Subtarget->hasVFP2())
10152       return false;
10153     if ((V & 3) != 0)
10154       return false;
10155     V >>= 2;
10156     return V == (V & ((1LL << 8) - 1));
10157   }
10158 }
10159
10160 /// isLegalAddressImmediate - Return true if the integer value can be used
10161 /// as the offset of the target addressing mode for load / store of the
10162 /// given type.
10163 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10164                                     const ARMSubtarget *Subtarget) {
10165   if (V == 0)
10166     return true;
10167
10168   if (!VT.isSimple())
10169     return false;
10170
10171   if (Subtarget->isThumb1Only())
10172     return isLegalT1AddressImmediate(V, VT);
10173   else if (Subtarget->isThumb2())
10174     return isLegalT2AddressImmediate(V, VT, Subtarget);
10175
10176   // ARM mode.
10177   if (V < 0)
10178     V = - V;
10179   switch (VT.getSimpleVT().SimpleTy) {
10180   default: return false;
10181   case MVT::i1:
10182   case MVT::i8:
10183   case MVT::i32:
10184     // +- imm12
10185     return V == (V & ((1LL << 12) - 1));
10186   case MVT::i16:
10187     // +- imm8
10188     return V == (V & ((1LL << 8) - 1));
10189   case MVT::f32:
10190   case MVT::f64:
10191     if (!Subtarget->hasVFP2()) // FIXME: NEON?
10192       return false;
10193     if ((V & 3) != 0)
10194       return false;
10195     V >>= 2;
10196     return V == (V & ((1LL << 8) - 1));
10197   }
10198 }
10199
10200 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10201                                                       EVT VT) const {
10202   int Scale = AM.Scale;
10203   if (Scale < 0)
10204     return false;
10205
10206   switch (VT.getSimpleVT().SimpleTy) {
10207   default: return false;
10208   case MVT::i1:
10209   case MVT::i8:
10210   case MVT::i16:
10211   case MVT::i32:
10212     if (Scale == 1)
10213       return true;
10214     // r + r << imm
10215     Scale = Scale & ~1;
10216     return Scale == 2 || Scale == 4 || Scale == 8;
10217   case MVT::i64:
10218     // r + r
10219     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10220       return true;
10221     return false;
10222   case MVT::isVoid:
10223     // Note, we allow "void" uses (basically, uses that aren't loads or
10224     // stores), because arm allows folding a scale into many arithmetic
10225     // operations.  This should be made more precise and revisited later.
10226
10227     // Allow r << imm, but the imm has to be a multiple of two.
10228     if (Scale & 1) return false;
10229     return isPowerOf2_32(Scale);
10230   }
10231 }
10232
10233 /// isLegalAddressingMode - Return true if the addressing mode represented
10234 /// by AM is legal for this target, for a load/store of the specified type.
10235 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10236                                               Type *Ty) const {
10237   EVT VT = getValueType(Ty, true);
10238   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10239     return false;
10240
10241   // Can never fold addr of global into load/store.
10242   if (AM.BaseGV)
10243     return false;
10244
10245   switch (AM.Scale) {
10246   case 0:  // no scale reg, must be "r+i" or "r", or "i".
10247     break;
10248   case 1:
10249     if (Subtarget->isThumb1Only())
10250       return false;
10251     // FALL THROUGH.
10252   default:
10253     // ARM doesn't support any R+R*scale+imm addr modes.
10254     if (AM.BaseOffs)
10255       return false;
10256
10257     if (!VT.isSimple())
10258       return false;
10259
10260     if (Subtarget->isThumb2())
10261       return isLegalT2ScaledAddressingMode(AM, VT);
10262
10263     int Scale = AM.Scale;
10264     switch (VT.getSimpleVT().SimpleTy) {
10265     default: return false;
10266     case MVT::i1:
10267     case MVT::i8:
10268     case MVT::i32:
10269       if (Scale < 0) Scale = -Scale;
10270       if (Scale == 1)
10271         return true;
10272       // r + r << imm
10273       return isPowerOf2_32(Scale & ~1);
10274     case MVT::i16:
10275     case MVT::i64:
10276       // r + r
10277       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10278         return true;
10279       return false;
10280
10281     case MVT::isVoid:
10282       // Note, we allow "void" uses (basically, uses that aren't loads or
10283       // stores), because arm allows folding a scale into many arithmetic
10284       // operations.  This should be made more precise and revisited later.
10285
10286       // Allow r << imm, but the imm has to be a multiple of two.
10287       if (Scale & 1) return false;
10288       return isPowerOf2_32(Scale);
10289     }
10290   }
10291   return true;
10292 }
10293
10294 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10295 /// icmp immediate, that is the target has icmp instructions which can compare
10296 /// a register against the immediate without having to materialize the
10297 /// immediate into a register.
10298 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10299   // Thumb2 and ARM modes can use cmn for negative immediates.
10300   if (!Subtarget->isThumb())
10301     return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
10302   if (Subtarget->isThumb2())
10303     return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
10304   // Thumb1 doesn't have cmn, and only 8-bit immediates.
10305   return Imm >= 0 && Imm <= 255;
10306 }
10307
10308 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10309 /// *or sub* immediate, that is the target has add or sub instructions which can
10310 /// add a register with the immediate without having to materialize the
10311 /// immediate into a register.
10312 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10313   // Same encoding for add/sub, just flip the sign.
10314   int64_t AbsImm = std::abs(Imm);
10315   if (!Subtarget->isThumb())
10316     return ARM_AM::getSOImmVal(AbsImm) != -1;
10317   if (Subtarget->isThumb2())
10318     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10319   // Thumb1 only has 8-bit unsigned immediate.
10320   return AbsImm >= 0 && AbsImm <= 255;
10321 }
10322
10323 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10324                                       bool isSEXTLoad, SDValue &Base,
10325                                       SDValue &Offset, bool &isInc,
10326                                       SelectionDAG &DAG) {
10327   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10328     return false;
10329
10330   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10331     // AddressingMode 3
10332     Base = Ptr->getOperand(0);
10333     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10334       int RHSC = (int)RHS->getZExtValue();
10335       if (RHSC < 0 && RHSC > -256) {
10336         assert(Ptr->getOpcode() == ISD::ADD);
10337         isInc = false;
10338         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10339         return true;
10340       }
10341     }
10342     isInc = (Ptr->getOpcode() == ISD::ADD);
10343     Offset = Ptr->getOperand(1);
10344     return true;
10345   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10346     // AddressingMode 2
10347     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10348       int RHSC = (int)RHS->getZExtValue();
10349       if (RHSC < 0 && RHSC > -0x1000) {
10350         assert(Ptr->getOpcode() == ISD::ADD);
10351         isInc = false;
10352         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10353         Base = Ptr->getOperand(0);
10354         return true;
10355       }
10356     }
10357
10358     if (Ptr->getOpcode() == ISD::ADD) {
10359       isInc = true;
10360       ARM_AM::ShiftOpc ShOpcVal=
10361         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10362       if (ShOpcVal != ARM_AM::no_shift) {
10363         Base = Ptr->getOperand(1);
10364         Offset = Ptr->getOperand(0);
10365       } else {
10366         Base = Ptr->getOperand(0);
10367         Offset = Ptr->getOperand(1);
10368       }
10369       return true;
10370     }
10371
10372     isInc = (Ptr->getOpcode() == ISD::ADD);
10373     Base = Ptr->getOperand(0);
10374     Offset = Ptr->getOperand(1);
10375     return true;
10376   }
10377
10378   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10379   return false;
10380 }
10381
10382 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10383                                      bool isSEXTLoad, SDValue &Base,
10384                                      SDValue &Offset, bool &isInc,
10385                                      SelectionDAG &DAG) {
10386   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10387     return false;
10388
10389   Base = Ptr->getOperand(0);
10390   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10391     int RHSC = (int)RHS->getZExtValue();
10392     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10393       assert(Ptr->getOpcode() == ISD::ADD);
10394       isInc = false;
10395       Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10396       return true;
10397     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10398       isInc = Ptr->getOpcode() == ISD::ADD;
10399       Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
10400       return true;
10401     }
10402   }
10403
10404   return false;
10405 }
10406
10407 /// getPreIndexedAddressParts - returns true by value, base pointer and
10408 /// offset pointer and addressing mode by reference if the node's address
10409 /// can be legally represented as pre-indexed load / store address.
10410 bool
10411 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10412                                              SDValue &Offset,
10413                                              ISD::MemIndexedMode &AM,
10414                                              SelectionDAG &DAG) const {
10415   if (Subtarget->isThumb1Only())
10416     return false;
10417
10418   EVT VT;
10419   SDValue Ptr;
10420   bool isSEXTLoad = false;
10421   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10422     Ptr = LD->getBasePtr();
10423     VT  = LD->getMemoryVT();
10424     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10425   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10426     Ptr = ST->getBasePtr();
10427     VT  = ST->getMemoryVT();
10428   } else
10429     return false;
10430
10431   bool isInc;
10432   bool isLegal = false;
10433   if (Subtarget->isThumb2())
10434     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10435                                        Offset, isInc, DAG);
10436   else
10437     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10438                                         Offset, isInc, DAG);
10439   if (!isLegal)
10440     return false;
10441
10442   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10443   return true;
10444 }
10445
10446 /// getPostIndexedAddressParts - returns true by value, base pointer and
10447 /// offset pointer and addressing mode by reference if this node can be
10448 /// combined with a load / store to form a post-indexed load / store.
10449 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10450                                                    SDValue &Base,
10451                                                    SDValue &Offset,
10452                                                    ISD::MemIndexedMode &AM,
10453                                                    SelectionDAG &DAG) const {
10454   if (Subtarget->isThumb1Only())
10455     return false;
10456
10457   EVT VT;
10458   SDValue Ptr;
10459   bool isSEXTLoad = false;
10460   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10461     VT  = LD->getMemoryVT();
10462     Ptr = LD->getBasePtr();
10463     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10464   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10465     VT  = ST->getMemoryVT();
10466     Ptr = ST->getBasePtr();
10467   } else
10468     return false;
10469
10470   bool isInc;
10471   bool isLegal = false;
10472   if (Subtarget->isThumb2())
10473     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10474                                        isInc, DAG);
10475   else
10476     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10477                                         isInc, DAG);
10478   if (!isLegal)
10479     return false;
10480
10481   if (Ptr != Base) {
10482     // Swap base ptr and offset to catch more post-index load / store when
10483     // it's legal. In Thumb2 mode, offset must be an immediate.
10484     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10485         !Subtarget->isThumb2())
10486       std::swap(Base, Offset);
10487
10488     // Post-indexed load / store update the base pointer.
10489     if (Ptr != Base)
10490       return false;
10491   }
10492
10493   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10494   return true;
10495 }
10496
10497 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10498                                                       APInt &KnownZero,
10499                                                       APInt &KnownOne,
10500                                                       const SelectionDAG &DAG,
10501                                                       unsigned Depth) const {
10502   unsigned BitWidth = KnownOne.getBitWidth();
10503   KnownZero = KnownOne = APInt(BitWidth, 0);
10504   switch (Op.getOpcode()) {
10505   default: break;
10506   case ARMISD::ADDC:
10507   case ARMISD::ADDE:
10508   case ARMISD::SUBC:
10509   case ARMISD::SUBE:
10510     // These nodes' second result is a boolean
10511     if (Op.getResNo() == 0)
10512       break;
10513     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10514     break;
10515   case ARMISD::CMOV: {
10516     // Bits are known zero/one if known on the LHS and RHS.
10517     DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10518     if (KnownZero == 0 && KnownOne == 0) return;
10519
10520     APInt KnownZeroRHS, KnownOneRHS;
10521     DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10522     KnownZero &= KnownZeroRHS;
10523     KnownOne  &= KnownOneRHS;
10524     return;
10525   }
10526   case ISD::INTRINSIC_W_CHAIN: {
10527     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10528     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10529     switch (IntID) {
10530     default: return;
10531     case Intrinsic::arm_ldaex:
10532     case Intrinsic::arm_ldrex: {
10533       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10534       unsigned MemBits = VT.getScalarType().getSizeInBits();
10535       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10536       return;
10537     }
10538     }
10539   }
10540   }
10541 }
10542
10543 //===----------------------------------------------------------------------===//
10544 //                           ARM Inline Assembly Support
10545 //===----------------------------------------------------------------------===//
10546
10547 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10548   // Looking for "rev" which is V6+.
10549   if (!Subtarget->hasV6Ops())
10550     return false;
10551
10552   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10553   std::string AsmStr = IA->getAsmString();
10554   SmallVector<StringRef, 4> AsmPieces;
10555   SplitString(AsmStr, AsmPieces, ";\n");
10556
10557   switch (AsmPieces.size()) {
10558   default: return false;
10559   case 1:
10560     AsmStr = AsmPieces[0];
10561     AsmPieces.clear();
10562     SplitString(AsmStr, AsmPieces, " \t,");
10563
10564     // rev $0, $1
10565     if (AsmPieces.size() == 3 &&
10566         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10567         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10568       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10569       if (Ty && Ty->getBitWidth() == 32)
10570         return IntrinsicLowering::LowerToByteSwap(CI);
10571     }
10572     break;
10573   }
10574
10575   return false;
10576 }
10577
10578 /// getConstraintType - Given a constraint letter, return the type of
10579 /// constraint it is for this target.
10580 ARMTargetLowering::ConstraintType
10581 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10582   if (Constraint.size() == 1) {
10583     switch (Constraint[0]) {
10584     default:  break;
10585     case 'l': return C_RegisterClass;
10586     case 'w': return C_RegisterClass;
10587     case 'h': return C_RegisterClass;
10588     case 'x': return C_RegisterClass;
10589     case 't': return C_RegisterClass;
10590     case 'j': return C_Other; // Constant for movw.
10591       // An address with a single base register. Due to the way we
10592       // currently handle addresses it is the same as an 'r' memory constraint.
10593     case 'Q': return C_Memory;
10594     }
10595   } else if (Constraint.size() == 2) {
10596     switch (Constraint[0]) {
10597     default: break;
10598     // All 'U+' constraints are addresses.
10599     case 'U': return C_Memory;
10600     }
10601   }
10602   return TargetLowering::getConstraintType(Constraint);
10603 }
10604
10605 /// Examine constraint type and operand type and determine a weight value.
10606 /// This object must already have been set up with the operand type
10607 /// and the current alternative constraint selected.
10608 TargetLowering::ConstraintWeight
10609 ARMTargetLowering::getSingleConstraintMatchWeight(
10610     AsmOperandInfo &info, const char *constraint) const {
10611   ConstraintWeight weight = CW_Invalid;
10612   Value *CallOperandVal = info.CallOperandVal;
10613     // If we don't have a value, we can't do a match,
10614     // but allow it at the lowest weight.
10615   if (!CallOperandVal)
10616     return CW_Default;
10617   Type *type = CallOperandVal->getType();
10618   // Look at the constraint type.
10619   switch (*constraint) {
10620   default:
10621     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10622     break;
10623   case 'l':
10624     if (type->isIntegerTy()) {
10625       if (Subtarget->isThumb())
10626         weight = CW_SpecificReg;
10627       else
10628         weight = CW_Register;
10629     }
10630     break;
10631   case 'w':
10632     if (type->isFloatingPointTy())
10633       weight = CW_Register;
10634     break;
10635   }
10636   return weight;
10637 }
10638
10639 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10640 RCPair
10641 ARMTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
10642                                                 const std::string &Constraint,
10643                                                 MVT VT) const {
10644   if (Constraint.size() == 1) {
10645     // GCC ARM Constraint Letters
10646     switch (Constraint[0]) {
10647     case 'l': // Low regs or general regs.
10648       if (Subtarget->isThumb())
10649         return RCPair(0U, &ARM::tGPRRegClass);
10650       return RCPair(0U, &ARM::GPRRegClass);
10651     case 'h': // High regs or no regs.
10652       if (Subtarget->isThumb())
10653         return RCPair(0U, &ARM::hGPRRegClass);
10654       break;
10655     case 'r':
10656       if (Subtarget->isThumb1Only())
10657         return RCPair(0U, &ARM::tGPRRegClass);
10658       return RCPair(0U, &ARM::GPRRegClass);
10659     case 'w':
10660       if (VT == MVT::Other)
10661         break;
10662       if (VT == MVT::f32)
10663         return RCPair(0U, &ARM::SPRRegClass);
10664       if (VT.getSizeInBits() == 64)
10665         return RCPair(0U, &ARM::DPRRegClass);
10666       if (VT.getSizeInBits() == 128)
10667         return RCPair(0U, &ARM::QPRRegClass);
10668       break;
10669     case 'x':
10670       if (VT == MVT::Other)
10671         break;
10672       if (VT == MVT::f32)
10673         return RCPair(0U, &ARM::SPR_8RegClass);
10674       if (VT.getSizeInBits() == 64)
10675         return RCPair(0U, &ARM::DPR_8RegClass);
10676       if (VT.getSizeInBits() == 128)
10677         return RCPair(0U, &ARM::QPR_8RegClass);
10678       break;
10679     case 't':
10680       if (VT == MVT::f32)
10681         return RCPair(0U, &ARM::SPRRegClass);
10682       break;
10683     }
10684   }
10685   if (StringRef("{cc}").equals_lower(Constraint))
10686     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10687
10688   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10689 }
10690
10691 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10692 /// vector.  If it is invalid, don't add anything to Ops.
10693 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10694                                                      std::string &Constraint,
10695                                                      std::vector<SDValue>&Ops,
10696                                                      SelectionDAG &DAG) const {
10697   SDValue Result;
10698
10699   // Currently only support length 1 constraints.
10700   if (Constraint.length() != 1) return;
10701
10702   char ConstraintLetter = Constraint[0];
10703   switch (ConstraintLetter) {
10704   default: break;
10705   case 'j':
10706   case 'I': case 'J': case 'K': case 'L':
10707   case 'M': case 'N': case 'O':
10708     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10709     if (!C)
10710       return;
10711
10712     int64_t CVal64 = C->getSExtValue();
10713     int CVal = (int) CVal64;
10714     // None of these constraints allow values larger than 32 bits.  Check
10715     // that the value fits in an int.
10716     if (CVal != CVal64)
10717       return;
10718
10719     switch (ConstraintLetter) {
10720       case 'j':
10721         // Constant suitable for movw, must be between 0 and
10722         // 65535.
10723         if (Subtarget->hasV6T2Ops())
10724           if (CVal >= 0 && CVal <= 65535)
10725             break;
10726         return;
10727       case 'I':
10728         if (Subtarget->isThumb1Only()) {
10729           // This must be a constant between 0 and 255, for ADD
10730           // immediates.
10731           if (CVal >= 0 && CVal <= 255)
10732             break;
10733         } else if (Subtarget->isThumb2()) {
10734           // A constant that can be used as an immediate value in a
10735           // data-processing instruction.
10736           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10737             break;
10738         } else {
10739           // A constant that can be used as an immediate value in a
10740           // data-processing instruction.
10741           if (ARM_AM::getSOImmVal(CVal) != -1)
10742             break;
10743         }
10744         return;
10745
10746       case 'J':
10747         if (Subtarget->isThumb()) {  // FIXME thumb2
10748           // This must be a constant between -255 and -1, for negated ADD
10749           // immediates. This can be used in GCC with an "n" modifier that
10750           // prints the negated value, for use with SUB instructions. It is
10751           // not useful otherwise but is implemented for compatibility.
10752           if (CVal >= -255 && CVal <= -1)
10753             break;
10754         } else {
10755           // This must be a constant between -4095 and 4095. It is not clear
10756           // what this constraint is intended for. Implemented for
10757           // compatibility with GCC.
10758           if (CVal >= -4095 && CVal <= 4095)
10759             break;
10760         }
10761         return;
10762
10763       case 'K':
10764         if (Subtarget->isThumb1Only()) {
10765           // A 32-bit value where only one byte has a nonzero value. Exclude
10766           // zero to match GCC. This constraint is used by GCC internally for
10767           // constants that can be loaded with a move/shift combination.
10768           // It is not useful otherwise but is implemented for compatibility.
10769           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10770             break;
10771         } else if (Subtarget->isThumb2()) {
10772           // A constant whose bitwise inverse can be used as an immediate
10773           // value in a data-processing instruction. This can be used in GCC
10774           // with a "B" modifier that prints the inverted value, for use with
10775           // BIC and MVN instructions. It is not useful otherwise but is
10776           // implemented for compatibility.
10777           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10778             break;
10779         } else {
10780           // A constant whose bitwise inverse can be used as an immediate
10781           // value in a data-processing instruction. This can be used in GCC
10782           // with a "B" modifier that prints the inverted value, for use with
10783           // BIC and MVN instructions. It is not useful otherwise but is
10784           // implemented for compatibility.
10785           if (ARM_AM::getSOImmVal(~CVal) != -1)
10786             break;
10787         }
10788         return;
10789
10790       case 'L':
10791         if (Subtarget->isThumb1Only()) {
10792           // This must be a constant between -7 and 7,
10793           // for 3-operand ADD/SUB immediate instructions.
10794           if (CVal >= -7 && CVal < 7)
10795             break;
10796         } else if (Subtarget->isThumb2()) {
10797           // A constant whose negation can be used as an immediate value in a
10798           // data-processing instruction. This can be used in GCC with an "n"
10799           // modifier that prints the negated value, for use with SUB
10800           // instructions. It is not useful otherwise but is implemented for
10801           // compatibility.
10802           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10803             break;
10804         } else {
10805           // A constant whose negation can be used as an immediate value in a
10806           // data-processing instruction. This can be used in GCC with an "n"
10807           // modifier that prints the negated value, for use with SUB
10808           // instructions. It is not useful otherwise but is implemented for
10809           // compatibility.
10810           if (ARM_AM::getSOImmVal(-CVal) != -1)
10811             break;
10812         }
10813         return;
10814
10815       case 'M':
10816         if (Subtarget->isThumb()) { // FIXME thumb2
10817           // This must be a multiple of 4 between 0 and 1020, for
10818           // ADD sp + immediate.
10819           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10820             break;
10821         } else {
10822           // A power of two or a constant between 0 and 32.  This is used in
10823           // GCC for the shift amount on shifted register operands, but it is
10824           // useful in general for any shift amounts.
10825           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10826             break;
10827         }
10828         return;
10829
10830       case 'N':
10831         if (Subtarget->isThumb()) {  // FIXME thumb2
10832           // This must be a constant between 0 and 31, for shift amounts.
10833           if (CVal >= 0 && CVal <= 31)
10834             break;
10835         }
10836         return;
10837
10838       case 'O':
10839         if (Subtarget->isThumb()) {  // FIXME thumb2
10840           // This must be a multiple of 4 between -508 and 508, for
10841           // ADD/SUB sp = sp + immediate.
10842           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10843             break;
10844         }
10845         return;
10846     }
10847     Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
10848     break;
10849   }
10850
10851   if (Result.getNode()) {
10852     Ops.push_back(Result);
10853     return;
10854   }
10855   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10856 }
10857
10858 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10859   assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10860   unsigned Opcode = Op->getOpcode();
10861   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10862          "Invalid opcode for Div/Rem lowering");
10863   bool isSigned = (Opcode == ISD::SDIVREM);
10864   EVT VT = Op->getValueType(0);
10865   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10866
10867   RTLIB::Libcall LC;
10868   switch (VT.getSimpleVT().SimpleTy) {
10869   default: llvm_unreachable("Unexpected request for libcall!");
10870   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
10871   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10872   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10873   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10874   }
10875
10876   SDValue InChain = DAG.getEntryNode();
10877
10878   TargetLowering::ArgListTy Args;
10879   TargetLowering::ArgListEntry Entry;
10880   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
10881     EVT ArgVT = Op->getOperand(i).getValueType();
10882     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10883     Entry.Node = Op->getOperand(i);
10884     Entry.Ty = ArgTy;
10885     Entry.isSExt = isSigned;
10886     Entry.isZExt = !isSigned;
10887     Args.push_back(Entry);
10888   }
10889
10890   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
10891                                          getPointerTy());
10892
10893   Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
10894
10895   SDLoc dl(Op);
10896   TargetLowering::CallLoweringInfo CLI(DAG);
10897   CLI.setDebugLoc(dl).setChain(InChain)
10898     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
10899     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
10900
10901   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
10902   return CallInfo.first;
10903 }
10904
10905 SDValue
10906 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
10907   assert(Subtarget->isTargetWindows() && "unsupported target platform");
10908   SDLoc DL(Op);
10909
10910   // Get the inputs.
10911   SDValue Chain = Op.getOperand(0);
10912   SDValue Size  = Op.getOperand(1);
10913
10914   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
10915                               DAG.getConstant(2, DL, MVT::i32));
10916
10917   SDValue Flag;
10918   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
10919   Flag = Chain.getValue(1);
10920
10921   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10922   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
10923
10924   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
10925   Chain = NewSP.getValue(1);
10926
10927   SDValue Ops[2] = { NewSP, Chain };
10928   return DAG.getMergeValues(Ops, DL);
10929 }
10930
10931 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
10932   assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
10933          "Unexpected type for custom-lowering FP_EXTEND");
10934
10935   RTLIB::Libcall LC;
10936   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
10937
10938   SDValue SrcVal = Op.getOperand(0);
10939   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
10940                      /*isSigned*/ false, SDLoc(Op)).first;
10941 }
10942
10943 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
10944   assert(Op.getOperand(0).getValueType() == MVT::f64 &&
10945          Subtarget->isFPOnlySP() &&
10946          "Unexpected type for custom-lowering FP_ROUND");
10947
10948   RTLIB::Libcall LC;
10949   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
10950
10951   SDValue SrcVal = Op.getOperand(0);
10952   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
10953                      /*isSigned*/ false, SDLoc(Op)).first;
10954 }
10955
10956 bool
10957 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10958   // The ARM target isn't yet aware of offsets.
10959   return false;
10960 }
10961
10962 bool ARM::isBitFieldInvertedMask(unsigned v) {
10963   if (v == 0xffffffff)
10964     return false;
10965
10966   // there can be 1's on either or both "outsides", all the "inside"
10967   // bits must be 0's
10968   return isShiftedMask_32(~v);
10969 }
10970
10971 /// isFPImmLegal - Returns true if the target can instruction select the
10972 /// specified FP immediate natively. If false, the legalizer will
10973 /// materialize the FP immediate as a load from a constant pool.
10974 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10975   if (!Subtarget->hasVFP3())
10976     return false;
10977   if (VT == MVT::f32)
10978     return ARM_AM::getFP32Imm(Imm) != -1;
10979   if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
10980     return ARM_AM::getFP64Imm(Imm) != -1;
10981   return false;
10982 }
10983
10984 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10985 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
10986 /// specified in the intrinsic calls.
10987 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10988                                            const CallInst &I,
10989                                            unsigned Intrinsic) const {
10990   switch (Intrinsic) {
10991   case Intrinsic::arm_neon_vld1:
10992   case Intrinsic::arm_neon_vld2:
10993   case Intrinsic::arm_neon_vld3:
10994   case Intrinsic::arm_neon_vld4:
10995   case Intrinsic::arm_neon_vld2lane:
10996   case Intrinsic::arm_neon_vld3lane:
10997   case Intrinsic::arm_neon_vld4lane: {
10998     Info.opc = ISD::INTRINSIC_W_CHAIN;
10999     // Conservatively set memVT to the entire set of vectors loaded.
11000     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
11001     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11002     Info.ptrVal = I.getArgOperand(0);
11003     Info.offset = 0;
11004     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11005     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11006     Info.vol = false; // volatile loads with NEON intrinsics not supported
11007     Info.readMem = true;
11008     Info.writeMem = false;
11009     return true;
11010   }
11011   case Intrinsic::arm_neon_vst1:
11012   case Intrinsic::arm_neon_vst2:
11013   case Intrinsic::arm_neon_vst3:
11014   case Intrinsic::arm_neon_vst4:
11015   case Intrinsic::arm_neon_vst2lane:
11016   case Intrinsic::arm_neon_vst3lane:
11017   case Intrinsic::arm_neon_vst4lane: {
11018     Info.opc = ISD::INTRINSIC_VOID;
11019     // Conservatively set memVT to the entire set of vectors stored.
11020     unsigned NumElts = 0;
11021     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11022       Type *ArgTy = I.getArgOperand(ArgI)->getType();
11023       if (!ArgTy->isVectorTy())
11024         break;
11025       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
11026     }
11027     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11028     Info.ptrVal = I.getArgOperand(0);
11029     Info.offset = 0;
11030     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11031     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11032     Info.vol = false; // volatile stores with NEON intrinsics not supported
11033     Info.readMem = false;
11034     Info.writeMem = true;
11035     return true;
11036   }
11037   case Intrinsic::arm_ldaex:
11038   case Intrinsic::arm_ldrex: {
11039     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11040     Info.opc = ISD::INTRINSIC_W_CHAIN;
11041     Info.memVT = MVT::getVT(PtrTy->getElementType());
11042     Info.ptrVal = I.getArgOperand(0);
11043     Info.offset = 0;
11044     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11045     Info.vol = true;
11046     Info.readMem = true;
11047     Info.writeMem = false;
11048     return true;
11049   }
11050   case Intrinsic::arm_stlex:
11051   case Intrinsic::arm_strex: {
11052     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11053     Info.opc = ISD::INTRINSIC_W_CHAIN;
11054     Info.memVT = MVT::getVT(PtrTy->getElementType());
11055     Info.ptrVal = I.getArgOperand(1);
11056     Info.offset = 0;
11057     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11058     Info.vol = true;
11059     Info.readMem = false;
11060     Info.writeMem = true;
11061     return true;
11062   }
11063   case Intrinsic::arm_stlexd:
11064   case Intrinsic::arm_strexd: {
11065     Info.opc = ISD::INTRINSIC_W_CHAIN;
11066     Info.memVT = MVT::i64;
11067     Info.ptrVal = I.getArgOperand(2);
11068     Info.offset = 0;
11069     Info.align = 8;
11070     Info.vol = true;
11071     Info.readMem = false;
11072     Info.writeMem = true;
11073     return true;
11074   }
11075   case Intrinsic::arm_ldaexd:
11076   case Intrinsic::arm_ldrexd: {
11077     Info.opc = ISD::INTRINSIC_W_CHAIN;
11078     Info.memVT = MVT::i64;
11079     Info.ptrVal = I.getArgOperand(0);
11080     Info.offset = 0;
11081     Info.align = 8;
11082     Info.vol = true;
11083     Info.readMem = true;
11084     Info.writeMem = false;
11085     return true;
11086   }
11087   default:
11088     break;
11089   }
11090
11091   return false;
11092 }
11093
11094 /// \brief Returns true if it is beneficial to convert a load of a constant
11095 /// to just the constant itself.
11096 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11097                                                           Type *Ty) const {
11098   assert(Ty->isIntegerTy());
11099
11100   unsigned Bits = Ty->getPrimitiveSizeInBits();
11101   if (Bits == 0 || Bits > 32)
11102     return false;
11103   return true;
11104 }
11105
11106 bool ARMTargetLowering::hasLoadLinkedStoreConditional() const { return true; }
11107
11108 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
11109                                         ARM_MB::MemBOpt Domain) const {
11110   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11111
11112   // First, if the target has no DMB, see what fallback we can use.
11113   if (!Subtarget->hasDataBarrier()) {
11114     // Some ARMv6 cpus can support data barriers with an mcr instruction.
11115     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
11116     // here.
11117     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
11118       Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
11119       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
11120                         Builder.getInt32(0), Builder.getInt32(7),
11121                         Builder.getInt32(10), Builder.getInt32(5)};
11122       return Builder.CreateCall(MCR, args);
11123     } else {
11124       // Instead of using barriers, atomic accesses on these subtargets use
11125       // libcalls.
11126       llvm_unreachable("makeDMB on a target so old that it has no barriers");
11127     }
11128   } else {
11129     Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
11130     // Only a full system barrier exists in the M-class architectures.
11131     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
11132     Constant *CDomain = Builder.getInt32(Domain);
11133     return Builder.CreateCall(DMB, CDomain);
11134   }
11135 }
11136
11137 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11138 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11139                                          AtomicOrdering Ord, bool IsStore,
11140                                          bool IsLoad) const {
11141   if (!getInsertFencesForAtomic())
11142     return nullptr;
11143
11144   switch (Ord) {
11145   case NotAtomic:
11146   case Unordered:
11147     llvm_unreachable("Invalid fence: unordered/non-atomic");
11148   case Monotonic:
11149   case Acquire:
11150     return nullptr; // Nothing to do
11151   case SequentiallyConsistent:
11152     if (!IsStore)
11153       return nullptr; // Nothing to do
11154     /*FALLTHROUGH*/
11155   case Release:
11156   case AcquireRelease:
11157     if (Subtarget->isSwift())
11158       return makeDMB(Builder, ARM_MB::ISHST);
11159     // FIXME: add a comment with a link to documentation justifying this.
11160     else
11161       return makeDMB(Builder, ARM_MB::ISH);
11162   }
11163   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
11164 }
11165
11166 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11167                                           AtomicOrdering Ord, bool IsStore,
11168                                           bool IsLoad) const {
11169   if (!getInsertFencesForAtomic())
11170     return nullptr;
11171
11172   switch (Ord) {
11173   case NotAtomic:
11174   case Unordered:
11175     llvm_unreachable("Invalid fence: unordered/not-atomic");
11176   case Monotonic:
11177   case Release:
11178     return nullptr; // Nothing to do
11179   case Acquire:
11180   case AcquireRelease:
11181   case SequentiallyConsistent:
11182     return makeDMB(Builder, ARM_MB::ISH);
11183   }
11184   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
11185 }
11186
11187 // Loads and stores less than 64-bits are already atomic; ones above that
11188 // are doomed anyway, so defer to the default libcall and blame the OS when
11189 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11190 // anything for those.
11191 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11192   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11193   return (Size == 64) && !Subtarget->isMClass();
11194 }
11195
11196 // Loads and stores less than 64-bits are already atomic; ones above that
11197 // are doomed anyway, so defer to the default libcall and blame the OS when
11198 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11199 // anything for those.
11200 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
11201 // guarantee, see DDI0406C ARM architecture reference manual,
11202 // sections A8.8.72-74 LDRD)
11203 bool ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11204   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11205   return (Size == 64) && !Subtarget->isMClass();
11206 }
11207
11208 // For the real atomic operations, we have ldrex/strex up to 32 bits,
11209 // and up to 64 bits on the non-M profiles
11210 TargetLoweringBase::AtomicRMWExpansionKind
11211 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11212   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11213   return (Size <= (Subtarget->isMClass() ? 32U : 64U))
11214              ? AtomicRMWExpansionKind::LLSC
11215              : AtomicRMWExpansionKind::None;
11216 }
11217
11218 // This has so far only been implemented for MachO.
11219 bool ARMTargetLowering::useLoadStackGuardNode() const {
11220   return Subtarget->isTargetMachO();
11221 }
11222
11223 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
11224                                                   unsigned &Cost) const {
11225   // If we do not have NEON, vector types are not natively supported.
11226   if (!Subtarget->hasNEON())
11227     return false;
11228
11229   // Floating point values and vector values map to the same register file.
11230   // Therefore, althought we could do a store extract of a vector type, this is
11231   // better to leave at float as we have more freedom in the addressing mode for
11232   // those.
11233   if (VectorTy->isFPOrFPVectorTy())
11234     return false;
11235
11236   // If the index is unknown at compile time, this is very expensive to lower
11237   // and it is not possible to combine the store with the extract.
11238   if (!isa<ConstantInt>(Idx))
11239     return false;
11240
11241   assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
11242   unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
11243   // We can do a store + vector extract on any vector that fits perfectly in a D
11244   // or Q register.
11245   if (BitWidth == 64 || BitWidth == 128) {
11246     Cost = 0;
11247     return true;
11248   }
11249   return false;
11250 }
11251
11252 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11253                                          AtomicOrdering Ord) const {
11254   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11255   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11256   bool IsAcquire = isAtLeastAcquire(Ord);
11257
11258   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
11259   // intrinsic must return {i32, i32} and we have to recombine them into a
11260   // single i64 here.
11261   if (ValTy->getPrimitiveSizeInBits() == 64) {
11262     Intrinsic::ID Int =
11263         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
11264     Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
11265
11266     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11267     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
11268
11269     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11270     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11271     if (!Subtarget->isLittle())
11272       std::swap (Lo, Hi);
11273     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11274     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11275     return Builder.CreateOr(
11276         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
11277   }
11278
11279   Type *Tys[] = { Addr->getType() };
11280   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
11281   Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
11282
11283   return Builder.CreateTruncOrBitCast(
11284       Builder.CreateCall(Ldrex, Addr),
11285       cast<PointerType>(Addr->getType())->getElementType());
11286 }
11287
11288 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
11289                                                Value *Addr,
11290                                                AtomicOrdering Ord) const {
11291   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11292   bool IsRelease = isAtLeastRelease(Ord);
11293
11294   // Since the intrinsics must have legal type, the i64 intrinsics take two
11295   // parameters: "i32, i32". We must marshal Val into the appropriate form
11296   // before the call.
11297   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
11298     Intrinsic::ID Int =
11299         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
11300     Function *Strex = Intrinsic::getDeclaration(M, Int);
11301     Type *Int32Ty = Type::getInt32Ty(M->getContext());
11302
11303     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
11304     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
11305     if (!Subtarget->isLittle())
11306       std::swap (Lo, Hi);
11307     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11308     return Builder.CreateCall3(Strex, Lo, Hi, Addr);
11309   }
11310
11311   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
11312   Type *Tys[] = { Addr->getType() };
11313   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
11314
11315   return Builder.CreateCall2(
11316       Strex, Builder.CreateZExtOrBitCast(
11317                  Val, Strex->getFunctionType()->getParamType(0)),
11318       Addr);
11319 }
11320
11321 enum HABaseType {
11322   HA_UNKNOWN = 0,
11323   HA_FLOAT,
11324   HA_DOUBLE,
11325   HA_VECT64,
11326   HA_VECT128
11327 };
11328
11329 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
11330                                    uint64_t &Members) {
11331   if (const StructType *ST = dyn_cast<StructType>(Ty)) {
11332     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
11333       uint64_t SubMembers = 0;
11334       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
11335         return false;
11336       Members += SubMembers;
11337     }
11338   } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
11339     uint64_t SubMembers = 0;
11340     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
11341       return false;
11342     Members += SubMembers * AT->getNumElements();
11343   } else if (Ty->isFloatTy()) {
11344     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
11345       return false;
11346     Members = 1;
11347     Base = HA_FLOAT;
11348   } else if (Ty->isDoubleTy()) {
11349     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
11350       return false;
11351     Members = 1;
11352     Base = HA_DOUBLE;
11353   } else if (const VectorType *VT = dyn_cast<VectorType>(Ty)) {
11354     Members = 1;
11355     switch (Base) {
11356     case HA_FLOAT:
11357     case HA_DOUBLE:
11358       return false;
11359     case HA_VECT64:
11360       return VT->getBitWidth() == 64;
11361     case HA_VECT128:
11362       return VT->getBitWidth() == 128;
11363     case HA_UNKNOWN:
11364       switch (VT->getBitWidth()) {
11365       case 64:
11366         Base = HA_VECT64;
11367         return true;
11368       case 128:
11369         Base = HA_VECT128;
11370         return true;
11371       default:
11372         return false;
11373       }
11374     }
11375   }
11376
11377   return (Members > 0 && Members <= 4);
11378 }
11379
11380 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
11381 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
11382 /// passing according to AAPCS rules.
11383 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
11384     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11385   if (getEffectiveCallingConv(CallConv, isVarArg) !=
11386       CallingConv::ARM_AAPCS_VFP)
11387     return false;
11388
11389   HABaseType Base = HA_UNKNOWN;
11390   uint64_t Members = 0;
11391   bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
11392   DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
11393
11394   bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
11395   return IsHA || IsIntArray;
11396 }