a7a47d972cbb1f09227d7c6750f39ee32582a6e2
[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/CodeGen/CallingConvLower.h"
27 #include "llvm/CodeGen/IntrinsicLowering.h"
28 #include "llvm/CodeGen/MachineBasicBlock.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/CodeGen/SelectionDAG.h"
35 #include "llvm/IR/CallingConv.h"
36 #include "llvm/IR/Constants.h"
37 #include "llvm/IR/Function.h"
38 #include "llvm/IR/GlobalValue.h"
39 #include "llvm/IR/IRBuilder.h"
40 #include "llvm/IR/Instruction.h"
41 #include "llvm/IR/Instructions.h"
42 #include "llvm/IR/Intrinsics.h"
43 #include "llvm/IR/Type.h"
44 #include "llvm/MC/MCSectionMachO.h"
45 #include "llvm/Support/CommandLine.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include "llvm/Support/MathExtras.h"
49 #include "llvm/Target/TargetOptions.h"
50 #include <utility>
51 using namespace llvm;
52
53 #define DEBUG_TYPE "arm-isel"
54
55 STATISTIC(NumTailCalls, "Number of tail calls");
56 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
57 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
58
59 cl::opt<bool>
60 EnableARMLongCalls("arm-long-calls", cl::Hidden,
61   cl::desc("Generate calls via indirect call instructions"),
62   cl::init(false));
63
64 static cl::opt<bool>
65 ARMInterworking("arm-interworking", cl::Hidden,
66   cl::desc("Enable / disable ARM interworking (for debugging only)"),
67   cl::init(true));
68
69 namespace {
70   class ARMCCState : public CCState {
71   public:
72     ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
73                const TargetMachine &TM, SmallVectorImpl<CCValAssign> &locs,
74                LLVMContext &C, ParmContext PC)
75         : CCState(CC, isVarArg, MF, TM, locs, C) {
76       assert(((PC == Call) || (PC == Prologue)) &&
77              "ARMCCState users must specify whether their context is call"
78              "or prologue generation.");
79       CallOrPrologue = PC;
80     }
81   };
82 }
83
84 // The APCS parameter registers.
85 static const MCPhysReg GPRArgRegs[] = {
86   ARM::R0, ARM::R1, ARM::R2, ARM::R3
87 };
88
89 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
90                                        MVT PromotedBitwiseVT) {
91   if (VT != PromotedLdStVT) {
92     setOperationAction(ISD::LOAD, VT, Promote);
93     AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
94
95     setOperationAction(ISD::STORE, VT, Promote);
96     AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
97   }
98
99   MVT ElemTy = VT.getVectorElementType();
100   if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
101     setOperationAction(ISD::SETCC, VT, Custom);
102   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
103   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
104   if (ElemTy == MVT::i32) {
105     setOperationAction(ISD::SINT_TO_FP, VT, Custom);
106     setOperationAction(ISD::UINT_TO_FP, VT, Custom);
107     setOperationAction(ISD::FP_TO_SINT, VT, Custom);
108     setOperationAction(ISD::FP_TO_UINT, VT, Custom);
109   } else {
110     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
111     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
112     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
113     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
114   }
115   setOperationAction(ISD::BUILD_VECTOR,      VT, Custom);
116   setOperationAction(ISD::VECTOR_SHUFFLE,    VT, Custom);
117   setOperationAction(ISD::CONCAT_VECTORS,    VT, Legal);
118   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
119   setOperationAction(ISD::SELECT,            VT, Expand);
120   setOperationAction(ISD::SELECT_CC,         VT, Expand);
121   setOperationAction(ISD::VSELECT,           VT, Expand);
122   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
123   if (VT.isInteger()) {
124     setOperationAction(ISD::SHL, VT, Custom);
125     setOperationAction(ISD::SRA, VT, Custom);
126     setOperationAction(ISD::SRL, VT, Custom);
127   }
128
129   // Promote all bit-wise operations.
130   if (VT.isInteger() && VT != PromotedBitwiseVT) {
131     setOperationAction(ISD::AND, VT, Promote);
132     AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
133     setOperationAction(ISD::OR,  VT, Promote);
134     AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
135     setOperationAction(ISD::XOR, VT, Promote);
136     AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
137   }
138
139   // Neon does not support vector divide/remainder operations.
140   setOperationAction(ISD::SDIV, VT, Expand);
141   setOperationAction(ISD::UDIV, VT, Expand);
142   setOperationAction(ISD::FDIV, VT, Expand);
143   setOperationAction(ISD::SREM, VT, Expand);
144   setOperationAction(ISD::UREM, VT, Expand);
145   setOperationAction(ISD::FREM, VT, Expand);
146 }
147
148 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
149   addRegisterClass(VT, &ARM::DPRRegClass);
150   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
151 }
152
153 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
154   addRegisterClass(VT, &ARM::DPairRegClass);
155   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
156 }
157
158 static TargetLoweringObjectFile *createTLOF(const Triple &TT) {
159   if (TT.isOSBinFormatMachO())
160     return new TargetLoweringObjectFileMachO();
161   if (TT.isOSWindows())
162     return new TargetLoweringObjectFileCOFF();
163   return new ARMElfTargetObjectFile();
164 }
165
166 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
167     : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))) {
168   Subtarget = &TM.getSubtarget<ARMSubtarget>();
169   RegInfo = TM.getRegisterInfo();
170   Itins = TM.getInstrItineraryData();
171
172   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
173
174   if (Subtarget->isTargetMachO()) {
175     // Uses VFP for Thumb libfuncs if available.
176     if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
177         Subtarget->hasARMOps() && !TM.Options.UseSoftFloat) {
178       // Single-precision floating-point arithmetic.
179       setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
180       setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
181       setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
182       setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
183
184       // Double-precision floating-point arithmetic.
185       setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
186       setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
187       setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
188       setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
189
190       // Single-precision comparisons.
191       setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
192       setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
193       setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
194       setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
195       setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
196       setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
197       setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
198       setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
199
200       setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
201       setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
202       setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
203       setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
204       setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
205       setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
206       setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
207       setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
208
209       // Double-precision comparisons.
210       setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
211       setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
212       setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
213       setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
214       setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
215       setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
216       setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
217       setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
218
219       setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
220       setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
221       setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
222       setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
223       setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
224       setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
225       setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
226       setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
227
228       // Floating-point to integer conversions.
229       // i64 conversions are done via library routines even when generating VFP
230       // instructions, so use the same ones.
231       setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
232       setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
233       setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
234       setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
235
236       // Conversions between floating types.
237       setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
238       setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
239
240       // Integer to floating-point conversions.
241       // i64 conversions are done via library routines even when generating VFP
242       // instructions, so use the same ones.
243       // FIXME: There appears to be some naming inconsistency in ARM libgcc:
244       // e.g., __floatunsidf vs. __floatunssidfvfp.
245       setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
246       setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
247       setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
248       setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
249     }
250   }
251
252   // These libcalls are not available in 32-bit.
253   setLibcallName(RTLIB::SHL_I128, nullptr);
254   setLibcallName(RTLIB::SRL_I128, nullptr);
255   setLibcallName(RTLIB::SRA_I128, nullptr);
256
257   if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO() &&
258       !Subtarget->isTargetWindows()) {
259     static const struct {
260       const RTLIB::Libcall Op;
261       const char * const Name;
262       const CallingConv::ID CC;
263       const ISD::CondCode Cond;
264     } LibraryCalls[] = {
265       // Double-precision floating-point arithmetic helper functions
266       // RTABI chapter 4.1.2, Table 2
267       { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
268       { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
269       { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
270       { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
271
272       // Double-precision floating-point comparison helper functions
273       // RTABI chapter 4.1.2, Table 3
274       { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
275       { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
276       { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
277       { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
278       { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
279       { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
280       { RTLIB::UO_F64,  "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
281       { RTLIB::O_F64,   "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
282
283       // Single-precision floating-point arithmetic helper functions
284       // RTABI chapter 4.1.2, Table 4
285       { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
286       { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
287       { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
288       { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
289
290       // Single-precision floating-point comparison helper functions
291       // RTABI chapter 4.1.2, Table 5
292       { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
293       { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
294       { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
295       { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
296       { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
297       { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
298       { RTLIB::UO_F32,  "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
299       { RTLIB::O_F32,   "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
300
301       // Floating-point to integer conversions.
302       // RTABI chapter 4.1.2, Table 6
303       { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
304       { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
305       { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
306       { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
307       { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
308       { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
309       { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
310       { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
311
312       // Conversions between floating types.
313       // RTABI chapter 4.1.2, Table 7
314       { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
315       { RTLIB::FPEXT_F32_F64,   "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
316
317       // Integer to floating-point conversions.
318       // RTABI chapter 4.1.2, Table 8
319       { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
320       { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
321       { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
322       { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
323       { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
324       { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
325       { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
326       { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
327
328       // Long long helper functions
329       // RTABI chapter 4.2, Table 9
330       { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
331       { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
332       { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
333       { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
334
335       // Integer division functions
336       // RTABI chapter 4.3.1
337       { RTLIB::SDIV_I8,  "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
338       { RTLIB::SDIV_I16, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
339       { RTLIB::SDIV_I32, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
340       { RTLIB::SDIV_I64, "__aeabi_ldivmod",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
341       { RTLIB::UDIV_I8,  "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
342       { RTLIB::UDIV_I16, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
343       { RTLIB::UDIV_I32, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
344       { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
345
346       // Memory operations
347       // RTABI chapter 4.3.4
348       { RTLIB::MEMCPY,  "__aeabi_memcpy",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
349       { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
350       { RTLIB::MEMSET,  "__aeabi_memset",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
351     };
352
353     for (const auto &LC : LibraryCalls) {
354       setLibcallName(LC.Op, LC.Name);
355       setLibcallCallingConv(LC.Op, LC.CC);
356       if (LC.Cond != ISD::SETCC_INVALID)
357         setCmpLibcallCC(LC.Op, LC.Cond);
358     }
359   }
360
361   if (Subtarget->isTargetWindows()) {
362     static const struct {
363       const RTLIB::Libcall Op;
364       const char * const Name;
365       const CallingConv::ID CC;
366     } LibraryCalls[] = {
367       { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
368       { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
369       { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
370       { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
371       { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
372       { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
373       { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
374       { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
375     };
376
377     for (const auto &LC : LibraryCalls) {
378       setLibcallName(LC.Op, LC.Name);
379       setLibcallCallingConv(LC.Op, LC.CC);
380     }
381   }
382
383   // Use divmod compiler-rt calls for iOS 5.0 and later.
384   if (Subtarget->getTargetTriple().isiOS() &&
385       !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
386     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
387     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
388   }
389
390   if (Subtarget->isThumb1Only())
391     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
392   else
393     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
394   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
395       !Subtarget->isThumb1Only()) {
396     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
397     if (!Subtarget->isFPOnlySP())
398       addRegisterClass(MVT::f64, &ARM::DPRRegClass);
399
400     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
401   }
402
403   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
404        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
405     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
406          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
407       setTruncStoreAction((MVT::SimpleValueType)VT,
408                           (MVT::SimpleValueType)InnerVT, Expand);
409     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
410     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
411     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
412
413     setOperationAction(ISD::MULHS, (MVT::SimpleValueType)VT, Expand);
414     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
415     setOperationAction(ISD::MULHU, (MVT::SimpleValueType)VT, Expand);
416     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
417
418     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
419   }
420
421   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
422   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
423
424   if (Subtarget->hasNEON()) {
425     addDRTypeForNEON(MVT::v2f32);
426     addDRTypeForNEON(MVT::v8i8);
427     addDRTypeForNEON(MVT::v4i16);
428     addDRTypeForNEON(MVT::v2i32);
429     addDRTypeForNEON(MVT::v1i64);
430
431     addQRTypeForNEON(MVT::v4f32);
432     addQRTypeForNEON(MVT::v2f64);
433     addQRTypeForNEON(MVT::v16i8);
434     addQRTypeForNEON(MVT::v8i16);
435     addQRTypeForNEON(MVT::v4i32);
436     addQRTypeForNEON(MVT::v2i64);
437
438     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
439     // neither Neon nor VFP support any arithmetic operations on it.
440     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
441     // supported for v4f32.
442     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
443     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
444     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
445     // FIXME: Code duplication: FDIV and FREM are expanded always, see
446     // ARMTargetLowering::addTypeForNEON method for details.
447     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
448     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
449     // FIXME: Create unittest.
450     // In another words, find a way when "copysign" appears in DAG with vector
451     // operands.
452     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
453     // FIXME: Code duplication: SETCC has custom operation action, see
454     // ARMTargetLowering::addTypeForNEON method for details.
455     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
456     // FIXME: Create unittest for FNEG and for FABS.
457     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
458     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
459     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
460     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
461     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
462     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
463     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
464     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
465     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
466     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
467     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
468     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
469     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
470     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
471     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
472     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
473     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
474     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
475     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
476
477     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
478     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
479     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
480     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
481     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
482     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
483     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
484     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
485     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
486     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
487     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
488     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
489     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
490     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
491     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
492
493     // Mark v2f32 intrinsics.
494     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
495     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
496     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
497     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
498     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
499     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
500     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
501     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
502     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
503     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
504     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
505     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
506     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
507     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
508     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
509
510     // Neon does not support some operations on v1i64 and v2i64 types.
511     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
512     // Custom handling for some quad-vector types to detect VMULL.
513     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
514     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
515     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
516     // Custom handling for some vector types to avoid expensive expansions
517     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
518     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
519     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
520     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
521     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
522     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
523     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
524     // a destination type that is wider than the source, and nor does
525     // it have a FP_TO_[SU]INT instruction with a narrower destination than
526     // source.
527     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
528     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
529     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
530     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
531
532     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
533     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
534
535     // NEON does not have single instruction CTPOP for vectors with element
536     // types wider than 8-bits.  However, custom lowering can leverage the
537     // v8i8/v16i8 vcnt instruction.
538     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
539     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
540     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
541     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
542
543     // NEON only has FMA instructions as of VFP4.
544     if (!Subtarget->hasVFP4()) {
545       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
546       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
547     }
548
549     setTargetDAGCombine(ISD::INTRINSIC_VOID);
550     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
551     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
552     setTargetDAGCombine(ISD::SHL);
553     setTargetDAGCombine(ISD::SRL);
554     setTargetDAGCombine(ISD::SRA);
555     setTargetDAGCombine(ISD::SIGN_EXTEND);
556     setTargetDAGCombine(ISD::ZERO_EXTEND);
557     setTargetDAGCombine(ISD::ANY_EXTEND);
558     setTargetDAGCombine(ISD::SELECT_CC);
559     setTargetDAGCombine(ISD::BUILD_VECTOR);
560     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
561     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
562     setTargetDAGCombine(ISD::STORE);
563     setTargetDAGCombine(ISD::FP_TO_SINT);
564     setTargetDAGCombine(ISD::FP_TO_UINT);
565     setTargetDAGCombine(ISD::FDIV);
566
567     // It is legal to extload from v4i8 to v4i16 or v4i32.
568     MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
569                   MVT::v4i16, MVT::v2i16,
570                   MVT::v2i32};
571     for (unsigned i = 0; i < 6; ++i) {
572       setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
573       setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
574       setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
575     }
576   }
577
578   // ARM and Thumb2 support UMLAL/SMLAL.
579   if (!Subtarget->isThumb1Only())
580     setTargetDAGCombine(ISD::ADDC);
581
582
583   computeRegisterProperties();
584
585   // ARM does not have f32 extending load.
586   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
587
588   // ARM does not have i1 sign extending load.
589   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
590
591   // ARM supports all 4 flavors of integer indexed load / store.
592   if (!Subtarget->isThumb1Only()) {
593     for (unsigned im = (unsigned)ISD::PRE_INC;
594          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
595       setIndexedLoadAction(im,  MVT::i1,  Legal);
596       setIndexedLoadAction(im,  MVT::i8,  Legal);
597       setIndexedLoadAction(im,  MVT::i16, Legal);
598       setIndexedLoadAction(im,  MVT::i32, Legal);
599       setIndexedStoreAction(im, MVT::i1,  Legal);
600       setIndexedStoreAction(im, MVT::i8,  Legal);
601       setIndexedStoreAction(im, MVT::i16, Legal);
602       setIndexedStoreAction(im, MVT::i32, Legal);
603     }
604   }
605
606   setOperationAction(ISD::SADDO, MVT::i32, Custom);
607   setOperationAction(ISD::UADDO, MVT::i32, Custom);
608   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
609   setOperationAction(ISD::USUBO, MVT::i32, Custom);
610
611   // i64 operation support.
612   setOperationAction(ISD::MUL,     MVT::i64, Expand);
613   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
614   if (Subtarget->isThumb1Only()) {
615     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
616     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
617   }
618   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
619       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
620     setOperationAction(ISD::MULHS, MVT::i32, Expand);
621
622   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
623   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
624   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
625   setOperationAction(ISD::SRL,       MVT::i64, Custom);
626   setOperationAction(ISD::SRA,       MVT::i64, Custom);
627
628   if (!Subtarget->isThumb1Only()) {
629     // FIXME: We should do this for Thumb1 as well.
630     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
631     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
632     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
633     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
634   }
635
636   // ARM does not have ROTL.
637   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
638   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
639   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
640   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
641     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
642
643   // These just redirect to CTTZ and CTLZ on ARM.
644   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
645   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
646
647   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
648
649   // Only ARMv6 has BSWAP.
650   if (!Subtarget->hasV6Ops())
651     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
652
653   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
654       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
655     // These are expanded into libcalls if the cpu doesn't have HW divider.
656     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
657     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
658   }
659
660   // FIXME: Also set divmod for SREM on EABI
661   setOperationAction(ISD::SREM,  MVT::i32, Expand);
662   setOperationAction(ISD::UREM,  MVT::i32, Expand);
663   // Register based DivRem for AEABI (RTABI 4.2)
664   if (Subtarget->isTargetAEABI()) {
665     setLibcallName(RTLIB::SDIVREM_I8,  "__aeabi_idivmod");
666     setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
667     setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
668     setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
669     setLibcallName(RTLIB::UDIVREM_I8,  "__aeabi_uidivmod");
670     setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
671     setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
672     setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
673
674     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
675     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
676     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
677     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
678     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
679     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
680     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
681     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
682
683     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
684     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
685   } else {
686     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
687     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
688   }
689
690   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
691   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
692   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
693   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
694   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
695
696   setOperationAction(ISD::TRAP, MVT::Other, Legal);
697
698   // Use the default implementation.
699   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
700   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
701   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
702   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
703   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
704   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
705
706   if (!Subtarget->isTargetMachO()) {
707     // Non-MachO platforms may return values in these registers via the
708     // personality function.
709     setExceptionPointerRegister(ARM::R0);
710     setExceptionSelectorRegister(ARM::R1);
711   }
712
713   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
714   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
715   // the default expansion.
716   if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
717     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
718     // to ldrex/strex loops already.
719     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
720
721     // On v8, we have particularly efficient implementations of atomic fences
722     // if they can be combined with nearby atomic loads and stores.
723     if (!Subtarget->hasV8Ops()) {
724       // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
725       setInsertFencesForAtomic(true);
726     }
727   } else {
728     // If there's anything we can use as a barrier, go through custom lowering
729     // for ATOMIC_FENCE.
730     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
731                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
732
733     // Set them all for expansion, which will force libcalls.
734     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
735     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
736     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
737     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
738     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
739     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
740     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
741     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
742     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
743     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
744     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
745     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
746     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
747     // Unordered/Monotonic case.
748     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
749     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
750   }
751
752   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
753
754   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
755   if (!Subtarget->hasV6Ops()) {
756     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
757     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
758   }
759   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
760
761   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
762       !Subtarget->isThumb1Only()) {
763     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
764     // iff target supports vfp2.
765     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
766     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
767   }
768
769   // We want to custom lower some of our intrinsics.
770   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
771   if (Subtarget->isTargetDarwin()) {
772     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
773     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
774     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
775   }
776
777   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
778   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
779   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
780   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
781   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
782   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
783   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
784   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
785   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
786
787   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
788   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
789   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
790   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
791   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
792
793   // We don't support sin/cos/fmod/copysign/pow
794   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
795   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
796   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
797   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
798   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
799   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
800   setOperationAction(ISD::FREM,      MVT::f64, Expand);
801   setOperationAction(ISD::FREM,      MVT::f32, Expand);
802   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
803       !Subtarget->isThumb1Only()) {
804     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
805     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
806   }
807   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
808   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
809
810   if (!Subtarget->hasVFP4()) {
811     setOperationAction(ISD::FMA, MVT::f64, Expand);
812     setOperationAction(ISD::FMA, MVT::f32, Expand);
813   }
814
815   // Various VFP goodness
816   if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
817     // int <-> fp are custom expanded into bit_convert + ARMISD ops.
818     if (Subtarget->hasVFP2()) {
819       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
820       setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
821       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
822       setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
823     }
824     // Special handling for half-precision FP.
825     if (!Subtarget->hasFP16()) {
826       setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
827       setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
828     }
829   }
830
831   // Combine sin / cos into one node or libcall if possible.
832   if (Subtarget->hasSinCos()) {
833     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
834     setLibcallName(RTLIB::SINCOS_F64, "sincos");
835     if (Subtarget->getTargetTriple().getOS() == Triple::IOS) {
836       // For iOS, we don't want to the normal expansion of a libcall to
837       // sincos. We want to issue a libcall to __sincos_stret.
838       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
839       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
840     }
841   }
842
843   // We have target-specific dag combine patterns for the following nodes:
844   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
845   setTargetDAGCombine(ISD::ADD);
846   setTargetDAGCombine(ISD::SUB);
847   setTargetDAGCombine(ISD::MUL);
848   setTargetDAGCombine(ISD::AND);
849   setTargetDAGCombine(ISD::OR);
850   setTargetDAGCombine(ISD::XOR);
851
852   if (Subtarget->hasV6Ops())
853     setTargetDAGCombine(ISD::SRL);
854
855   setStackPointerRegisterToSaveRestore(ARM::SP);
856
857   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
858       !Subtarget->hasVFP2())
859     setSchedulingPreference(Sched::RegPressure);
860   else
861     setSchedulingPreference(Sched::Hybrid);
862
863   //// temporary - rewrite interface to use type
864   MaxStoresPerMemset = 8;
865   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
866   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
867   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
868   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
869   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
870
871   // On ARM arguments smaller than 4 bytes are extended, so all arguments
872   // are at least 4 bytes aligned.
873   setMinStackArgumentAlignment(4);
874
875   // Prefer likely predicted branches to selects on out-of-order cores.
876   PredictableSelectIsExpensive = Subtarget->isLikeA9();
877
878   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
879 }
880
881 // FIXME: It might make sense to define the representative register class as the
882 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
883 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
884 // SPR's representative would be DPR_VFP2. This should work well if register
885 // pressure tracking were modified such that a register use would increment the
886 // pressure of the register class's representative and all of it's super
887 // classes' representatives transitively. We have not implemented this because
888 // of the difficulty prior to coalescing of modeling operand register classes
889 // due to the common occurrence of cross class copies and subregister insertions
890 // and extractions.
891 std::pair<const TargetRegisterClass*, uint8_t>
892 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
893   const TargetRegisterClass *RRC = nullptr;
894   uint8_t Cost = 1;
895   switch (VT.SimpleTy) {
896   default:
897     return TargetLowering::findRepresentativeClass(VT);
898   // Use DPR as representative register class for all floating point
899   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
900   // the cost is 1 for both f32 and f64.
901   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
902   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
903     RRC = &ARM::DPRRegClass;
904     // When NEON is used for SP, only half of the register file is available
905     // because operations that define both SP and DP results will be constrained
906     // to the VFP2 class (D0-D15). We currently model this constraint prior to
907     // coalescing by double-counting the SP regs. See the FIXME above.
908     if (Subtarget->useNEONForSinglePrecisionFP())
909       Cost = 2;
910     break;
911   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
912   case MVT::v4f32: case MVT::v2f64:
913     RRC = &ARM::DPRRegClass;
914     Cost = 2;
915     break;
916   case MVT::v4i64:
917     RRC = &ARM::DPRRegClass;
918     Cost = 4;
919     break;
920   case MVT::v8i64:
921     RRC = &ARM::DPRRegClass;
922     Cost = 8;
923     break;
924   }
925   return std::make_pair(RRC, Cost);
926 }
927
928 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
929   switch (Opcode) {
930   default: return nullptr;
931   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
932   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
933   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
934   case ARMISD::CALL:          return "ARMISD::CALL";
935   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
936   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
937   case ARMISD::tCALL:         return "ARMISD::tCALL";
938   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
939   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
940   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
941   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
942   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
943   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
944   case ARMISD::CMP:           return "ARMISD::CMP";
945   case ARMISD::CMN:           return "ARMISD::CMN";
946   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
947   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
948   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
949   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
950   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
951
952   case ARMISD::CMOV:          return "ARMISD::CMOV";
953
954   case ARMISD::RBIT:          return "ARMISD::RBIT";
955
956   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
957   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
958   case ARMISD::SITOF:         return "ARMISD::SITOF";
959   case ARMISD::UITOF:         return "ARMISD::UITOF";
960
961   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
962   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
963   case ARMISD::RRX:           return "ARMISD::RRX";
964
965   case ARMISD::ADDC:          return "ARMISD::ADDC";
966   case ARMISD::ADDE:          return "ARMISD::ADDE";
967   case ARMISD::SUBC:          return "ARMISD::SUBC";
968   case ARMISD::SUBE:          return "ARMISD::SUBE";
969
970   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
971   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
972
973   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
974   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
975
976   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
977
978   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
979
980   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
981
982   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
983
984   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
985
986   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
987   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
988   case ARMISD::VCGE:          return "ARMISD::VCGE";
989   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
990   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
991   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
992   case ARMISD::VCGT:          return "ARMISD::VCGT";
993   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
994   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
995   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
996   case ARMISD::VTST:          return "ARMISD::VTST";
997
998   case ARMISD::VSHL:          return "ARMISD::VSHL";
999   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1000   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1001   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1002   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1003   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1004   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1005   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1006   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1007   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1008   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1009   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1010   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1011   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1012   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1013   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1014   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1015   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1016   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1017   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1018   case ARMISD::VDUP:          return "ARMISD::VDUP";
1019   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1020   case ARMISD::VEXT:          return "ARMISD::VEXT";
1021   case ARMISD::VREV64:        return "ARMISD::VREV64";
1022   case ARMISD::VREV32:        return "ARMISD::VREV32";
1023   case ARMISD::VREV16:        return "ARMISD::VREV16";
1024   case ARMISD::VZIP:          return "ARMISD::VZIP";
1025   case ARMISD::VUZP:          return "ARMISD::VUZP";
1026   case ARMISD::VTRN:          return "ARMISD::VTRN";
1027   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1028   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1029   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1030   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1031   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1032   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1033   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1034   case ARMISD::FMAX:          return "ARMISD::FMAX";
1035   case ARMISD::FMIN:          return "ARMISD::FMIN";
1036   case ARMISD::VMAXNM:        return "ARMISD::VMAX";
1037   case ARMISD::VMINNM:        return "ARMISD::VMIN";
1038   case ARMISD::BFI:           return "ARMISD::BFI";
1039   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1040   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1041   case ARMISD::VBSL:          return "ARMISD::VBSL";
1042   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1043   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1044   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1045   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1046   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1047   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1048   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1049   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1050   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1051   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1052   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1053   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1054   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1055   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1056   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1057   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1058   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1059   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1060   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1061   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1062   }
1063 }
1064
1065 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1066   if (!VT.isVector()) return getPointerTy();
1067   return VT.changeVectorElementTypeToInteger();
1068 }
1069
1070 /// getRegClassFor - Return the register class that should be used for the
1071 /// specified value type.
1072 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1073   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1074   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1075   // load / store 4 to 8 consecutive D registers.
1076   if (Subtarget->hasNEON()) {
1077     if (VT == MVT::v4i64)
1078       return &ARM::QQPRRegClass;
1079     if (VT == MVT::v8i64)
1080       return &ARM::QQQQPRRegClass;
1081   }
1082   return TargetLowering::getRegClassFor(VT);
1083 }
1084
1085 // Create a fast isel object.
1086 FastISel *
1087 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1088                                   const TargetLibraryInfo *libInfo) const {
1089   return ARM::createFastISel(funcInfo, libInfo);
1090 }
1091
1092 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1093 /// be used for loads / stores from the global.
1094 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1095   return (Subtarget->isThumb1Only() ? 127 : 4095);
1096 }
1097
1098 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1099   unsigned NumVals = N->getNumValues();
1100   if (!NumVals)
1101     return Sched::RegPressure;
1102
1103   for (unsigned i = 0; i != NumVals; ++i) {
1104     EVT VT = N->getValueType(i);
1105     if (VT == MVT::Glue || VT == MVT::Other)
1106       continue;
1107     if (VT.isFloatingPoint() || VT.isVector())
1108       return Sched::ILP;
1109   }
1110
1111   if (!N->isMachineOpcode())
1112     return Sched::RegPressure;
1113
1114   // Load are scheduled for latency even if there instruction itinerary
1115   // is not available.
1116   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1117   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1118
1119   if (MCID.getNumDefs() == 0)
1120     return Sched::RegPressure;
1121   if (!Itins->isEmpty() &&
1122       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1123     return Sched::ILP;
1124
1125   return Sched::RegPressure;
1126 }
1127
1128 //===----------------------------------------------------------------------===//
1129 // Lowering Code
1130 //===----------------------------------------------------------------------===//
1131
1132 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1133 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1134   switch (CC) {
1135   default: llvm_unreachable("Unknown condition code!");
1136   case ISD::SETNE:  return ARMCC::NE;
1137   case ISD::SETEQ:  return ARMCC::EQ;
1138   case ISD::SETGT:  return ARMCC::GT;
1139   case ISD::SETGE:  return ARMCC::GE;
1140   case ISD::SETLT:  return ARMCC::LT;
1141   case ISD::SETLE:  return ARMCC::LE;
1142   case ISD::SETUGT: return ARMCC::HI;
1143   case ISD::SETUGE: return ARMCC::HS;
1144   case ISD::SETULT: return ARMCC::LO;
1145   case ISD::SETULE: return ARMCC::LS;
1146   }
1147 }
1148
1149 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1150 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1151                         ARMCC::CondCodes &CondCode2) {
1152   CondCode2 = ARMCC::AL;
1153   switch (CC) {
1154   default: llvm_unreachable("Unknown FP condition!");
1155   case ISD::SETEQ:
1156   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1157   case ISD::SETGT:
1158   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1159   case ISD::SETGE:
1160   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1161   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1162   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1163   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1164   case ISD::SETO:   CondCode = ARMCC::VC; break;
1165   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1166   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1167   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1168   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1169   case ISD::SETLT:
1170   case ISD::SETULT: CondCode = ARMCC::LT; break;
1171   case ISD::SETLE:
1172   case ISD::SETULE: CondCode = ARMCC::LE; break;
1173   case ISD::SETNE:
1174   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1175   }
1176 }
1177
1178 //===----------------------------------------------------------------------===//
1179 //                      Calling Convention Implementation
1180 //===----------------------------------------------------------------------===//
1181
1182 #include "ARMGenCallingConv.inc"
1183
1184 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1185 /// account presence of floating point hardware and calling convention
1186 /// limitations, such as support for variadic functions.
1187 CallingConv::ID
1188 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1189                                            bool isVarArg) const {
1190   switch (CC) {
1191   default:
1192     llvm_unreachable("Unsupported calling convention");
1193   case CallingConv::ARM_AAPCS:
1194   case CallingConv::ARM_APCS:
1195   case CallingConv::GHC:
1196     return CC;
1197   case CallingConv::ARM_AAPCS_VFP:
1198     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1199   case CallingConv::C:
1200     if (!Subtarget->isAAPCS_ABI())
1201       return CallingConv::ARM_APCS;
1202     else if (Subtarget->hasVFP2() &&
1203              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1204              !isVarArg)
1205       return CallingConv::ARM_AAPCS_VFP;
1206     else
1207       return CallingConv::ARM_AAPCS;
1208   case CallingConv::Fast:
1209     if (!Subtarget->isAAPCS_ABI()) {
1210       if (Subtarget->hasVFP2() && !isVarArg)
1211         return CallingConv::Fast;
1212       return CallingConv::ARM_APCS;
1213     } else if (Subtarget->hasVFP2() && !isVarArg)
1214       return CallingConv::ARM_AAPCS_VFP;
1215     else
1216       return CallingConv::ARM_AAPCS;
1217   }
1218 }
1219
1220 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1221 /// CallingConvention.
1222 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1223                                                  bool Return,
1224                                                  bool isVarArg) const {
1225   switch (getEffectiveCallingConv(CC, isVarArg)) {
1226   default:
1227     llvm_unreachable("Unsupported calling convention");
1228   case CallingConv::ARM_APCS:
1229     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1230   case CallingConv::ARM_AAPCS:
1231     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1232   case CallingConv::ARM_AAPCS_VFP:
1233     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1234   case CallingConv::Fast:
1235     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1236   case CallingConv::GHC:
1237     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1238   }
1239 }
1240
1241 /// LowerCallResult - Lower the result values of a call into the
1242 /// appropriate copies out of appropriate physical registers.
1243 SDValue
1244 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1245                                    CallingConv::ID CallConv, bool isVarArg,
1246                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1247                                    SDLoc dl, SelectionDAG &DAG,
1248                                    SmallVectorImpl<SDValue> &InVals,
1249                                    bool isThisReturn, SDValue ThisVal) const {
1250
1251   // Assign locations to each value returned by this call.
1252   SmallVector<CCValAssign, 16> RVLocs;
1253   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1254                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1255   CCInfo.AnalyzeCallResult(Ins,
1256                            CCAssignFnForNode(CallConv, /* Return*/ true,
1257                                              isVarArg));
1258
1259   // Copy all of the result registers out of their specified physreg.
1260   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1261     CCValAssign VA = RVLocs[i];
1262
1263     // Pass 'this' value directly from the argument to return value, to avoid
1264     // reg unit interference
1265     if (i == 0 && isThisReturn) {
1266       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1267              "unexpected return calling convention register assignment");
1268       InVals.push_back(ThisVal);
1269       continue;
1270     }
1271
1272     SDValue Val;
1273     if (VA.needsCustom()) {
1274       // Handle f64 or half of a v2f64.
1275       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1276                                       InFlag);
1277       Chain = Lo.getValue(1);
1278       InFlag = Lo.getValue(2);
1279       VA = RVLocs[++i]; // skip ahead to next loc
1280       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1281                                       InFlag);
1282       Chain = Hi.getValue(1);
1283       InFlag = Hi.getValue(2);
1284       if (!Subtarget->isLittle())
1285         std::swap (Lo, Hi);
1286       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1287
1288       if (VA.getLocVT() == MVT::v2f64) {
1289         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1290         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1291                           DAG.getConstant(0, MVT::i32));
1292
1293         VA = RVLocs[++i]; // skip ahead to next loc
1294         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1295         Chain = Lo.getValue(1);
1296         InFlag = Lo.getValue(2);
1297         VA = RVLocs[++i]; // skip ahead to next loc
1298         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1299         Chain = Hi.getValue(1);
1300         InFlag = Hi.getValue(2);
1301         if (!Subtarget->isLittle())
1302           std::swap (Lo, Hi);
1303         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1304         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1305                           DAG.getConstant(1, MVT::i32));
1306       }
1307     } else {
1308       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1309                                InFlag);
1310       Chain = Val.getValue(1);
1311       InFlag = Val.getValue(2);
1312     }
1313
1314     switch (VA.getLocInfo()) {
1315     default: llvm_unreachable("Unknown loc info!");
1316     case CCValAssign::Full: break;
1317     case CCValAssign::BCvt:
1318       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1319       break;
1320     }
1321
1322     InVals.push_back(Val);
1323   }
1324
1325   return Chain;
1326 }
1327
1328 /// LowerMemOpCallTo - Store the argument to the stack.
1329 SDValue
1330 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1331                                     SDValue StackPtr, SDValue Arg,
1332                                     SDLoc dl, SelectionDAG &DAG,
1333                                     const CCValAssign &VA,
1334                                     ISD::ArgFlagsTy Flags) const {
1335   unsigned LocMemOffset = VA.getLocMemOffset();
1336   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1337   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1338   return DAG.getStore(Chain, dl, Arg, PtrOff,
1339                       MachinePointerInfo::getStack(LocMemOffset),
1340                       false, false, 0);
1341 }
1342
1343 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1344                                          SDValue Chain, SDValue &Arg,
1345                                          RegsToPassVector &RegsToPass,
1346                                          CCValAssign &VA, CCValAssign &NextVA,
1347                                          SDValue &StackPtr,
1348                                          SmallVectorImpl<SDValue> &MemOpChains,
1349                                          ISD::ArgFlagsTy Flags) const {
1350
1351   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1352                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1353   unsigned id = Subtarget->isLittle() ? 0 : 1;
1354   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1355
1356   if (NextVA.isRegLoc())
1357     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1358   else {
1359     assert(NextVA.isMemLoc());
1360     if (!StackPtr.getNode())
1361       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1362
1363     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1364                                            dl, DAG, NextVA,
1365                                            Flags));
1366   }
1367 }
1368
1369 /// LowerCall - Lowering a call into a callseq_start <-
1370 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1371 /// nodes.
1372 SDValue
1373 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1374                              SmallVectorImpl<SDValue> &InVals) const {
1375   SelectionDAG &DAG                     = CLI.DAG;
1376   SDLoc &dl                          = CLI.DL;
1377   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1378   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1379   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1380   SDValue Chain                         = CLI.Chain;
1381   SDValue Callee                        = CLI.Callee;
1382   bool &isTailCall                      = CLI.IsTailCall;
1383   CallingConv::ID CallConv              = CLI.CallConv;
1384   bool doesNotRet                       = CLI.DoesNotReturn;
1385   bool isVarArg                         = CLI.IsVarArg;
1386
1387   MachineFunction &MF = DAG.getMachineFunction();
1388   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1389   bool isThisReturn   = false;
1390   bool isSibCall      = false;
1391
1392   // Disable tail calls if they're not supported.
1393   if (!Subtarget->supportsTailCall() || MF.getTarget().Options.DisableTailCalls)
1394     isTailCall = false;
1395
1396   if (isTailCall) {
1397     // Check if it's really possible to do a tail call.
1398     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1399                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1400                                                    Outs, OutVals, Ins, DAG);
1401     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1402       report_fatal_error("failed to perform tail call elimination on a call "
1403                          "site marked musttail");
1404     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1405     // detected sibcalls.
1406     if (isTailCall) {
1407       ++NumTailCalls;
1408       isSibCall = true;
1409     }
1410   }
1411
1412   // Analyze operands of the call, assigning locations to each operand.
1413   SmallVector<CCValAssign, 16> ArgLocs;
1414   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1415                  getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1416   CCInfo.AnalyzeCallOperands(Outs,
1417                              CCAssignFnForNode(CallConv, /* Return*/ false,
1418                                                isVarArg));
1419
1420   // Get a count of how many bytes are to be pushed on the stack.
1421   unsigned NumBytes = CCInfo.getNextStackOffset();
1422
1423   // For tail calls, memory operands are available in our caller's stack.
1424   if (isSibCall)
1425     NumBytes = 0;
1426
1427   // Adjust the stack pointer for the new arguments...
1428   // These operations are automatically eliminated by the prolog/epilog pass
1429   if (!isSibCall)
1430     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1431                                  dl);
1432
1433   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1434
1435   RegsToPassVector RegsToPass;
1436   SmallVector<SDValue, 8> MemOpChains;
1437
1438   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1439   // of tail call optimization, arguments are handled later.
1440   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1441        i != e;
1442        ++i, ++realArgIdx) {
1443     CCValAssign &VA = ArgLocs[i];
1444     SDValue Arg = OutVals[realArgIdx];
1445     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1446     bool isByVal = Flags.isByVal();
1447
1448     // Promote the value if needed.
1449     switch (VA.getLocInfo()) {
1450     default: llvm_unreachable("Unknown loc info!");
1451     case CCValAssign::Full: break;
1452     case CCValAssign::SExt:
1453       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1454       break;
1455     case CCValAssign::ZExt:
1456       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1457       break;
1458     case CCValAssign::AExt:
1459       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1460       break;
1461     case CCValAssign::BCvt:
1462       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1463       break;
1464     }
1465
1466     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1467     if (VA.needsCustom()) {
1468       if (VA.getLocVT() == MVT::v2f64) {
1469         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1470                                   DAG.getConstant(0, MVT::i32));
1471         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1472                                   DAG.getConstant(1, MVT::i32));
1473
1474         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1475                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1476
1477         VA = ArgLocs[++i]; // skip ahead to next loc
1478         if (VA.isRegLoc()) {
1479           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1480                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1481         } else {
1482           assert(VA.isMemLoc());
1483
1484           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1485                                                  dl, DAG, VA, Flags));
1486         }
1487       } else {
1488         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1489                          StackPtr, MemOpChains, Flags);
1490       }
1491     } else if (VA.isRegLoc()) {
1492       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1493         assert(VA.getLocVT() == MVT::i32 &&
1494                "unexpected calling convention register assignment");
1495         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1496                "unexpected use of 'returned'");
1497         isThisReturn = true;
1498       }
1499       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1500     } else if (isByVal) {
1501       assert(VA.isMemLoc());
1502       unsigned offset = 0;
1503
1504       // True if this byval aggregate will be split between registers
1505       // and memory.
1506       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1507       unsigned CurByValIdx = CCInfo.getInRegsParamsProceed();
1508
1509       if (CurByValIdx < ByValArgsCount) {
1510
1511         unsigned RegBegin, RegEnd;
1512         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1513
1514         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1515         unsigned int i, j;
1516         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1517           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1518           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1519           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1520                                      MachinePointerInfo(),
1521                                      false, false, false,
1522                                      DAG.InferPtrAlignment(AddArg));
1523           MemOpChains.push_back(Load.getValue(1));
1524           RegsToPass.push_back(std::make_pair(j, Load));
1525         }
1526
1527         // If parameter size outsides register area, "offset" value
1528         // helps us to calculate stack slot for remained part properly.
1529         offset = RegEnd - RegBegin;
1530
1531         CCInfo.nextInRegsParam();
1532       }
1533
1534       if (Flags.getByValSize() > 4*offset) {
1535         unsigned LocMemOffset = VA.getLocMemOffset();
1536         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1537         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1538                                   StkPtrOff);
1539         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1540         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1541         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1542                                            MVT::i32);
1543         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1544
1545         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1546         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1547         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1548                                           Ops));
1549       }
1550     } else if (!isSibCall) {
1551       assert(VA.isMemLoc());
1552
1553       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1554                                              dl, DAG, VA, Flags));
1555     }
1556   }
1557
1558   if (!MemOpChains.empty())
1559     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1560
1561   // Build a sequence of copy-to-reg nodes chained together with token chain
1562   // and flag operands which copy the outgoing args into the appropriate regs.
1563   SDValue InFlag;
1564   // Tail call byval lowering might overwrite argument registers so in case of
1565   // tail call optimization the copies to registers are lowered later.
1566   if (!isTailCall)
1567     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1568       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1569                                RegsToPass[i].second, InFlag);
1570       InFlag = Chain.getValue(1);
1571     }
1572
1573   // For tail calls lower the arguments to the 'real' stack slot.
1574   if (isTailCall) {
1575     // Force all the incoming stack arguments to be loaded from the stack
1576     // before any new outgoing arguments are stored to the stack, because the
1577     // outgoing stack slots may alias the incoming argument stack slots, and
1578     // the alias isn't otherwise explicit. This is slightly more conservative
1579     // than necessary, because it means that each store effectively depends
1580     // on every argument instead of just those arguments it would clobber.
1581
1582     // Do not flag preceding copytoreg stuff together with the following stuff.
1583     InFlag = SDValue();
1584     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1585       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1586                                RegsToPass[i].second, InFlag);
1587       InFlag = Chain.getValue(1);
1588     }
1589     InFlag = SDValue();
1590   }
1591
1592   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1593   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1594   // node so that legalize doesn't hack it.
1595   bool isDirect = false;
1596   bool isARMFunc = false;
1597   bool isLocalARMFunc = false;
1598   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1599
1600   if (EnableARMLongCalls) {
1601     assert (getTargetMachine().getRelocationModel() == Reloc::Static
1602             && "long-calls with non-static relocation model!");
1603     // Handle a global address or an external symbol. If it's not one of
1604     // those, the target's already in a register, so we don't need to do
1605     // anything extra.
1606     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1607       const GlobalValue *GV = G->getGlobal();
1608       // Create a constant pool entry for the callee address
1609       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1610       ARMConstantPoolValue *CPV =
1611         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1612
1613       // Get the address of the callee into a register
1614       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1615       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1616       Callee = DAG.getLoad(getPointerTy(), dl,
1617                            DAG.getEntryNode(), CPAddr,
1618                            MachinePointerInfo::getConstantPool(),
1619                            false, false, false, 0);
1620     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1621       const char *Sym = S->getSymbol();
1622
1623       // Create a constant pool entry for the callee address
1624       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1625       ARMConstantPoolValue *CPV =
1626         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1627                                       ARMPCLabelIndex, 0);
1628       // Get the address of the callee into a register
1629       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1630       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1631       Callee = DAG.getLoad(getPointerTy(), dl,
1632                            DAG.getEntryNode(), CPAddr,
1633                            MachinePointerInfo::getConstantPool(),
1634                            false, false, false, 0);
1635     }
1636   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1637     const GlobalValue *GV = G->getGlobal();
1638     isDirect = true;
1639     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1640     bool isStub = (isExt && Subtarget->isTargetMachO()) &&
1641                    getTargetMachine().getRelocationModel() != Reloc::Static;
1642     isARMFunc = !Subtarget->isThumb() || isStub;
1643     // ARM call to a local ARM function is predicable.
1644     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1645     // tBX takes a register source operand.
1646     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1647       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1648       Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1649                            DAG.getTargetGlobalAddress(GV, dl, getPointerTy()));
1650     } else {
1651       // On ELF targets for PIC code, direct calls should go through the PLT
1652       unsigned OpFlags = 0;
1653       if (Subtarget->isTargetELF() &&
1654           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1655         OpFlags = ARMII::MO_PLT;
1656       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1657     }
1658   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1659     isDirect = true;
1660     bool isStub = Subtarget->isTargetMachO() &&
1661                   getTargetMachine().getRelocationModel() != Reloc::Static;
1662     isARMFunc = !Subtarget->isThumb() || isStub;
1663     // tBX takes a register source operand.
1664     const char *Sym = S->getSymbol();
1665     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1666       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1667       ARMConstantPoolValue *CPV =
1668         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1669                                       ARMPCLabelIndex, 4);
1670       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1671       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1672       Callee = DAG.getLoad(getPointerTy(), dl,
1673                            DAG.getEntryNode(), CPAddr,
1674                            MachinePointerInfo::getConstantPool(),
1675                            false, false, false, 0);
1676       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1677       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1678                            getPointerTy(), Callee, PICLabel);
1679     } else {
1680       unsigned OpFlags = 0;
1681       // On ELF targets for PIC code, direct calls should go through the PLT
1682       if (Subtarget->isTargetELF() &&
1683                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1684         OpFlags = ARMII::MO_PLT;
1685       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1686     }
1687   }
1688
1689   // FIXME: handle tail calls differently.
1690   unsigned CallOpc;
1691   bool HasMinSizeAttr = Subtarget->isMinSize();
1692   if (Subtarget->isThumb()) {
1693     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1694       CallOpc = ARMISD::CALL_NOLINK;
1695     else
1696       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1697   } else {
1698     if (!isDirect && !Subtarget->hasV5TOps())
1699       CallOpc = ARMISD::CALL_NOLINK;
1700     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1701                // Emit regular call when code size is the priority
1702                !HasMinSizeAttr)
1703       // "mov lr, pc; b _foo" to avoid confusing the RSP
1704       CallOpc = ARMISD::CALL_NOLINK;
1705     else
1706       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1707   }
1708
1709   std::vector<SDValue> Ops;
1710   Ops.push_back(Chain);
1711   Ops.push_back(Callee);
1712
1713   // Add argument registers to the end of the list so that they are known live
1714   // into the call.
1715   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1716     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1717                                   RegsToPass[i].second.getValueType()));
1718
1719   // Add a register mask operand representing the call-preserved registers.
1720   if (!isTailCall) {
1721     const uint32_t *Mask;
1722     const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1723     const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1724     if (isThisReturn) {
1725       // For 'this' returns, use the R0-preserving mask if applicable
1726       Mask = ARI->getThisReturnPreservedMask(CallConv);
1727       if (!Mask) {
1728         // Set isThisReturn to false if the calling convention is not one that
1729         // allows 'returned' to be modeled in this way, so LowerCallResult does
1730         // not try to pass 'this' straight through
1731         isThisReturn = false;
1732         Mask = ARI->getCallPreservedMask(CallConv);
1733       }
1734     } else
1735       Mask = ARI->getCallPreservedMask(CallConv);
1736
1737     assert(Mask && "Missing call preserved mask for calling convention");
1738     Ops.push_back(DAG.getRegisterMask(Mask));
1739   }
1740
1741   if (InFlag.getNode())
1742     Ops.push_back(InFlag);
1743
1744   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1745   if (isTailCall)
1746     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1747
1748   // Returns a chain and a flag for retval copy to use.
1749   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1750   InFlag = Chain.getValue(1);
1751
1752   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1753                              DAG.getIntPtrConstant(0, true), InFlag, dl);
1754   if (!Ins.empty())
1755     InFlag = Chain.getValue(1);
1756
1757   // Handle result values, copying them out of physregs into vregs that we
1758   // return.
1759   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1760                          InVals, isThisReturn,
1761                          isThisReturn ? OutVals[0] : SDValue());
1762 }
1763
1764 /// HandleByVal - Every parameter *after* a byval parameter is passed
1765 /// on the stack.  Remember the next parameter register to allocate,
1766 /// and then confiscate the rest of the parameter registers to insure
1767 /// this.
1768 void
1769 ARMTargetLowering::HandleByVal(
1770     CCState *State, unsigned &size, unsigned Align) const {
1771   unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1772   assert((State->getCallOrPrologue() == Prologue ||
1773           State->getCallOrPrologue() == Call) &&
1774          "unhandled ParmContext");
1775
1776   if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1777     if (Subtarget->isAAPCS_ABI() && Align > 4) {
1778       unsigned AlignInRegs = Align / 4;
1779       unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1780       for (unsigned i = 0; i < Waste; ++i)
1781         reg = State->AllocateReg(GPRArgRegs, 4);
1782     }
1783     if (reg != 0) {
1784       unsigned excess = 4 * (ARM::R4 - reg);
1785
1786       // Special case when NSAA != SP and parameter size greater than size of
1787       // all remained GPR regs. In that case we can't split parameter, we must
1788       // send it to stack. We also must set NCRN to R4, so waste all
1789       // remained registers.
1790       const unsigned NSAAOffset = State->getNextStackOffset();
1791       if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1792         while (State->AllocateReg(GPRArgRegs, 4))
1793           ;
1794         return;
1795       }
1796
1797       // First register for byval parameter is the first register that wasn't
1798       // allocated before this method call, so it would be "reg".
1799       // If parameter is small enough to be saved in range [reg, r4), then
1800       // the end (first after last) register would be reg + param-size-in-regs,
1801       // else parameter would be splitted between registers and stack,
1802       // end register would be r4 in this case.
1803       unsigned ByValRegBegin = reg;
1804       unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1805       State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1806       // Note, first register is allocated in the beginning of function already,
1807       // allocate remained amount of registers we need.
1808       for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1809         State->AllocateReg(GPRArgRegs, 4);
1810       // A byval parameter that is split between registers and memory needs its
1811       // size truncated here.
1812       // In the case where the entire structure fits in registers, we set the
1813       // size in memory to zero.
1814       if (size < excess)
1815         size = 0;
1816       else
1817         size -= excess;
1818     }
1819   }
1820 }
1821
1822 /// MatchingStackOffset - Return true if the given stack call argument is
1823 /// already available in the same position (relatively) of the caller's
1824 /// incoming argument stack.
1825 static
1826 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1827                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1828                          const TargetInstrInfo *TII) {
1829   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1830   int FI = INT_MAX;
1831   if (Arg.getOpcode() == ISD::CopyFromReg) {
1832     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1833     if (!TargetRegisterInfo::isVirtualRegister(VR))
1834       return false;
1835     MachineInstr *Def = MRI->getVRegDef(VR);
1836     if (!Def)
1837       return false;
1838     if (!Flags.isByVal()) {
1839       if (!TII->isLoadFromStackSlot(Def, FI))
1840         return false;
1841     } else {
1842       return false;
1843     }
1844   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1845     if (Flags.isByVal())
1846       // ByVal argument is passed in as a pointer but it's now being
1847       // dereferenced. e.g.
1848       // define @foo(%struct.X* %A) {
1849       //   tail call @bar(%struct.X* byval %A)
1850       // }
1851       return false;
1852     SDValue Ptr = Ld->getBasePtr();
1853     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1854     if (!FINode)
1855       return false;
1856     FI = FINode->getIndex();
1857   } else
1858     return false;
1859
1860   assert(FI != INT_MAX);
1861   if (!MFI->isFixedObjectIndex(FI))
1862     return false;
1863   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1864 }
1865
1866 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1867 /// for tail call optimization. Targets which want to do tail call
1868 /// optimization should implement this function.
1869 bool
1870 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1871                                                      CallingConv::ID CalleeCC,
1872                                                      bool isVarArg,
1873                                                      bool isCalleeStructRet,
1874                                                      bool isCallerStructRet,
1875                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1876                                     const SmallVectorImpl<SDValue> &OutVals,
1877                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1878                                                      SelectionDAG& DAG) const {
1879   const Function *CallerF = DAG.getMachineFunction().getFunction();
1880   CallingConv::ID CallerCC = CallerF->getCallingConv();
1881   bool CCMatch = CallerCC == CalleeCC;
1882
1883   // Look for obvious safe cases to perform tail call optimization that do not
1884   // require ABI changes. This is what gcc calls sibcall.
1885
1886   // Do not sibcall optimize vararg calls unless the call site is not passing
1887   // any arguments.
1888   if (isVarArg && !Outs.empty())
1889     return false;
1890
1891   // Exception-handling functions need a special set of instructions to indicate
1892   // a return to the hardware. Tail-calling another function would probably
1893   // break this.
1894   if (CallerF->hasFnAttribute("interrupt"))
1895     return false;
1896
1897   // Also avoid sibcall optimization if either caller or callee uses struct
1898   // return semantics.
1899   if (isCalleeStructRet || isCallerStructRet)
1900     return false;
1901
1902   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1903   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1904   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1905   // support in the assembler and linker to be used. This would need to be
1906   // fixed to fully support tail calls in Thumb1.
1907   //
1908   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1909   // LR.  This means if we need to reload LR, it takes an extra instructions,
1910   // which outweighs the value of the tail call; but here we don't know yet
1911   // whether LR is going to be used.  Probably the right approach is to
1912   // generate the tail call here and turn it back into CALL/RET in
1913   // emitEpilogue if LR is used.
1914
1915   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1916   // but we need to make sure there are enough registers; the only valid
1917   // registers are the 4 used for parameters.  We don't currently do this
1918   // case.
1919   if (Subtarget->isThumb1Only())
1920     return false;
1921
1922   // If the calling conventions do not match, then we'd better make sure the
1923   // results are returned in the same way as what the caller expects.
1924   if (!CCMatch) {
1925     SmallVector<CCValAssign, 16> RVLocs1;
1926     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1927                        getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1928     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1929
1930     SmallVector<CCValAssign, 16> RVLocs2;
1931     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1932                        getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1933     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1934
1935     if (RVLocs1.size() != RVLocs2.size())
1936       return false;
1937     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1938       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1939         return false;
1940       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1941         return false;
1942       if (RVLocs1[i].isRegLoc()) {
1943         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1944           return false;
1945       } else {
1946         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1947           return false;
1948       }
1949     }
1950   }
1951
1952   // If Caller's vararg or byval argument has been split between registers and
1953   // stack, do not perform tail call, since part of the argument is in caller's
1954   // local frame.
1955   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
1956                                       getInfo<ARMFunctionInfo>();
1957   if (AFI_Caller->getArgRegsSaveSize())
1958     return false;
1959
1960   // If the callee takes no arguments then go on to check the results of the
1961   // call.
1962   if (!Outs.empty()) {
1963     // Check if stack adjustment is needed. For now, do not do this if any
1964     // argument is passed on the stack.
1965     SmallVector<CCValAssign, 16> ArgLocs;
1966     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
1967                       getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1968     CCInfo.AnalyzeCallOperands(Outs,
1969                                CCAssignFnForNode(CalleeCC, false, isVarArg));
1970     if (CCInfo.getNextStackOffset()) {
1971       MachineFunction &MF = DAG.getMachineFunction();
1972
1973       // Check if the arguments are already laid out in the right way as
1974       // the caller's fixed stack objects.
1975       MachineFrameInfo *MFI = MF.getFrameInfo();
1976       const MachineRegisterInfo *MRI = &MF.getRegInfo();
1977       const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1978       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1979            i != e;
1980            ++i, ++realArgIdx) {
1981         CCValAssign &VA = ArgLocs[i];
1982         EVT RegVT = VA.getLocVT();
1983         SDValue Arg = OutVals[realArgIdx];
1984         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1985         if (VA.getLocInfo() == CCValAssign::Indirect)
1986           return false;
1987         if (VA.needsCustom()) {
1988           // f64 and vector types are split into multiple registers or
1989           // register/stack-slot combinations.  The types will not match
1990           // the registers; give up on memory f64 refs until we figure
1991           // out what to do about this.
1992           if (!VA.isRegLoc())
1993             return false;
1994           if (!ArgLocs[++i].isRegLoc())
1995             return false;
1996           if (RegVT == MVT::v2f64) {
1997             if (!ArgLocs[++i].isRegLoc())
1998               return false;
1999             if (!ArgLocs[++i].isRegLoc())
2000               return false;
2001           }
2002         } else if (!VA.isRegLoc()) {
2003           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2004                                    MFI, MRI, TII))
2005             return false;
2006         }
2007       }
2008     }
2009   }
2010
2011   return true;
2012 }
2013
2014 bool
2015 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2016                                   MachineFunction &MF, bool isVarArg,
2017                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2018                                   LLVMContext &Context) const {
2019   SmallVector<CCValAssign, 16> RVLocs;
2020   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
2021   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2022                                                     isVarArg));
2023 }
2024
2025 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2026                                     SDLoc DL, SelectionDAG &DAG) {
2027   const MachineFunction &MF = DAG.getMachineFunction();
2028   const Function *F = MF.getFunction();
2029
2030   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2031
2032   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2033   // version of the "preferred return address". These offsets affect the return
2034   // instruction if this is a return from PL1 without hypervisor extensions.
2035   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2036   //    SWI:     0      "subs pc, lr, #0"
2037   //    ABORT:   +4     "subs pc, lr, #4"
2038   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2039   // UNDEF varies depending on where the exception came from ARM or Thumb
2040   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2041
2042   int64_t LROffset;
2043   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2044       IntKind == "ABORT")
2045     LROffset = 4;
2046   else if (IntKind == "SWI" || IntKind == "UNDEF")
2047     LROffset = 0;
2048   else
2049     report_fatal_error("Unsupported interrupt attribute. If present, value "
2050                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2051
2052   RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2053
2054   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2055 }
2056
2057 SDValue
2058 ARMTargetLowering::LowerReturn(SDValue Chain,
2059                                CallingConv::ID CallConv, bool isVarArg,
2060                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2061                                const SmallVectorImpl<SDValue> &OutVals,
2062                                SDLoc dl, SelectionDAG &DAG) const {
2063
2064   // CCValAssign - represent the assignment of the return value to a location.
2065   SmallVector<CCValAssign, 16> RVLocs;
2066
2067   // CCState - Info about the registers and stack slots.
2068   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2069                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
2070
2071   // Analyze outgoing return values.
2072   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2073                                                isVarArg));
2074
2075   SDValue Flag;
2076   SmallVector<SDValue, 4> RetOps;
2077   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2078   bool isLittleEndian = Subtarget->isLittle();
2079
2080   // Copy the result values into the output registers.
2081   for (unsigned i = 0, realRVLocIdx = 0;
2082        i != RVLocs.size();
2083        ++i, ++realRVLocIdx) {
2084     CCValAssign &VA = RVLocs[i];
2085     assert(VA.isRegLoc() && "Can only return in registers!");
2086
2087     SDValue Arg = OutVals[realRVLocIdx];
2088
2089     switch (VA.getLocInfo()) {
2090     default: llvm_unreachable("Unknown loc info!");
2091     case CCValAssign::Full: break;
2092     case CCValAssign::BCvt:
2093       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2094       break;
2095     }
2096
2097     if (VA.needsCustom()) {
2098       if (VA.getLocVT() == MVT::v2f64) {
2099         // Extract the first half and return it in two registers.
2100         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2101                                    DAG.getConstant(0, MVT::i32));
2102         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2103                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2104
2105         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2106                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2107                                  Flag);
2108         Flag = Chain.getValue(1);
2109         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2110         VA = RVLocs[++i]; // skip ahead to next loc
2111         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2112                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2113                                  Flag);
2114         Flag = Chain.getValue(1);
2115         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2116         VA = RVLocs[++i]; // skip ahead to next loc
2117
2118         // Extract the 2nd half and fall through to handle it as an f64 value.
2119         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2120                           DAG.getConstant(1, MVT::i32));
2121       }
2122       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2123       // available.
2124       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2125                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2126       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2127                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2128                                Flag);
2129       Flag = Chain.getValue(1);
2130       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2131       VA = RVLocs[++i]; // skip ahead to next loc
2132       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2133                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2134                                Flag);
2135     } else
2136       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2137
2138     // Guarantee that all emitted copies are
2139     // stuck together, avoiding something bad.
2140     Flag = Chain.getValue(1);
2141     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2142   }
2143
2144   // Update chain and glue.
2145   RetOps[0] = Chain;
2146   if (Flag.getNode())
2147     RetOps.push_back(Flag);
2148
2149   // CPUs which aren't M-class use a special sequence to return from
2150   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2151   // though we use "subs pc, lr, #N").
2152   //
2153   // M-class CPUs actually use a normal return sequence with a special
2154   // (hardware-provided) value in LR, so the normal code path works.
2155   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2156       !Subtarget->isMClass()) {
2157     if (Subtarget->isThumb1Only())
2158       report_fatal_error("interrupt attribute is not supported in Thumb1");
2159     return LowerInterruptReturn(RetOps, dl, DAG);
2160   }
2161
2162   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2163 }
2164
2165 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2166   if (N->getNumValues() != 1)
2167     return false;
2168   if (!N->hasNUsesOfValue(1, 0))
2169     return false;
2170
2171   SDValue TCChain = Chain;
2172   SDNode *Copy = *N->use_begin();
2173   if (Copy->getOpcode() == ISD::CopyToReg) {
2174     // If the copy has a glue operand, we conservatively assume it isn't safe to
2175     // perform a tail call.
2176     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2177       return false;
2178     TCChain = Copy->getOperand(0);
2179   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2180     SDNode *VMov = Copy;
2181     // f64 returned in a pair of GPRs.
2182     SmallPtrSet<SDNode*, 2> Copies;
2183     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2184          UI != UE; ++UI) {
2185       if (UI->getOpcode() != ISD::CopyToReg)
2186         return false;
2187       Copies.insert(*UI);
2188     }
2189     if (Copies.size() > 2)
2190       return false;
2191
2192     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2193          UI != UE; ++UI) {
2194       SDValue UseChain = UI->getOperand(0);
2195       if (Copies.count(UseChain.getNode()))
2196         // Second CopyToReg
2197         Copy = *UI;
2198       else
2199         // First CopyToReg
2200         TCChain = UseChain;
2201     }
2202   } else if (Copy->getOpcode() == ISD::BITCAST) {
2203     // f32 returned in a single GPR.
2204     if (!Copy->hasOneUse())
2205       return false;
2206     Copy = *Copy->use_begin();
2207     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2208       return false;
2209     TCChain = Copy->getOperand(0);
2210   } else {
2211     return false;
2212   }
2213
2214   bool HasRet = false;
2215   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2216        UI != UE; ++UI) {
2217     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2218         UI->getOpcode() != ARMISD::INTRET_FLAG)
2219       return false;
2220     HasRet = true;
2221   }
2222
2223   if (!HasRet)
2224     return false;
2225
2226   Chain = TCChain;
2227   return true;
2228 }
2229
2230 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2231   if (!Subtarget->supportsTailCall())
2232     return false;
2233
2234   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2235     return false;
2236
2237   return !Subtarget->isThumb1Only();
2238 }
2239
2240 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2241 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2242 // one of the above mentioned nodes. It has to be wrapped because otherwise
2243 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2244 // be used to form addressing mode. These wrapped nodes will be selected
2245 // into MOVi.
2246 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2247   EVT PtrVT = Op.getValueType();
2248   // FIXME there is no actual debug info here
2249   SDLoc dl(Op);
2250   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2251   SDValue Res;
2252   if (CP->isMachineConstantPoolEntry())
2253     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2254                                     CP->getAlignment());
2255   else
2256     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2257                                     CP->getAlignment());
2258   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2259 }
2260
2261 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2262   return MachineJumpTableInfo::EK_Inline;
2263 }
2264
2265 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2266                                              SelectionDAG &DAG) const {
2267   MachineFunction &MF = DAG.getMachineFunction();
2268   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2269   unsigned ARMPCLabelIndex = 0;
2270   SDLoc DL(Op);
2271   EVT PtrVT = getPointerTy();
2272   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2273   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2274   SDValue CPAddr;
2275   if (RelocM == Reloc::Static) {
2276     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2277   } else {
2278     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2279     ARMPCLabelIndex = AFI->createPICLabelUId();
2280     ARMConstantPoolValue *CPV =
2281       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2282                                       ARMCP::CPBlockAddress, PCAdj);
2283     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2284   }
2285   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2286   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2287                                MachinePointerInfo::getConstantPool(),
2288                                false, false, false, 0);
2289   if (RelocM == Reloc::Static)
2290     return Result;
2291   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2292   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2293 }
2294
2295 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2296 SDValue
2297 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2298                                                  SelectionDAG &DAG) const {
2299   SDLoc dl(GA);
2300   EVT PtrVT = getPointerTy();
2301   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2302   MachineFunction &MF = DAG.getMachineFunction();
2303   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2304   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2305   ARMConstantPoolValue *CPV =
2306     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2307                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2308   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2309   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2310   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2311                          MachinePointerInfo::getConstantPool(),
2312                          false, false, false, 0);
2313   SDValue Chain = Argument.getValue(1);
2314
2315   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2316   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2317
2318   // call __tls_get_addr.
2319   ArgListTy Args;
2320   ArgListEntry Entry;
2321   Entry.Node = Argument;
2322   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2323   Args.push_back(Entry);
2324
2325   // FIXME: is there useful debug info available here?
2326   TargetLowering::CallLoweringInfo CLI(DAG);
2327   CLI.setDebugLoc(dl).setChain(Chain)
2328     .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2329                DAG.getExternalSymbol("__tls_get_addr", PtrVT), &Args, 0);
2330
2331   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2332   return CallResult.first;
2333 }
2334
2335 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2336 // "local exec" model.
2337 SDValue
2338 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2339                                         SelectionDAG &DAG,
2340                                         TLSModel::Model model) const {
2341   const GlobalValue *GV = GA->getGlobal();
2342   SDLoc dl(GA);
2343   SDValue Offset;
2344   SDValue Chain = DAG.getEntryNode();
2345   EVT PtrVT = getPointerTy();
2346   // Get the Thread Pointer
2347   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2348
2349   if (model == TLSModel::InitialExec) {
2350     MachineFunction &MF = DAG.getMachineFunction();
2351     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2352     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2353     // Initial exec model.
2354     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2355     ARMConstantPoolValue *CPV =
2356       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2357                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2358                                       true);
2359     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2360     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2361     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2362                          MachinePointerInfo::getConstantPool(),
2363                          false, false, false, 0);
2364     Chain = Offset.getValue(1);
2365
2366     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2367     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2368
2369     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2370                          MachinePointerInfo::getConstantPool(),
2371                          false, false, false, 0);
2372   } else {
2373     // local exec model
2374     assert(model == TLSModel::LocalExec);
2375     ARMConstantPoolValue *CPV =
2376       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2377     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2378     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2379     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2380                          MachinePointerInfo::getConstantPool(),
2381                          false, false, false, 0);
2382   }
2383
2384   // The address of the thread local variable is the add of the thread
2385   // pointer with the offset of the variable.
2386   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2387 }
2388
2389 SDValue
2390 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2391   // TODO: implement the "local dynamic" model
2392   assert(Subtarget->isTargetELF() &&
2393          "TLS not implemented for non-ELF targets");
2394   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2395
2396   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2397
2398   switch (model) {
2399     case TLSModel::GeneralDynamic:
2400     case TLSModel::LocalDynamic:
2401       return LowerToTLSGeneralDynamicModel(GA, DAG);
2402     case TLSModel::InitialExec:
2403     case TLSModel::LocalExec:
2404       return LowerToTLSExecModels(GA, DAG, model);
2405   }
2406   llvm_unreachable("bogus TLS model");
2407 }
2408
2409 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2410                                                  SelectionDAG &DAG) const {
2411   EVT PtrVT = getPointerTy();
2412   SDLoc dl(Op);
2413   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2414   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2415     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2416     ARMConstantPoolValue *CPV =
2417       ARMConstantPoolConstant::Create(GV,
2418                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2419     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2420     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2421     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2422                                  CPAddr,
2423                                  MachinePointerInfo::getConstantPool(),
2424                                  false, false, false, 0);
2425     SDValue Chain = Result.getValue(1);
2426     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2427     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2428     if (!UseGOTOFF)
2429       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2430                            MachinePointerInfo::getGOT(),
2431                            false, false, false, 0);
2432     return Result;
2433   }
2434
2435   // If we have T2 ops, we can materialize the address directly via movt/movw
2436   // pair. This is always cheaper.
2437   if (Subtarget->useMovt()) {
2438     ++NumMovwMovt;
2439     // FIXME: Once remat is capable of dealing with instructions with register
2440     // operands, expand this into two nodes.
2441     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2442                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2443   } else {
2444     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2445     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2446     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2447                        MachinePointerInfo::getConstantPool(),
2448                        false, false, false, 0);
2449   }
2450 }
2451
2452 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2453                                                     SelectionDAG &DAG) const {
2454   EVT PtrVT = getPointerTy();
2455   SDLoc dl(Op);
2456   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2457   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2458
2459   if (Subtarget->useMovt())
2460     ++NumMovwMovt;
2461
2462   // FIXME: Once remat is capable of dealing with instructions with register
2463   // operands, expand this into multiple nodes
2464   unsigned Wrapper =
2465       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2466
2467   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2468   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2469
2470   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2471     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2472                          MachinePointerInfo::getGOT(), false, false, false, 0);
2473   return Result;
2474 }
2475
2476 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2477                                                      SelectionDAG &DAG) const {
2478   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2479   assert(Subtarget->useMovt() && "Windows on ARM expects to use movw/movt");
2480
2481   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2482   EVT PtrVT = getPointerTy();
2483   SDLoc DL(Op);
2484
2485   ++NumMovwMovt;
2486
2487   // FIXME: Once remat is capable of dealing with instructions with register
2488   // operands, expand this into two nodes.
2489   return DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2490                      DAG.getTargetGlobalAddress(GV, DL, PtrVT));
2491 }
2492
2493 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2494                                                     SelectionDAG &DAG) const {
2495   assert(Subtarget->isTargetELF() &&
2496          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2497   MachineFunction &MF = DAG.getMachineFunction();
2498   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2499   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2500   EVT PtrVT = getPointerTy();
2501   SDLoc dl(Op);
2502   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2503   ARMConstantPoolValue *CPV =
2504     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2505                                   ARMPCLabelIndex, PCAdj);
2506   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2507   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2508   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2509                                MachinePointerInfo::getConstantPool(),
2510                                false, false, false, 0);
2511   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2512   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2513 }
2514
2515 SDValue
2516 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2517   SDLoc dl(Op);
2518   SDValue Val = DAG.getConstant(0, MVT::i32);
2519   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2520                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2521                      Op.getOperand(1), Val);
2522 }
2523
2524 SDValue
2525 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2526   SDLoc dl(Op);
2527   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2528                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2529 }
2530
2531 SDValue
2532 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2533                                           const ARMSubtarget *Subtarget) const {
2534   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2535   SDLoc dl(Op);
2536   switch (IntNo) {
2537   default: return SDValue();    // Don't custom lower most intrinsics.
2538   case Intrinsic::arm_thread_pointer: {
2539     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2540     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2541   }
2542   case Intrinsic::eh_sjlj_lsda: {
2543     MachineFunction &MF = DAG.getMachineFunction();
2544     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2545     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2546     EVT PtrVT = getPointerTy();
2547     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2548     SDValue CPAddr;
2549     unsigned PCAdj = (RelocM != Reloc::PIC_)
2550       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2551     ARMConstantPoolValue *CPV =
2552       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2553                                       ARMCP::CPLSDA, PCAdj);
2554     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2555     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2556     SDValue Result =
2557       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2558                   MachinePointerInfo::getConstantPool(),
2559                   false, false, false, 0);
2560
2561     if (RelocM == Reloc::PIC_) {
2562       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2563       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2564     }
2565     return Result;
2566   }
2567   case Intrinsic::arm_neon_vmulls:
2568   case Intrinsic::arm_neon_vmullu: {
2569     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2570       ? ARMISD::VMULLs : ARMISD::VMULLu;
2571     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2572                        Op.getOperand(1), Op.getOperand(2));
2573   }
2574   }
2575 }
2576
2577 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2578                                  const ARMSubtarget *Subtarget) {
2579   // FIXME: handle "fence singlethread" more efficiently.
2580   SDLoc dl(Op);
2581   if (!Subtarget->hasDataBarrier()) {
2582     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2583     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2584     // here.
2585     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2586            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2587     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2588                        DAG.getConstant(0, MVT::i32));
2589   }
2590
2591   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2592   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2593   unsigned Domain = ARM_MB::ISH;
2594   if (Subtarget->isMClass()) {
2595     // Only a full system barrier exists in the M-class architectures.
2596     Domain = ARM_MB::SY;
2597   } else if (Subtarget->isSwift() && Ord == Release) {
2598     // Swift happens to implement ISHST barriers in a way that's compatible with
2599     // Release semantics but weaker than ISH so we'd be fools not to use
2600     // it. Beware: other processors probably don't!
2601     Domain = ARM_MB::ISHST;
2602   }
2603
2604   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2605                      DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2606                      DAG.getConstant(Domain, MVT::i32));
2607 }
2608
2609 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2610                              const ARMSubtarget *Subtarget) {
2611   // ARM pre v5TE and Thumb1 does not have preload instructions.
2612   if (!(Subtarget->isThumb2() ||
2613         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2614     // Just preserve the chain.
2615     return Op.getOperand(0);
2616
2617   SDLoc dl(Op);
2618   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2619   if (!isRead &&
2620       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2621     // ARMv7 with MP extension has PLDW.
2622     return Op.getOperand(0);
2623
2624   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2625   if (Subtarget->isThumb()) {
2626     // Invert the bits.
2627     isRead = ~isRead & 1;
2628     isData = ~isData & 1;
2629   }
2630
2631   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2632                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2633                      DAG.getConstant(isData, MVT::i32));
2634 }
2635
2636 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2637   MachineFunction &MF = DAG.getMachineFunction();
2638   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2639
2640   // vastart just stores the address of the VarArgsFrameIndex slot into the
2641   // memory location argument.
2642   SDLoc dl(Op);
2643   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2644   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2645   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2646   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2647                       MachinePointerInfo(SV), false, false, 0);
2648 }
2649
2650 SDValue
2651 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2652                                         SDValue &Root, SelectionDAG &DAG,
2653                                         SDLoc dl) const {
2654   MachineFunction &MF = DAG.getMachineFunction();
2655   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2656
2657   const TargetRegisterClass *RC;
2658   if (AFI->isThumb1OnlyFunction())
2659     RC = &ARM::tGPRRegClass;
2660   else
2661     RC = &ARM::GPRRegClass;
2662
2663   // Transform the arguments stored in physical registers into virtual ones.
2664   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2665   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2666
2667   SDValue ArgValue2;
2668   if (NextVA.isMemLoc()) {
2669     MachineFrameInfo *MFI = MF.getFrameInfo();
2670     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2671
2672     // Create load node to retrieve arguments from the stack.
2673     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2674     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2675                             MachinePointerInfo::getFixedStack(FI),
2676                             false, false, false, 0);
2677   } else {
2678     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2679     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2680   }
2681   if (!Subtarget->isLittle())
2682     std::swap (ArgValue, ArgValue2);
2683   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2684 }
2685
2686 void
2687 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2688                                   unsigned InRegsParamRecordIdx,
2689                                   unsigned ArgSize,
2690                                   unsigned &ArgRegsSize,
2691                                   unsigned &ArgRegsSaveSize)
2692   const {
2693   unsigned NumGPRs;
2694   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2695     unsigned RBegin, REnd;
2696     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2697     NumGPRs = REnd - RBegin;
2698   } else {
2699     unsigned int firstUnalloced;
2700     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2701                                                 sizeof(GPRArgRegs) /
2702                                                 sizeof(GPRArgRegs[0]));
2703     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2704   }
2705
2706   unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2707   ArgRegsSize = NumGPRs * 4;
2708
2709   // If parameter is split between stack and GPRs...
2710   if (NumGPRs && Align > 4 &&
2711       (ArgRegsSize < ArgSize ||
2712         InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2713     // Add padding for part of param recovered from GPRs.  For example,
2714     // if Align == 8, its last byte must be at address K*8 - 1.
2715     // We need to do it, since remained (stack) part of parameter has
2716     // stack alignment, and we need to "attach" "GPRs head" without gaps
2717     // to it:
2718     // Stack:
2719     // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2720     // [ [padding] [GPRs head] ] [        Tail passed via stack       ....
2721     //
2722     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2723     unsigned Padding =
2724         OffsetToAlignment(ArgRegsSize + AFI->getArgRegsSaveSize(), Align);
2725     ArgRegsSaveSize = ArgRegsSize + Padding;
2726   } else
2727     // We don't need to extend regs save size for byval parameters if they
2728     // are passed via GPRs only.
2729     ArgRegsSaveSize = ArgRegsSize;
2730 }
2731
2732 // The remaining GPRs hold either the beginning of variable-argument
2733 // data, or the beginning of an aggregate passed by value (usually
2734 // byval).  Either way, we allocate stack slots adjacent to the data
2735 // provided by our caller, and store the unallocated registers there.
2736 // If this is a variadic function, the va_list pointer will begin with
2737 // these values; otherwise, this reassembles a (byval) structure that
2738 // was split between registers and memory.
2739 // Return: The frame index registers were stored into.
2740 int
2741 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2742                                   SDLoc dl, SDValue &Chain,
2743                                   const Value *OrigArg,
2744                                   unsigned InRegsParamRecordIdx,
2745                                   unsigned OffsetFromOrigArg,
2746                                   unsigned ArgOffset,
2747                                   unsigned ArgSize,
2748                                   bool ForceMutable,
2749                                   unsigned ByValStoreOffset,
2750                                   unsigned TotalArgRegsSaveSize) const {
2751
2752   // Currently, two use-cases possible:
2753   // Case #1. Non-var-args function, and we meet first byval parameter.
2754   //          Setup first unallocated register as first byval register;
2755   //          eat all remained registers
2756   //          (these two actions are performed by HandleByVal method).
2757   //          Then, here, we initialize stack frame with
2758   //          "store-reg" instructions.
2759   // Case #2. Var-args function, that doesn't contain byval parameters.
2760   //          The same: eat all remained unallocated registers,
2761   //          initialize stack frame.
2762
2763   MachineFunction &MF = DAG.getMachineFunction();
2764   MachineFrameInfo *MFI = MF.getFrameInfo();
2765   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2766   unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2767   unsigned RBegin, REnd;
2768   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2769     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2770     firstRegToSaveIndex = RBegin - ARM::R0;
2771     lastRegToSaveIndex = REnd - ARM::R0;
2772   } else {
2773     firstRegToSaveIndex = CCInfo.getFirstUnallocated
2774       (GPRArgRegs, array_lengthof(GPRArgRegs));
2775     lastRegToSaveIndex = 4;
2776   }
2777
2778   unsigned ArgRegsSize, ArgRegsSaveSize;
2779   computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2780                  ArgRegsSize, ArgRegsSaveSize);
2781
2782   // Store any by-val regs to their spots on the stack so that they may be
2783   // loaded by deferencing the result of formal parameter pointer or va_next.
2784   // Note: once stack area for byval/varargs registers
2785   // was initialized, it can't be initialized again.
2786   if (ArgRegsSaveSize) {
2787     unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2788
2789     if (Padding) {
2790       assert(AFI->getStoredByValParamsPadding() == 0 &&
2791              "The only parameter may be padded.");
2792       AFI->setStoredByValParamsPadding(Padding);
2793     }
2794
2795     int FrameIndex = MFI->CreateFixedObject(ArgRegsSaveSize,
2796                                             Padding +
2797                                               ByValStoreOffset -
2798                                               (int64_t)TotalArgRegsSaveSize,
2799                                             false);
2800     SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2801     if (Padding) {
2802        MFI->CreateFixedObject(Padding,
2803                               ArgOffset + ByValStoreOffset -
2804                                 (int64_t)ArgRegsSaveSize,
2805                               false);
2806     }
2807
2808     SmallVector<SDValue, 4> MemOps;
2809     for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2810          ++firstRegToSaveIndex, ++i) {
2811       const TargetRegisterClass *RC;
2812       if (AFI->isThumb1OnlyFunction())
2813         RC = &ARM::tGPRRegClass;
2814       else
2815         RC = &ARM::GPRRegClass;
2816
2817       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2818       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2819       SDValue Store =
2820         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2821                      MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2822                      false, false, 0);
2823       MemOps.push_back(Store);
2824       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2825                         DAG.getConstant(4, getPointerTy()));
2826     }
2827
2828     AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2829
2830     if (!MemOps.empty())
2831       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2832     return FrameIndex;
2833   } else {
2834     if (ArgSize == 0) {
2835       // We cannot allocate a zero-byte object for the first variadic argument,
2836       // so just make up a size.
2837       ArgSize = 4;
2838     }
2839     // This will point to the next argument passed via stack.
2840     return MFI->CreateFixedObject(
2841       ArgSize, ArgOffset, !ForceMutable);
2842   }
2843 }
2844
2845 // Setup stack frame, the va_list pointer will start from.
2846 void
2847 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2848                                         SDLoc dl, SDValue &Chain,
2849                                         unsigned ArgOffset,
2850                                         unsigned TotalArgRegsSaveSize,
2851                                         bool ForceMutable) const {
2852   MachineFunction &MF = DAG.getMachineFunction();
2853   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2854
2855   // Try to store any remaining integer argument regs
2856   // to their spots on the stack so that they may be loaded by deferencing
2857   // the result of va_next.
2858   // If there is no regs to be stored, just point address after last
2859   // argument passed via stack.
2860   int FrameIndex =
2861     StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
2862                    CCInfo.getInRegsParamsCount(), 0, ArgOffset, 0, ForceMutable,
2863                    0, TotalArgRegsSaveSize);
2864
2865   AFI->setVarArgsFrameIndex(FrameIndex);
2866 }
2867
2868 SDValue
2869 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2870                                         CallingConv::ID CallConv, bool isVarArg,
2871                                         const SmallVectorImpl<ISD::InputArg>
2872                                           &Ins,
2873                                         SDLoc dl, SelectionDAG &DAG,
2874                                         SmallVectorImpl<SDValue> &InVals)
2875                                           const {
2876   MachineFunction &MF = DAG.getMachineFunction();
2877   MachineFrameInfo *MFI = MF.getFrameInfo();
2878
2879   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2880
2881   // Assign locations to all of the incoming arguments.
2882   SmallVector<CCValAssign, 16> ArgLocs;
2883   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2884                     getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2885   CCInfo.AnalyzeFormalArguments(Ins,
2886                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2887                                                   isVarArg));
2888
2889   SmallVector<SDValue, 16> ArgValues;
2890   int lastInsIndex = -1;
2891   SDValue ArgValue;
2892   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2893   unsigned CurArgIdx = 0;
2894
2895   // Initially ArgRegsSaveSize is zero.
2896   // Then we increase this value each time we meet byval parameter.
2897   // We also increase this value in case of varargs function.
2898   AFI->setArgRegsSaveSize(0);
2899
2900   unsigned ByValStoreOffset = 0;
2901   unsigned TotalArgRegsSaveSize = 0;
2902   unsigned ArgRegsSaveSizeMaxAlign = 4;
2903
2904   // Calculate the amount of stack space that we need to allocate to store
2905   // byval and variadic arguments that are passed in registers.
2906   // We need to know this before we allocate the first byval or variadic
2907   // argument, as they will be allocated a stack slot below the CFA (Canonical
2908   // Frame Address, the stack pointer at entry to the function).
2909   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2910     CCValAssign &VA = ArgLocs[i];
2911     if (VA.isMemLoc()) {
2912       int index = VA.getValNo();
2913       if (index != lastInsIndex) {
2914         ISD::ArgFlagsTy Flags = Ins[index].Flags;
2915         if (Flags.isByVal()) {
2916           unsigned ExtraArgRegsSize;
2917           unsigned ExtraArgRegsSaveSize;
2918           computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsProceed(),
2919                          Flags.getByValSize(),
2920                          ExtraArgRegsSize, ExtraArgRegsSaveSize);
2921
2922           TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
2923           if (Flags.getByValAlign() > ArgRegsSaveSizeMaxAlign)
2924               ArgRegsSaveSizeMaxAlign = Flags.getByValAlign();
2925           CCInfo.nextInRegsParam();
2926         }
2927         lastInsIndex = index;
2928       }
2929     }
2930   }
2931   CCInfo.rewindByValRegsInfo();
2932   lastInsIndex = -1;
2933   if (isVarArg) {
2934     unsigned ExtraArgRegsSize;
2935     unsigned ExtraArgRegsSaveSize;
2936     computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsCount(), 0,
2937                    ExtraArgRegsSize, ExtraArgRegsSaveSize);
2938     TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
2939   }
2940   // If the arg regs save area contains N-byte aligned values, the
2941   // bottom of it must be at least N-byte aligned.
2942   TotalArgRegsSaveSize = RoundUpToAlignment(TotalArgRegsSaveSize, ArgRegsSaveSizeMaxAlign);
2943   TotalArgRegsSaveSize = std::min(TotalArgRegsSaveSize, 16U);
2944
2945   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2946     CCValAssign &VA = ArgLocs[i];
2947     std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
2948     CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
2949     // Arguments stored in registers.
2950     if (VA.isRegLoc()) {
2951       EVT RegVT = VA.getLocVT();
2952
2953       if (VA.needsCustom()) {
2954         // f64 and vector types are split up into multiple registers or
2955         // combinations of registers and stack slots.
2956         if (VA.getLocVT() == MVT::v2f64) {
2957           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2958                                                    Chain, DAG, dl);
2959           VA = ArgLocs[++i]; // skip ahead to next loc
2960           SDValue ArgValue2;
2961           if (VA.isMemLoc()) {
2962             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2963             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2964             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2965                                     MachinePointerInfo::getFixedStack(FI),
2966                                     false, false, false, 0);
2967           } else {
2968             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2969                                              Chain, DAG, dl);
2970           }
2971           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2972           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2973                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2974           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2975                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2976         } else
2977           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2978
2979       } else {
2980         const TargetRegisterClass *RC;
2981
2982         if (RegVT == MVT::f32)
2983           RC = &ARM::SPRRegClass;
2984         else if (RegVT == MVT::f64)
2985           RC = &ARM::DPRRegClass;
2986         else if (RegVT == MVT::v2f64)
2987           RC = &ARM::QPRRegClass;
2988         else if (RegVT == MVT::i32)
2989           RC = AFI->isThumb1OnlyFunction() ?
2990             (const TargetRegisterClass*)&ARM::tGPRRegClass :
2991             (const TargetRegisterClass*)&ARM::GPRRegClass;
2992         else
2993           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2994
2995         // Transform the arguments in physical registers into virtual ones.
2996         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2997         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2998       }
2999
3000       // If this is an 8 or 16-bit value, it is really passed promoted
3001       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3002       // truncate to the right size.
3003       switch (VA.getLocInfo()) {
3004       default: llvm_unreachable("Unknown loc info!");
3005       case CCValAssign::Full: break;
3006       case CCValAssign::BCvt:
3007         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3008         break;
3009       case CCValAssign::SExt:
3010         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3011                                DAG.getValueType(VA.getValVT()));
3012         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3013         break;
3014       case CCValAssign::ZExt:
3015         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3016                                DAG.getValueType(VA.getValVT()));
3017         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3018         break;
3019       }
3020
3021       InVals.push_back(ArgValue);
3022
3023     } else { // VA.isRegLoc()
3024
3025       // sanity check
3026       assert(VA.isMemLoc());
3027       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3028
3029       int index = ArgLocs[i].getValNo();
3030
3031       // Some Ins[] entries become multiple ArgLoc[] entries.
3032       // Process them only once.
3033       if (index != lastInsIndex)
3034         {
3035           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3036           // FIXME: For now, all byval parameter objects are marked mutable.
3037           // This can be changed with more analysis.
3038           // In case of tail call optimization mark all arguments mutable.
3039           // Since they could be overwritten by lowering of arguments in case of
3040           // a tail call.
3041           if (Flags.isByVal()) {
3042             unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
3043
3044             ByValStoreOffset = RoundUpToAlignment(ByValStoreOffset, Flags.getByValAlign());
3045             int FrameIndex = StoreByValRegs(
3046                 CCInfo, DAG, dl, Chain, CurOrigArg,
3047                 CurByValIndex,
3048                 Ins[VA.getValNo()].PartOffset,
3049                 VA.getLocMemOffset(),
3050                 Flags.getByValSize(),
3051                 true /*force mutable frames*/,
3052                 ByValStoreOffset,
3053                 TotalArgRegsSaveSize);
3054             ByValStoreOffset += Flags.getByValSize();
3055             ByValStoreOffset = std::min(ByValStoreOffset, 16U);
3056             InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3057             CCInfo.nextInRegsParam();
3058           } else {
3059             unsigned FIOffset = VA.getLocMemOffset();
3060             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3061                                             FIOffset, true);
3062
3063             // Create load nodes to retrieve arguments from the stack.
3064             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3065             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3066                                          MachinePointerInfo::getFixedStack(FI),
3067                                          false, false, false, 0));
3068           }
3069           lastInsIndex = index;
3070         }
3071     }
3072   }
3073
3074   // varargs
3075   if (isVarArg)
3076     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3077                          CCInfo.getNextStackOffset(),
3078                          TotalArgRegsSaveSize);
3079
3080   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3081
3082   return Chain;
3083 }
3084
3085 /// isFloatingPointZero - Return true if this is +0.0.
3086 static bool isFloatingPointZero(SDValue Op) {
3087   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3088     return CFP->getValueAPF().isPosZero();
3089   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3090     // Maybe this has already been legalized into the constant pool?
3091     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3092       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3093       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3094         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3095           return CFP->getValueAPF().isPosZero();
3096     }
3097   }
3098   return false;
3099 }
3100
3101 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3102 /// the given operands.
3103 SDValue
3104 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3105                              SDValue &ARMcc, SelectionDAG &DAG,
3106                              SDLoc dl) const {
3107   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3108     unsigned C = RHSC->getZExtValue();
3109     if (!isLegalICmpImmediate(C)) {
3110       // Constant does not fit, try adjusting it by one?
3111       switch (CC) {
3112       default: break;
3113       case ISD::SETLT:
3114       case ISD::SETGE:
3115         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3116           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3117           RHS = DAG.getConstant(C-1, MVT::i32);
3118         }
3119         break;
3120       case ISD::SETULT:
3121       case ISD::SETUGE:
3122         if (C != 0 && isLegalICmpImmediate(C-1)) {
3123           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3124           RHS = DAG.getConstant(C-1, MVT::i32);
3125         }
3126         break;
3127       case ISD::SETLE:
3128       case ISD::SETGT:
3129         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3130           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3131           RHS = DAG.getConstant(C+1, MVT::i32);
3132         }
3133         break;
3134       case ISD::SETULE:
3135       case ISD::SETUGT:
3136         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3137           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3138           RHS = DAG.getConstant(C+1, MVT::i32);
3139         }
3140         break;
3141       }
3142     }
3143   }
3144
3145   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3146   ARMISD::NodeType CompareType;
3147   switch (CondCode) {
3148   default:
3149     CompareType = ARMISD::CMP;
3150     break;
3151   case ARMCC::EQ:
3152   case ARMCC::NE:
3153     // Uses only Z Flag
3154     CompareType = ARMISD::CMPZ;
3155     break;
3156   }
3157   ARMcc = DAG.getConstant(CondCode, MVT::i32);
3158   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3159 }
3160
3161 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3162 SDValue
3163 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3164                              SDLoc dl) const {
3165   SDValue Cmp;
3166   if (!isFloatingPointZero(RHS))
3167     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3168   else
3169     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3170   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3171 }
3172
3173 /// duplicateCmp - Glue values can have only one use, so this function
3174 /// duplicates a comparison node.
3175 SDValue
3176 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3177   unsigned Opc = Cmp.getOpcode();
3178   SDLoc DL(Cmp);
3179   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3180     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3181
3182   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3183   Cmp = Cmp.getOperand(0);
3184   Opc = Cmp.getOpcode();
3185   if (Opc == ARMISD::CMPFP)
3186     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3187   else {
3188     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3189     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3190   }
3191   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3192 }
3193
3194 std::pair<SDValue, SDValue>
3195 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3196                                  SDValue &ARMcc) const {
3197   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3198
3199   SDValue Value, OverflowCmp;
3200   SDValue LHS = Op.getOperand(0);
3201   SDValue RHS = Op.getOperand(1);
3202
3203
3204   // FIXME: We are currently always generating CMPs because we don't support
3205   // generating CMN through the backend. This is not as good as the natural
3206   // CMP case because it causes a register dependency and cannot be folded
3207   // later.
3208
3209   switch (Op.getOpcode()) {
3210   default:
3211     llvm_unreachable("Unknown overflow instruction!");
3212   case ISD::SADDO:
3213     ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3214     Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3215     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3216     break;
3217   case ISD::UADDO:
3218     ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3219     Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3220     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3221     break;
3222   case ISD::SSUBO:
3223     ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3224     Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3225     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3226     break;
3227   case ISD::USUBO:
3228     ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3229     Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3230     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3231     break;
3232   } // switch (...)
3233
3234   return std::make_pair(Value, OverflowCmp);
3235 }
3236
3237
3238 SDValue
3239 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3240   // Let legalize expand this if it isn't a legal type yet.
3241   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3242     return SDValue();
3243
3244   SDValue Value, OverflowCmp;
3245   SDValue ARMcc;
3246   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3247   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3248   // We use 0 and 1 as false and true values.
3249   SDValue TVal = DAG.getConstant(1, MVT::i32);
3250   SDValue FVal = DAG.getConstant(0, MVT::i32);
3251   EVT VT = Op.getValueType();
3252
3253   SDValue Overflow = DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, TVal, FVal,
3254                                  ARMcc, CCR, OverflowCmp);
3255
3256   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3257   return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), VTs, Value, Overflow);
3258 }
3259
3260
3261 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3262   SDValue Cond = Op.getOperand(0);
3263   SDValue SelectTrue = Op.getOperand(1);
3264   SDValue SelectFalse = Op.getOperand(2);
3265   SDLoc dl(Op);
3266   unsigned Opc = Cond.getOpcode();
3267
3268   if (Cond.getResNo() == 1 &&
3269       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3270        Opc == ISD::USUBO)) {
3271     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3272       return SDValue();
3273
3274     SDValue Value, OverflowCmp;
3275     SDValue ARMcc;
3276     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3277     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3278     EVT VT = Op.getValueType();
3279
3280     return DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, SelectTrue, SelectFalse,
3281                        ARMcc, CCR, OverflowCmp);
3282
3283   }
3284
3285   // Convert:
3286   //
3287   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3288   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3289   //
3290   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3291     const ConstantSDNode *CMOVTrue =
3292       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3293     const ConstantSDNode *CMOVFalse =
3294       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3295
3296     if (CMOVTrue && CMOVFalse) {
3297       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3298       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3299
3300       SDValue True;
3301       SDValue False;
3302       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3303         True = SelectTrue;
3304         False = SelectFalse;
3305       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3306         True = SelectFalse;
3307         False = SelectTrue;
3308       }
3309
3310       if (True.getNode() && False.getNode()) {
3311         EVT VT = Op.getValueType();
3312         SDValue ARMcc = Cond.getOperand(2);
3313         SDValue CCR = Cond.getOperand(3);
3314         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3315         assert(True.getValueType() == VT);
3316         return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
3317       }
3318     }
3319   }
3320
3321   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3322   // undefined bits before doing a full-word comparison with zero.
3323   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3324                      DAG.getConstant(1, Cond.getValueType()));
3325
3326   return DAG.getSelectCC(dl, Cond,
3327                          DAG.getConstant(0, Cond.getValueType()),
3328                          SelectTrue, SelectFalse, ISD::SETNE);
3329 }
3330
3331 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3332   if (CC == ISD::SETNE)
3333     return ISD::SETEQ;
3334   return ISD::getSetCCInverse(CC, true);
3335 }
3336
3337 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3338                                  bool &swpCmpOps, bool &swpVselOps) {
3339   // Start by selecting the GE condition code for opcodes that return true for
3340   // 'equality'
3341   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3342       CC == ISD::SETULE)
3343     CondCode = ARMCC::GE;
3344
3345   // and GT for opcodes that return false for 'equality'.
3346   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3347            CC == ISD::SETULT)
3348     CondCode = ARMCC::GT;
3349
3350   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3351   // to swap the compare operands.
3352   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3353       CC == ISD::SETULT)
3354     swpCmpOps = true;
3355
3356   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3357   // If we have an unordered opcode, we need to swap the operands to the VSEL
3358   // instruction (effectively negating the condition).
3359   //
3360   // This also has the effect of swapping which one of 'less' or 'greater'
3361   // returns true, so we also swap the compare operands. It also switches
3362   // whether we return true for 'equality', so we compensate by picking the
3363   // opposite condition code to our original choice.
3364   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3365       CC == ISD::SETUGT) {
3366     swpCmpOps = !swpCmpOps;
3367     swpVselOps = !swpVselOps;
3368     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3369   }
3370
3371   // 'ordered' is 'anything but unordered', so use the VS condition code and
3372   // swap the VSEL operands.
3373   if (CC == ISD::SETO) {
3374     CondCode = ARMCC::VS;
3375     swpVselOps = true;
3376   }
3377
3378   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3379   // code and swap the VSEL operands.
3380   if (CC == ISD::SETUNE) {
3381     CondCode = ARMCC::EQ;
3382     swpVselOps = true;
3383   }
3384 }
3385
3386 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3387   EVT VT = Op.getValueType();
3388   SDValue LHS = Op.getOperand(0);
3389   SDValue RHS = Op.getOperand(1);
3390   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3391   SDValue TrueVal = Op.getOperand(2);
3392   SDValue FalseVal = Op.getOperand(3);
3393   SDLoc dl(Op);
3394
3395   if (LHS.getValueType() == MVT::i32) {
3396     // Try to generate VSEL on ARMv8.
3397     // The VSEL instruction can't use all the usual ARM condition
3398     // codes: it only has two bits to select the condition code, so it's
3399     // constrained to use only GE, GT, VS and EQ.
3400     //
3401     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3402     // swap the operands of the previous compare instruction (effectively
3403     // inverting the compare condition, swapping 'less' and 'greater') and
3404     // sometimes need to swap the operands to the VSEL (which inverts the
3405     // condition in the sense of firing whenever the previous condition didn't)
3406     if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3407                                       TrueVal.getValueType() == MVT::f64)) {
3408       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3409       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3410           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3411         CC = getInverseCCForVSEL(CC);
3412         std::swap(TrueVal, FalseVal);
3413       }
3414     }
3415
3416     SDValue ARMcc;
3417     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3418     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3419     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3420                        Cmp);
3421   }
3422
3423   ARMCC::CondCodes CondCode, CondCode2;
3424   FPCCToARMCC(CC, CondCode, CondCode2);
3425
3426   // Try to generate VSEL on ARMv8.
3427   if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3428                                     TrueVal.getValueType() == MVT::f64)) {
3429     // We can select VMAXNM/VMINNM from a compare followed by a select with the
3430     // same operands, as follows:
3431     //   c = fcmp [ogt, olt, ugt, ult] a, b
3432     //   select c, a, b
3433     // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3434     // handled differently than the original code sequence.
3435     if (getTargetMachine().Options.UnsafeFPMath && LHS == TrueVal &&
3436         RHS == FalseVal) {
3437       if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3438         return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3439       if (CC == ISD::SETOLT || CC == ISD::SETULT)
3440         return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3441     }
3442
3443     bool swpCmpOps = false;
3444     bool swpVselOps = false;
3445     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3446
3447     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3448         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3449       if (swpCmpOps)
3450         std::swap(LHS, RHS);
3451       if (swpVselOps)
3452         std::swap(TrueVal, FalseVal);
3453     }
3454   }
3455
3456   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3457   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3458   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3459   SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
3460                                ARMcc, CCR, Cmp);
3461   if (CondCode2 != ARMCC::AL) {
3462     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3463     // FIXME: Needs another CMP because flag can have but one use.
3464     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3465     Result = DAG.getNode(ARMISD::CMOV, dl, VT,
3466                          Result, TrueVal, ARMcc2, CCR, Cmp2);
3467   }
3468   return Result;
3469 }
3470
3471 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3472 /// to morph to an integer compare sequence.
3473 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3474                            const ARMSubtarget *Subtarget) {
3475   SDNode *N = Op.getNode();
3476   if (!N->hasOneUse())
3477     // Otherwise it requires moving the value from fp to integer registers.
3478     return false;
3479   if (!N->getNumValues())
3480     return false;
3481   EVT VT = Op.getValueType();
3482   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3483     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3484     // vmrs are very slow, e.g. cortex-a8.
3485     return false;
3486
3487   if (isFloatingPointZero(Op)) {
3488     SeenZero = true;
3489     return true;
3490   }
3491   return ISD::isNormalLoad(N);
3492 }
3493
3494 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3495   if (isFloatingPointZero(Op))
3496     return DAG.getConstant(0, MVT::i32);
3497
3498   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3499     return DAG.getLoad(MVT::i32, SDLoc(Op),
3500                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3501                        Ld->isVolatile(), Ld->isNonTemporal(),
3502                        Ld->isInvariant(), Ld->getAlignment());
3503
3504   llvm_unreachable("Unknown VFP cmp argument!");
3505 }
3506
3507 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3508                            SDValue &RetVal1, SDValue &RetVal2) {
3509   if (isFloatingPointZero(Op)) {
3510     RetVal1 = DAG.getConstant(0, MVT::i32);
3511     RetVal2 = DAG.getConstant(0, MVT::i32);
3512     return;
3513   }
3514
3515   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3516     SDValue Ptr = Ld->getBasePtr();
3517     RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3518                           Ld->getChain(), Ptr,
3519                           Ld->getPointerInfo(),
3520                           Ld->isVolatile(), Ld->isNonTemporal(),
3521                           Ld->isInvariant(), Ld->getAlignment());
3522
3523     EVT PtrType = Ptr.getValueType();
3524     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3525     SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3526                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
3527     RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3528                           Ld->getChain(), NewPtr,
3529                           Ld->getPointerInfo().getWithOffset(4),
3530                           Ld->isVolatile(), Ld->isNonTemporal(),
3531                           Ld->isInvariant(), NewAlign);
3532     return;
3533   }
3534
3535   llvm_unreachable("Unknown VFP cmp argument!");
3536 }
3537
3538 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3539 /// f32 and even f64 comparisons to integer ones.
3540 SDValue
3541 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3542   SDValue Chain = Op.getOperand(0);
3543   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3544   SDValue LHS = Op.getOperand(2);
3545   SDValue RHS = Op.getOperand(3);
3546   SDValue Dest = Op.getOperand(4);
3547   SDLoc dl(Op);
3548
3549   bool LHSSeenZero = false;
3550   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3551   bool RHSSeenZero = false;
3552   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3553   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3554     // If unsafe fp math optimization is enabled and there are no other uses of
3555     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3556     // to an integer comparison.
3557     if (CC == ISD::SETOEQ)
3558       CC = ISD::SETEQ;
3559     else if (CC == ISD::SETUNE)
3560       CC = ISD::SETNE;
3561
3562     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3563     SDValue ARMcc;
3564     if (LHS.getValueType() == MVT::f32) {
3565       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3566                         bitcastf32Toi32(LHS, DAG), Mask);
3567       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3568                         bitcastf32Toi32(RHS, DAG), Mask);
3569       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3570       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3571       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3572                          Chain, Dest, ARMcc, CCR, Cmp);
3573     }
3574
3575     SDValue LHS1, LHS2;
3576     SDValue RHS1, RHS2;
3577     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3578     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3579     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3580     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3581     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3582     ARMcc = DAG.getConstant(CondCode, MVT::i32);
3583     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3584     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3585     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3586   }
3587
3588   return SDValue();
3589 }
3590
3591 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3592   SDValue Chain = Op.getOperand(0);
3593   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3594   SDValue LHS = Op.getOperand(2);
3595   SDValue RHS = Op.getOperand(3);
3596   SDValue Dest = Op.getOperand(4);
3597   SDLoc dl(Op);
3598
3599   if (LHS.getValueType() == MVT::i32) {
3600     SDValue ARMcc;
3601     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3602     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3603     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3604                        Chain, Dest, ARMcc, CCR, Cmp);
3605   }
3606
3607   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3608
3609   if (getTargetMachine().Options.UnsafeFPMath &&
3610       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3611        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3612     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3613     if (Result.getNode())
3614       return Result;
3615   }
3616
3617   ARMCC::CondCodes CondCode, CondCode2;
3618   FPCCToARMCC(CC, CondCode, CondCode2);
3619
3620   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3621   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3622   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3623   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3624   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3625   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3626   if (CondCode2 != ARMCC::AL) {
3627     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3628     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3629     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3630   }
3631   return Res;
3632 }
3633
3634 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3635   SDValue Chain = Op.getOperand(0);
3636   SDValue Table = Op.getOperand(1);
3637   SDValue Index = Op.getOperand(2);
3638   SDLoc dl(Op);
3639
3640   EVT PTy = getPointerTy();
3641   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3642   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3643   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3644   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3645   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3646   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3647   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3648   if (Subtarget->isThumb2()) {
3649     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3650     // which does another jump to the destination. This also makes it easier
3651     // to translate it to TBB / TBH later.
3652     // FIXME: This might not work if the function is extremely large.
3653     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3654                        Addr, Op.getOperand(2), JTI, UId);
3655   }
3656   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3657     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3658                        MachinePointerInfo::getJumpTable(),
3659                        false, false, false, 0);
3660     Chain = Addr.getValue(1);
3661     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3662     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3663   } else {
3664     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3665                        MachinePointerInfo::getJumpTable(),
3666                        false, false, false, 0);
3667     Chain = Addr.getValue(1);
3668     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3669   }
3670 }
3671
3672 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3673   EVT VT = Op.getValueType();
3674   SDLoc dl(Op);
3675
3676   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3677     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3678       return Op;
3679     return DAG.UnrollVectorOp(Op.getNode());
3680   }
3681
3682   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3683          "Invalid type for custom lowering!");
3684   if (VT != MVT::v4i16)
3685     return DAG.UnrollVectorOp(Op.getNode());
3686
3687   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3688   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3689 }
3690
3691 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3692   EVT VT = Op.getValueType();
3693   if (VT.isVector())
3694     return LowerVectorFP_TO_INT(Op, DAG);
3695
3696   SDLoc dl(Op);
3697   unsigned Opc;
3698
3699   switch (Op.getOpcode()) {
3700   default: llvm_unreachable("Invalid opcode!");
3701   case ISD::FP_TO_SINT:
3702     Opc = ARMISD::FTOSI;
3703     break;
3704   case ISD::FP_TO_UINT:
3705     Opc = ARMISD::FTOUI;
3706     break;
3707   }
3708   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3709   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3710 }
3711
3712 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3713   EVT VT = Op.getValueType();
3714   SDLoc dl(Op);
3715
3716   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3717     if (VT.getVectorElementType() == MVT::f32)
3718       return Op;
3719     return DAG.UnrollVectorOp(Op.getNode());
3720   }
3721
3722   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3723          "Invalid type for custom lowering!");
3724   if (VT != MVT::v4f32)
3725     return DAG.UnrollVectorOp(Op.getNode());
3726
3727   unsigned CastOpc;
3728   unsigned Opc;
3729   switch (Op.getOpcode()) {
3730   default: llvm_unreachable("Invalid opcode!");
3731   case ISD::SINT_TO_FP:
3732     CastOpc = ISD::SIGN_EXTEND;
3733     Opc = ISD::SINT_TO_FP;
3734     break;
3735   case ISD::UINT_TO_FP:
3736     CastOpc = ISD::ZERO_EXTEND;
3737     Opc = ISD::UINT_TO_FP;
3738     break;
3739   }
3740
3741   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3742   return DAG.getNode(Opc, dl, VT, Op);
3743 }
3744
3745 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3746   EVT VT = Op.getValueType();
3747   if (VT.isVector())
3748     return LowerVectorINT_TO_FP(Op, DAG);
3749
3750   SDLoc dl(Op);
3751   unsigned Opc;
3752
3753   switch (Op.getOpcode()) {
3754   default: llvm_unreachable("Invalid opcode!");
3755   case ISD::SINT_TO_FP:
3756     Opc = ARMISD::SITOF;
3757     break;
3758   case ISD::UINT_TO_FP:
3759     Opc = ARMISD::UITOF;
3760     break;
3761   }
3762
3763   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3764   return DAG.getNode(Opc, dl, VT, Op);
3765 }
3766
3767 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3768   // Implement fcopysign with a fabs and a conditional fneg.
3769   SDValue Tmp0 = Op.getOperand(0);
3770   SDValue Tmp1 = Op.getOperand(1);
3771   SDLoc dl(Op);
3772   EVT VT = Op.getValueType();
3773   EVT SrcVT = Tmp1.getValueType();
3774   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3775     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3776   bool UseNEON = !InGPR && Subtarget->hasNEON();
3777
3778   if (UseNEON) {
3779     // Use VBSL to copy the sign bit.
3780     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3781     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3782                                DAG.getTargetConstant(EncodedVal, MVT::i32));
3783     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3784     if (VT == MVT::f64)
3785       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3786                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3787                          DAG.getConstant(32, MVT::i32));
3788     else /*if (VT == MVT::f32)*/
3789       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3790     if (SrcVT == MVT::f32) {
3791       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3792       if (VT == MVT::f64)
3793         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3794                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3795                            DAG.getConstant(32, MVT::i32));
3796     } else if (VT == MVT::f32)
3797       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3798                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3799                          DAG.getConstant(32, MVT::i32));
3800     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3801     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3802
3803     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3804                                             MVT::i32);
3805     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3806     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3807                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3808
3809     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3810                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3811                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3812     if (VT == MVT::f32) {
3813       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3814       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3815                         DAG.getConstant(0, MVT::i32));
3816     } else {
3817       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3818     }
3819
3820     return Res;
3821   }
3822
3823   // Bitcast operand 1 to i32.
3824   if (SrcVT == MVT::f64)
3825     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3826                        Tmp1).getValue(1);
3827   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3828
3829   // Or in the signbit with integer operations.
3830   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3831   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3832   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3833   if (VT == MVT::f32) {
3834     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3835                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3836     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3837                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3838   }
3839
3840   // f64: Or the high part with signbit and then combine two parts.
3841   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3842                      Tmp0);
3843   SDValue Lo = Tmp0.getValue(0);
3844   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3845   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3846   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3847 }
3848
3849 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3850   MachineFunction &MF = DAG.getMachineFunction();
3851   MachineFrameInfo *MFI = MF.getFrameInfo();
3852   MFI->setReturnAddressIsTaken(true);
3853
3854   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3855     return SDValue();
3856
3857   EVT VT = Op.getValueType();
3858   SDLoc dl(Op);
3859   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3860   if (Depth) {
3861     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3862     SDValue Offset = DAG.getConstant(4, MVT::i32);
3863     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3864                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3865                        MachinePointerInfo(), false, false, false, 0);
3866   }
3867
3868   // Return LR, which contains the return address. Mark it an implicit live-in.
3869   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3870   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3871 }
3872
3873 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3874   const ARMBaseRegisterInfo &ARI =
3875     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
3876   MachineFunction &MF = DAG.getMachineFunction();
3877   MachineFrameInfo *MFI = MF.getFrameInfo();
3878   MFI->setFrameAddressIsTaken(true);
3879
3880   EVT VT = Op.getValueType();
3881   SDLoc dl(Op);  // FIXME probably not meaningful
3882   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3883   unsigned FrameReg = ARI.getFrameRegister(MF);
3884   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3885   while (Depth--)
3886     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3887                             MachinePointerInfo(),
3888                             false, false, false, 0);
3889   return FrameAddr;
3890 }
3891
3892 // FIXME? Maybe this could be a TableGen attribute on some registers and
3893 // this table could be generated automatically from RegInfo.
3894 unsigned ARMTargetLowering::getRegisterByName(const char* RegName,
3895                                               EVT VT) const {
3896   unsigned Reg = StringSwitch<unsigned>(RegName)
3897                        .Case("sp", ARM::SP)
3898                        .Default(0);
3899   if (Reg)
3900     return Reg;
3901   report_fatal_error("Invalid register name global variable");
3902 }
3903
3904 /// ExpandBITCAST - If the target supports VFP, this function is called to
3905 /// expand a bit convert where either the source or destination type is i64 to
3906 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
3907 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3908 /// vectors), since the legalizer won't know what to do with that.
3909 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3910   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3911   SDLoc dl(N);
3912   SDValue Op = N->getOperand(0);
3913
3914   // This function is only supposed to be called for i64 types, either as the
3915   // source or destination of the bit convert.
3916   EVT SrcVT = Op.getValueType();
3917   EVT DstVT = N->getValueType(0);
3918   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3919          "ExpandBITCAST called for non-i64 type");
3920
3921   // Turn i64->f64 into VMOVDRR.
3922   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3923     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3924                              DAG.getConstant(0, MVT::i32));
3925     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3926                              DAG.getConstant(1, MVT::i32));
3927     return DAG.getNode(ISD::BITCAST, dl, DstVT,
3928                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3929   }
3930
3931   // Turn f64->i64 into VMOVRRD.
3932   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3933     SDValue Cvt;
3934     if (TLI.isBigEndian() && SrcVT.isVector() &&
3935         SrcVT.getVectorNumElements() > 1)
3936       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3937                         DAG.getVTList(MVT::i32, MVT::i32),
3938                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
3939     else
3940       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3941                         DAG.getVTList(MVT::i32, MVT::i32), Op);
3942     // Merge the pieces into a single i64 value.
3943     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3944   }
3945
3946   return SDValue();
3947 }
3948
3949 /// getZeroVector - Returns a vector of specified type with all zero elements.
3950 /// Zero vectors are used to represent vector negation and in those cases
3951 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
3952 /// not support i64 elements, so sometimes the zero vectors will need to be
3953 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
3954 /// zero vector.
3955 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
3956   assert(VT.isVector() && "Expected a vector type");
3957   // The canonical modified immediate encoding of a zero vector is....0!
3958   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3959   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3960   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3961   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3962 }
3963
3964 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3965 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3966 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3967                                                 SelectionDAG &DAG) const {
3968   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3969   EVT VT = Op.getValueType();
3970   unsigned VTBits = VT.getSizeInBits();
3971   SDLoc dl(Op);
3972   SDValue ShOpLo = Op.getOperand(0);
3973   SDValue ShOpHi = Op.getOperand(1);
3974   SDValue ShAmt  = Op.getOperand(2);
3975   SDValue ARMcc;
3976   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3977
3978   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3979
3980   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3981                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3982   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3983   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3984                                    DAG.getConstant(VTBits, MVT::i32));
3985   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3986   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3987   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3988
3989   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3990   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3991                           ARMcc, DAG, dl);
3992   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3993   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3994                            CCR, Cmp);
3995
3996   SDValue Ops[2] = { Lo, Hi };
3997   return DAG.getMergeValues(Ops, dl);
3998 }
3999
4000 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4001 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4002 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4003                                                SelectionDAG &DAG) const {
4004   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4005   EVT VT = Op.getValueType();
4006   unsigned VTBits = VT.getSizeInBits();
4007   SDLoc dl(Op);
4008   SDValue ShOpLo = Op.getOperand(0);
4009   SDValue ShOpHi = Op.getOperand(1);
4010   SDValue ShAmt  = Op.getOperand(2);
4011   SDValue ARMcc;
4012
4013   assert(Op.getOpcode() == ISD::SHL_PARTS);
4014   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4015                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
4016   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4017   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4018                                    DAG.getConstant(VTBits, MVT::i32));
4019   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4020   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4021
4022   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4023   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4024   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4025                           ARMcc, DAG, dl);
4026   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4027   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4028                            CCR, Cmp);
4029
4030   SDValue Ops[2] = { Lo, Hi };
4031   return DAG.getMergeValues(Ops, dl);
4032 }
4033
4034 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4035                                             SelectionDAG &DAG) const {
4036   // The rounding mode is in bits 23:22 of the FPSCR.
4037   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4038   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4039   // so that the shift + and get folded into a bitfield extract.
4040   SDLoc dl(Op);
4041   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4042                               DAG.getConstant(Intrinsic::arm_get_fpscr,
4043                                               MVT::i32));
4044   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4045                                   DAG.getConstant(1U << 22, MVT::i32));
4046   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4047                               DAG.getConstant(22, MVT::i32));
4048   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4049                      DAG.getConstant(3, MVT::i32));
4050 }
4051
4052 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4053                          const ARMSubtarget *ST) {
4054   EVT VT = N->getValueType(0);
4055   SDLoc dl(N);
4056
4057   if (!ST->hasV6T2Ops())
4058     return SDValue();
4059
4060   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4061   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4062 }
4063
4064 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4065 /// for each 16-bit element from operand, repeated.  The basic idea is to
4066 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4067 ///
4068 /// Trace for v4i16:
4069 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
4070 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4071 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4072 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4073 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
4074 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
4075 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4076 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
4077 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4078   EVT VT = N->getValueType(0);
4079   SDLoc DL(N);
4080
4081   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4082   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4083   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4084   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4085   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4086   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4087 }
4088
4089 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4090 /// bit-count for each 16-bit element from the operand.  We need slightly
4091 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4092 /// 64/128-bit registers.
4093 ///
4094 /// Trace for v4i16:
4095 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
4096 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4097 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
4098 /// v4i16:Extracted = [k0    k1    k2    k3    ]
4099 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4100   EVT VT = N->getValueType(0);
4101   SDLoc DL(N);
4102
4103   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4104   if (VT.is64BitVector()) {
4105     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4106     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4107                        DAG.getIntPtrConstant(0));
4108   } else {
4109     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4110                                     BitCounts, DAG.getIntPtrConstant(0));
4111     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4112   }
4113 }
4114
4115 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4116 /// bit-count for each 32-bit element from the operand.  The idea here is
4117 /// to split the vector into 16-bit elements, leverage the 16-bit count
4118 /// routine, and then combine the results.
4119 ///
4120 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4121 /// input    = [v0    v1    ] (vi: 32-bit elements)
4122 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4123 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4124 /// vrev: N0 = [k1 k0 k3 k2 ]
4125 ///            [k0 k1 k2 k3 ]
4126 ///       N1 =+[k1 k0 k3 k2 ]
4127 ///            [k0 k2 k1 k3 ]
4128 ///       N2 =+[k1 k3 k0 k2 ]
4129 ///            [k0    k2    k1    k3    ]
4130 /// Extended =+[k1    k3    k0    k2    ]
4131 ///            [k0    k2    ]
4132 /// Extracted=+[k1    k3    ]
4133 ///
4134 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4135   EVT VT = N->getValueType(0);
4136   SDLoc DL(N);
4137
4138   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4139
4140   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4141   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4142   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4143   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4144   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4145
4146   if (VT.is64BitVector()) {
4147     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4148     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4149                        DAG.getIntPtrConstant(0));
4150   } else {
4151     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4152                                     DAG.getIntPtrConstant(0));
4153     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4154   }
4155 }
4156
4157 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4158                           const ARMSubtarget *ST) {
4159   EVT VT = N->getValueType(0);
4160
4161   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4162   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4163           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4164          "Unexpected type for custom ctpop lowering");
4165
4166   if (VT.getVectorElementType() == MVT::i32)
4167     return lowerCTPOP32BitElements(N, DAG);
4168   else
4169     return lowerCTPOP16BitElements(N, DAG);
4170 }
4171
4172 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4173                           const ARMSubtarget *ST) {
4174   EVT VT = N->getValueType(0);
4175   SDLoc dl(N);
4176
4177   if (!VT.isVector())
4178     return SDValue();
4179
4180   // Lower vector shifts on NEON to use VSHL.
4181   assert(ST->hasNEON() && "unexpected vector shift");
4182
4183   // Left shifts translate directly to the vshiftu intrinsic.
4184   if (N->getOpcode() == ISD::SHL)
4185     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4186                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4187                        N->getOperand(0), N->getOperand(1));
4188
4189   assert((N->getOpcode() == ISD::SRA ||
4190           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4191
4192   // NEON uses the same intrinsics for both left and right shifts.  For
4193   // right shifts, the shift amounts are negative, so negate the vector of
4194   // shift amounts.
4195   EVT ShiftVT = N->getOperand(1).getValueType();
4196   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4197                                      getZeroVector(ShiftVT, DAG, dl),
4198                                      N->getOperand(1));
4199   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4200                              Intrinsic::arm_neon_vshifts :
4201                              Intrinsic::arm_neon_vshiftu);
4202   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4203                      DAG.getConstant(vshiftInt, MVT::i32),
4204                      N->getOperand(0), NegatedCount);
4205 }
4206
4207 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4208                                 const ARMSubtarget *ST) {
4209   EVT VT = N->getValueType(0);
4210   SDLoc dl(N);
4211
4212   // We can get here for a node like i32 = ISD::SHL i32, i64
4213   if (VT != MVT::i64)
4214     return SDValue();
4215
4216   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4217          "Unknown shift to lower!");
4218
4219   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4220   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4221       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4222     return SDValue();
4223
4224   // If we are in thumb mode, we don't have RRX.
4225   if (ST->isThumb1Only()) return SDValue();
4226
4227   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4228   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4229                            DAG.getConstant(0, MVT::i32));
4230   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4231                            DAG.getConstant(1, MVT::i32));
4232
4233   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4234   // captures the result into a carry flag.
4235   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4236   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4237
4238   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4239   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4240
4241   // Merge the pieces into a single i64 value.
4242  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4243 }
4244
4245 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4246   SDValue TmpOp0, TmpOp1;
4247   bool Invert = false;
4248   bool Swap = false;
4249   unsigned Opc = 0;
4250
4251   SDValue Op0 = Op.getOperand(0);
4252   SDValue Op1 = Op.getOperand(1);
4253   SDValue CC = Op.getOperand(2);
4254   EVT VT = Op.getValueType();
4255   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4256   SDLoc dl(Op);
4257
4258   if (Op.getOperand(1).getValueType().isFloatingPoint()) {
4259     switch (SetCCOpcode) {
4260     default: llvm_unreachable("Illegal FP comparison");
4261     case ISD::SETUNE:
4262     case ISD::SETNE:  Invert = true; // Fallthrough
4263     case ISD::SETOEQ:
4264     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4265     case ISD::SETOLT:
4266     case ISD::SETLT: Swap = true; // Fallthrough
4267     case ISD::SETOGT:
4268     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4269     case ISD::SETOLE:
4270     case ISD::SETLE:  Swap = true; // Fallthrough
4271     case ISD::SETOGE:
4272     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4273     case ISD::SETUGE: Swap = true; // Fallthrough
4274     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4275     case ISD::SETUGT: Swap = true; // Fallthrough
4276     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4277     case ISD::SETUEQ: Invert = true; // Fallthrough
4278     case ISD::SETONE:
4279       // Expand this to (OLT | OGT).
4280       TmpOp0 = Op0;
4281       TmpOp1 = Op1;
4282       Opc = ISD::OR;
4283       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4284       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
4285       break;
4286     case ISD::SETUO: Invert = true; // Fallthrough
4287     case ISD::SETO:
4288       // Expand this to (OLT | OGE).
4289       TmpOp0 = Op0;
4290       TmpOp1 = Op1;
4291       Opc = ISD::OR;
4292       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4293       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
4294       break;
4295     }
4296   } else {
4297     // Integer comparisons.
4298     switch (SetCCOpcode) {
4299     default: llvm_unreachable("Illegal integer comparison");
4300     case ISD::SETNE:  Invert = true;
4301     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4302     case ISD::SETLT:  Swap = true;
4303     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4304     case ISD::SETLE:  Swap = true;
4305     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4306     case ISD::SETULT: Swap = true;
4307     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4308     case ISD::SETULE: Swap = true;
4309     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4310     }
4311
4312     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4313     if (Opc == ARMISD::VCEQ) {
4314
4315       SDValue AndOp;
4316       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4317         AndOp = Op0;
4318       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4319         AndOp = Op1;
4320
4321       // Ignore bitconvert.
4322       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4323         AndOp = AndOp.getOperand(0);
4324
4325       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4326         Opc = ARMISD::VTST;
4327         Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
4328         Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4329         Invert = !Invert;
4330       }
4331     }
4332   }
4333
4334   if (Swap)
4335     std::swap(Op0, Op1);
4336
4337   // If one of the operands is a constant vector zero, attempt to fold the
4338   // comparison to a specialized compare-against-zero form.
4339   SDValue SingleOp;
4340   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4341     SingleOp = Op0;
4342   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4343     if (Opc == ARMISD::VCGE)
4344       Opc = ARMISD::VCLEZ;
4345     else if (Opc == ARMISD::VCGT)
4346       Opc = ARMISD::VCLTZ;
4347     SingleOp = Op1;
4348   }
4349
4350   SDValue Result;
4351   if (SingleOp.getNode()) {
4352     switch (Opc) {
4353     case ARMISD::VCEQ:
4354       Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4355     case ARMISD::VCGE:
4356       Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4357     case ARMISD::VCLEZ:
4358       Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4359     case ARMISD::VCGT:
4360       Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4361     case ARMISD::VCLTZ:
4362       Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4363     default:
4364       Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4365     }
4366   } else {
4367      Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4368   }
4369
4370   if (Invert)
4371     Result = DAG.getNOT(dl, Result, VT);
4372
4373   return Result;
4374 }
4375
4376 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4377 /// valid vector constant for a NEON instruction with a "modified immediate"
4378 /// operand (e.g., VMOV).  If so, return the encoded value.
4379 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4380                                  unsigned SplatBitSize, SelectionDAG &DAG,
4381                                  EVT &VT, bool is128Bits, NEONModImmType type) {
4382   unsigned OpCmode, Imm;
4383
4384   // SplatBitSize is set to the smallest size that splats the vector, so a
4385   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4386   // immediate instructions others than VMOV do not support the 8-bit encoding
4387   // of a zero vector, and the default encoding of zero is supposed to be the
4388   // 32-bit version.
4389   if (SplatBits == 0)
4390     SplatBitSize = 32;
4391
4392   switch (SplatBitSize) {
4393   case 8:
4394     if (type != VMOVModImm)
4395       return SDValue();
4396     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4397     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4398     OpCmode = 0xe;
4399     Imm = SplatBits;
4400     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4401     break;
4402
4403   case 16:
4404     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4405     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4406     if ((SplatBits & ~0xff) == 0) {
4407       // Value = 0x00nn: Op=x, Cmode=100x.
4408       OpCmode = 0x8;
4409       Imm = SplatBits;
4410       break;
4411     }
4412     if ((SplatBits & ~0xff00) == 0) {
4413       // Value = 0xnn00: Op=x, Cmode=101x.
4414       OpCmode = 0xa;
4415       Imm = SplatBits >> 8;
4416       break;
4417     }
4418     return SDValue();
4419
4420   case 32:
4421     // NEON's 32-bit VMOV supports splat values where:
4422     // * only one byte is nonzero, or
4423     // * the least significant byte is 0xff and the second byte is nonzero, or
4424     // * the least significant 2 bytes are 0xff and the third is nonzero.
4425     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4426     if ((SplatBits & ~0xff) == 0) {
4427       // Value = 0x000000nn: Op=x, Cmode=000x.
4428       OpCmode = 0;
4429       Imm = SplatBits;
4430       break;
4431     }
4432     if ((SplatBits & ~0xff00) == 0) {
4433       // Value = 0x0000nn00: Op=x, Cmode=001x.
4434       OpCmode = 0x2;
4435       Imm = SplatBits >> 8;
4436       break;
4437     }
4438     if ((SplatBits & ~0xff0000) == 0) {
4439       // Value = 0x00nn0000: Op=x, Cmode=010x.
4440       OpCmode = 0x4;
4441       Imm = SplatBits >> 16;
4442       break;
4443     }
4444     if ((SplatBits & ~0xff000000) == 0) {
4445       // Value = 0xnn000000: Op=x, Cmode=011x.
4446       OpCmode = 0x6;
4447       Imm = SplatBits >> 24;
4448       break;
4449     }
4450
4451     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4452     if (type == OtherModImm) return SDValue();
4453
4454     if ((SplatBits & ~0xffff) == 0 &&
4455         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4456       // Value = 0x0000nnff: Op=x, Cmode=1100.
4457       OpCmode = 0xc;
4458       Imm = SplatBits >> 8;
4459       break;
4460     }
4461
4462     if ((SplatBits & ~0xffffff) == 0 &&
4463         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4464       // Value = 0x00nnffff: Op=x, Cmode=1101.
4465       OpCmode = 0xd;
4466       Imm = SplatBits >> 16;
4467       break;
4468     }
4469
4470     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4471     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4472     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4473     // and fall through here to test for a valid 64-bit splat.  But, then the
4474     // caller would also need to check and handle the change in size.
4475     return SDValue();
4476
4477   case 64: {
4478     if (type != VMOVModImm)
4479       return SDValue();
4480     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4481     uint64_t BitMask = 0xff;
4482     uint64_t Val = 0;
4483     unsigned ImmMask = 1;
4484     Imm = 0;
4485     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4486       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4487         Val |= BitMask;
4488         Imm |= ImmMask;
4489       } else if ((SplatBits & BitMask) != 0) {
4490         return SDValue();
4491       }
4492       BitMask <<= 8;
4493       ImmMask <<= 1;
4494     }
4495     // Op=1, Cmode=1110.
4496     OpCmode = 0x1e;
4497     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4498     break;
4499   }
4500
4501   default:
4502     llvm_unreachable("unexpected size for isNEONModifiedImm");
4503   }
4504
4505   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4506   return DAG.getTargetConstant(EncodedVal, MVT::i32);
4507 }
4508
4509 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4510                                            const ARMSubtarget *ST) const {
4511   if (!ST->hasVFP3())
4512     return SDValue();
4513
4514   bool IsDouble = Op.getValueType() == MVT::f64;
4515   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4516
4517   // Try splatting with a VMOV.f32...
4518   APFloat FPVal = CFP->getValueAPF();
4519   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4520
4521   if (ImmVal != -1) {
4522     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4523       // We have code in place to select a valid ConstantFP already, no need to
4524       // do any mangling.
4525       return Op;
4526     }
4527
4528     // It's a float and we are trying to use NEON operations where
4529     // possible. Lower it to a splat followed by an extract.
4530     SDLoc DL(Op);
4531     SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4532     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4533                                       NewVal);
4534     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4535                        DAG.getConstant(0, MVT::i32));
4536   }
4537
4538   // The rest of our options are NEON only, make sure that's allowed before
4539   // proceeding..
4540   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4541     return SDValue();
4542
4543   EVT VMovVT;
4544   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4545
4546   // It wouldn't really be worth bothering for doubles except for one very
4547   // important value, which does happen to match: 0.0. So make sure we don't do
4548   // anything stupid.
4549   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4550     return SDValue();
4551
4552   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4553   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4554                                      false, VMOVModImm);
4555   if (NewVal != SDValue()) {
4556     SDLoc DL(Op);
4557     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4558                                       NewVal);
4559     if (IsDouble)
4560       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4561
4562     // It's a float: cast and extract a vector element.
4563     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4564                                        VecConstant);
4565     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4566                        DAG.getConstant(0, MVT::i32));
4567   }
4568
4569   // Finally, try a VMVN.i32
4570   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4571                              false, VMVNModImm);
4572   if (NewVal != SDValue()) {
4573     SDLoc DL(Op);
4574     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4575
4576     if (IsDouble)
4577       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4578
4579     // It's a float: cast and extract a vector element.
4580     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4581                                        VecConstant);
4582     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4583                        DAG.getConstant(0, MVT::i32));
4584   }
4585
4586   return SDValue();
4587 }
4588
4589 // check if an VEXT instruction can handle the shuffle mask when the
4590 // vector sources of the shuffle are the same.
4591 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4592   unsigned NumElts = VT.getVectorNumElements();
4593
4594   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4595   if (M[0] < 0)
4596     return false;
4597
4598   Imm = M[0];
4599
4600   // If this is a VEXT shuffle, the immediate value is the index of the first
4601   // element.  The other shuffle indices must be the successive elements after
4602   // the first one.
4603   unsigned ExpectedElt = Imm;
4604   for (unsigned i = 1; i < NumElts; ++i) {
4605     // Increment the expected index.  If it wraps around, just follow it
4606     // back to index zero and keep going.
4607     ++ExpectedElt;
4608     if (ExpectedElt == NumElts)
4609       ExpectedElt = 0;
4610
4611     if (M[i] < 0) continue; // ignore UNDEF indices
4612     if (ExpectedElt != static_cast<unsigned>(M[i]))
4613       return false;
4614   }
4615
4616   return true;
4617 }
4618
4619
4620 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4621                        bool &ReverseVEXT, unsigned &Imm) {
4622   unsigned NumElts = VT.getVectorNumElements();
4623   ReverseVEXT = false;
4624
4625   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4626   if (M[0] < 0)
4627     return false;
4628
4629   Imm = M[0];
4630
4631   // If this is a VEXT shuffle, the immediate value is the index of the first
4632   // element.  The other shuffle indices must be the successive elements after
4633   // the first one.
4634   unsigned ExpectedElt = Imm;
4635   for (unsigned i = 1; i < NumElts; ++i) {
4636     // Increment the expected index.  If it wraps around, it may still be
4637     // a VEXT but the source vectors must be swapped.
4638     ExpectedElt += 1;
4639     if (ExpectedElt == NumElts * 2) {
4640       ExpectedElt = 0;
4641       ReverseVEXT = true;
4642     }
4643
4644     if (M[i] < 0) continue; // ignore UNDEF indices
4645     if (ExpectedElt != static_cast<unsigned>(M[i]))
4646       return false;
4647   }
4648
4649   // Adjust the index value if the source operands will be swapped.
4650   if (ReverseVEXT)
4651     Imm -= NumElts;
4652
4653   return true;
4654 }
4655
4656 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4657 /// instruction with the specified blocksize.  (The order of the elements
4658 /// within each block of the vector is reversed.)
4659 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4660   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4661          "Only possible block sizes for VREV are: 16, 32, 64");
4662
4663   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4664   if (EltSz == 64)
4665     return false;
4666
4667   unsigned NumElts = VT.getVectorNumElements();
4668   unsigned BlockElts = M[0] + 1;
4669   // If the first shuffle index is UNDEF, be optimistic.
4670   if (M[0] < 0)
4671     BlockElts = BlockSize / EltSz;
4672
4673   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4674     return false;
4675
4676   for (unsigned i = 0; i < NumElts; ++i) {
4677     if (M[i] < 0) continue; // ignore UNDEF indices
4678     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4679       return false;
4680   }
4681
4682   return true;
4683 }
4684
4685 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4686   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4687   // range, then 0 is placed into the resulting vector. So pretty much any mask
4688   // of 8 elements can work here.
4689   return VT == MVT::v8i8 && M.size() == 8;
4690 }
4691
4692 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4693   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4694   if (EltSz == 64)
4695     return false;
4696
4697   unsigned NumElts = VT.getVectorNumElements();
4698   WhichResult = (M[0] == 0 ? 0 : 1);
4699   for (unsigned i = 0; i < NumElts; i += 2) {
4700     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4701         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4702       return false;
4703   }
4704   return true;
4705 }
4706
4707 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4708 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4709 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4710 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4711   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4712   if (EltSz == 64)
4713     return false;
4714
4715   unsigned NumElts = VT.getVectorNumElements();
4716   WhichResult = (M[0] == 0 ? 0 : 1);
4717   for (unsigned i = 0; i < NumElts; i += 2) {
4718     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4719         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4720       return false;
4721   }
4722   return true;
4723 }
4724
4725 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4726   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4727   if (EltSz == 64)
4728     return false;
4729
4730   unsigned NumElts = VT.getVectorNumElements();
4731   WhichResult = (M[0] == 0 ? 0 : 1);
4732   for (unsigned i = 0; i != NumElts; ++i) {
4733     if (M[i] < 0) continue; // ignore UNDEF indices
4734     if ((unsigned) M[i] != 2 * i + WhichResult)
4735       return false;
4736   }
4737
4738   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4739   if (VT.is64BitVector() && EltSz == 32)
4740     return false;
4741
4742   return true;
4743 }
4744
4745 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4746 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4747 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4748 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4749   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4750   if (EltSz == 64)
4751     return false;
4752
4753   unsigned Half = VT.getVectorNumElements() / 2;
4754   WhichResult = (M[0] == 0 ? 0 : 1);
4755   for (unsigned j = 0; j != 2; ++j) {
4756     unsigned Idx = WhichResult;
4757     for (unsigned i = 0; i != Half; ++i) {
4758       int MIdx = M[i + j * Half];
4759       if (MIdx >= 0 && (unsigned) MIdx != Idx)
4760         return false;
4761       Idx += 2;
4762     }
4763   }
4764
4765   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4766   if (VT.is64BitVector() && EltSz == 32)
4767     return false;
4768
4769   return true;
4770 }
4771
4772 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4773   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4774   if (EltSz == 64)
4775     return false;
4776
4777   unsigned NumElts = VT.getVectorNumElements();
4778   WhichResult = (M[0] == 0 ? 0 : 1);
4779   unsigned Idx = WhichResult * NumElts / 2;
4780   for (unsigned i = 0; i != NumElts; i += 2) {
4781     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4782         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4783       return false;
4784     Idx += 1;
4785   }
4786
4787   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4788   if (VT.is64BitVector() && EltSz == 32)
4789     return false;
4790
4791   return true;
4792 }
4793
4794 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4795 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4796 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4797 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4798   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4799   if (EltSz == 64)
4800     return false;
4801
4802   unsigned NumElts = VT.getVectorNumElements();
4803   WhichResult = (M[0] == 0 ? 0 : 1);
4804   unsigned Idx = WhichResult * NumElts / 2;
4805   for (unsigned i = 0; i != NumElts; i += 2) {
4806     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4807         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4808       return false;
4809     Idx += 1;
4810   }
4811
4812   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4813   if (VT.is64BitVector() && EltSz == 32)
4814     return false;
4815
4816   return true;
4817 }
4818
4819 /// \return true if this is a reverse operation on an vector.
4820 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4821   unsigned NumElts = VT.getVectorNumElements();
4822   // Make sure the mask has the right size.
4823   if (NumElts != M.size())
4824       return false;
4825
4826   // Look for <15, ..., 3, -1, 1, 0>.
4827   for (unsigned i = 0; i != NumElts; ++i)
4828     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4829       return false;
4830
4831   return true;
4832 }
4833
4834 // If N is an integer constant that can be moved into a register in one
4835 // instruction, return an SDValue of such a constant (will become a MOV
4836 // instruction).  Otherwise return null.
4837 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4838                                      const ARMSubtarget *ST, SDLoc dl) {
4839   uint64_t Val;
4840   if (!isa<ConstantSDNode>(N))
4841     return SDValue();
4842   Val = cast<ConstantSDNode>(N)->getZExtValue();
4843
4844   if (ST->isThumb1Only()) {
4845     if (Val <= 255 || ~Val <= 255)
4846       return DAG.getConstant(Val, MVT::i32);
4847   } else {
4848     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4849       return DAG.getConstant(Val, MVT::i32);
4850   }
4851   return SDValue();
4852 }
4853
4854 // If this is a case we can't handle, return null and let the default
4855 // expansion code take care of it.
4856 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4857                                              const ARMSubtarget *ST) const {
4858   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4859   SDLoc dl(Op);
4860   EVT VT = Op.getValueType();
4861
4862   APInt SplatBits, SplatUndef;
4863   unsigned SplatBitSize;
4864   bool HasAnyUndefs;
4865   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4866     if (SplatBitSize <= 64) {
4867       // Check if an immediate VMOV works.
4868       EVT VmovVT;
4869       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4870                                       SplatUndef.getZExtValue(), SplatBitSize,
4871                                       DAG, VmovVT, VT.is128BitVector(),
4872                                       VMOVModImm);
4873       if (Val.getNode()) {
4874         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4875         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4876       }
4877
4878       // Try an immediate VMVN.
4879       uint64_t NegatedImm = (~SplatBits).getZExtValue();
4880       Val = isNEONModifiedImm(NegatedImm,
4881                                       SplatUndef.getZExtValue(), SplatBitSize,
4882                                       DAG, VmovVT, VT.is128BitVector(),
4883                                       VMVNModImm);
4884       if (Val.getNode()) {
4885         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4886         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4887       }
4888
4889       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4890       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4891         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4892         if (ImmVal != -1) {
4893           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4894           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4895         }
4896       }
4897     }
4898   }
4899
4900   // Scan through the operands to see if only one value is used.
4901   //
4902   // As an optimisation, even if more than one value is used it may be more
4903   // profitable to splat with one value then change some lanes.
4904   //
4905   // Heuristically we decide to do this if the vector has a "dominant" value,
4906   // defined as splatted to more than half of the lanes.
4907   unsigned NumElts = VT.getVectorNumElements();
4908   bool isOnlyLowElement = true;
4909   bool usesOnlyOneValue = true;
4910   bool hasDominantValue = false;
4911   bool isConstant = true;
4912
4913   // Map of the number of times a particular SDValue appears in the
4914   // element list.
4915   DenseMap<SDValue, unsigned> ValueCounts;
4916   SDValue Value;
4917   for (unsigned i = 0; i < NumElts; ++i) {
4918     SDValue V = Op.getOperand(i);
4919     if (V.getOpcode() == ISD::UNDEF)
4920       continue;
4921     if (i > 0)
4922       isOnlyLowElement = false;
4923     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4924       isConstant = false;
4925
4926     ValueCounts.insert(std::make_pair(V, 0));
4927     unsigned &Count = ValueCounts[V];
4928
4929     // Is this value dominant? (takes up more than half of the lanes)
4930     if (++Count > (NumElts / 2)) {
4931       hasDominantValue = true;
4932       Value = V;
4933     }
4934   }
4935   if (ValueCounts.size() != 1)
4936     usesOnlyOneValue = false;
4937   if (!Value.getNode() && ValueCounts.size() > 0)
4938     Value = ValueCounts.begin()->first;
4939
4940   if (ValueCounts.size() == 0)
4941     return DAG.getUNDEF(VT);
4942
4943   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
4944   // Keep going if we are hitting this case.
4945   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
4946     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4947
4948   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4949
4950   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
4951   // i32 and try again.
4952   if (hasDominantValue && EltSize <= 32) {
4953     if (!isConstant) {
4954       SDValue N;
4955
4956       // If we are VDUPing a value that comes directly from a vector, that will
4957       // cause an unnecessary move to and from a GPR, where instead we could
4958       // just use VDUPLANE. We can only do this if the lane being extracted
4959       // is at a constant index, as the VDUP from lane instructions only have
4960       // constant-index forms.
4961       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4962           isa<ConstantSDNode>(Value->getOperand(1))) {
4963         // We need to create a new undef vector to use for the VDUPLANE if the
4964         // size of the vector from which we get the value is different than the
4965         // size of the vector that we need to create. We will insert the element
4966         // such that the register coalescer will remove unnecessary copies.
4967         if (VT != Value->getOperand(0).getValueType()) {
4968           ConstantSDNode *constIndex;
4969           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
4970           assert(constIndex && "The index is not a constant!");
4971           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
4972                              VT.getVectorNumElements();
4973           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4974                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
4975                         Value, DAG.getConstant(index, MVT::i32)),
4976                            DAG.getConstant(index, MVT::i32));
4977         } else
4978           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4979                         Value->getOperand(0), Value->getOperand(1));
4980       } else
4981         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4982
4983       if (!usesOnlyOneValue) {
4984         // The dominant value was splatted as 'N', but we now have to insert
4985         // all differing elements.
4986         for (unsigned I = 0; I < NumElts; ++I) {
4987           if (Op.getOperand(I) == Value)
4988             continue;
4989           SmallVector<SDValue, 3> Ops;
4990           Ops.push_back(N);
4991           Ops.push_back(Op.getOperand(I));
4992           Ops.push_back(DAG.getConstant(I, MVT::i32));
4993           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
4994         }
4995       }
4996       return N;
4997     }
4998     if (VT.getVectorElementType().isFloatingPoint()) {
4999       SmallVector<SDValue, 8> Ops;
5000       for (unsigned i = 0; i < NumElts; ++i)
5001         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5002                                   Op.getOperand(i)));
5003       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5004       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5005       Val = LowerBUILD_VECTOR(Val, DAG, ST);
5006       if (Val.getNode())
5007         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5008     }
5009     if (usesOnlyOneValue) {
5010       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5011       if (isConstant && Val.getNode())
5012         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5013     }
5014   }
5015
5016   // If all elements are constants and the case above didn't get hit, fall back
5017   // to the default expansion, which will generate a load from the constant
5018   // pool.
5019   if (isConstant)
5020     return SDValue();
5021
5022   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5023   if (NumElts >= 4) {
5024     SDValue shuffle = ReconstructShuffle(Op, DAG);
5025     if (shuffle != SDValue())
5026       return shuffle;
5027   }
5028
5029   // Vectors with 32- or 64-bit elements can be built by directly assigning
5030   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
5031   // will be legalized.
5032   if (EltSize >= 32) {
5033     // Do the expansion with floating-point types, since that is what the VFP
5034     // registers are defined to use, and since i64 is not legal.
5035     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5036     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5037     SmallVector<SDValue, 8> Ops;
5038     for (unsigned i = 0; i < NumElts; ++i)
5039       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5040     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5041     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5042   }
5043
5044   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5045   // know the default expansion would otherwise fall back on something even
5046   // worse. For a vector with one or two non-undef values, that's
5047   // scalar_to_vector for the elements followed by a shuffle (provided the
5048   // shuffle is valid for the target) and materialization element by element
5049   // on the stack followed by a load for everything else.
5050   if (!isConstant && !usesOnlyOneValue) {
5051     SDValue Vec = DAG.getUNDEF(VT);
5052     for (unsigned i = 0 ; i < NumElts; ++i) {
5053       SDValue V = Op.getOperand(i);
5054       if (V.getOpcode() == ISD::UNDEF)
5055         continue;
5056       SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
5057       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5058     }
5059     return Vec;
5060   }
5061
5062   return SDValue();
5063 }
5064
5065 // Gather data to see if the operation can be modelled as a
5066 // shuffle in combination with VEXTs.
5067 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5068                                               SelectionDAG &DAG) const {
5069   SDLoc dl(Op);
5070   EVT VT = Op.getValueType();
5071   unsigned NumElts = VT.getVectorNumElements();
5072
5073   SmallVector<SDValue, 2> SourceVecs;
5074   SmallVector<unsigned, 2> MinElts;
5075   SmallVector<unsigned, 2> MaxElts;
5076
5077   for (unsigned i = 0; i < NumElts; ++i) {
5078     SDValue V = Op.getOperand(i);
5079     if (V.getOpcode() == ISD::UNDEF)
5080       continue;
5081     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5082       // A shuffle can only come from building a vector from various
5083       // elements of other vectors.
5084       return SDValue();
5085     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5086                VT.getVectorElementType()) {
5087       // This code doesn't know how to handle shuffles where the vector
5088       // element types do not match (this happens because type legalization
5089       // promotes the return type of EXTRACT_VECTOR_ELT).
5090       // FIXME: It might be appropriate to extend this code to handle
5091       // mismatched types.
5092       return SDValue();
5093     }
5094
5095     // Record this extraction against the appropriate vector if possible...
5096     SDValue SourceVec = V.getOperand(0);
5097     // If the element number isn't a constant, we can't effectively
5098     // analyze what's going on.
5099     if (!isa<ConstantSDNode>(V.getOperand(1)))
5100       return SDValue();
5101     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5102     bool FoundSource = false;
5103     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5104       if (SourceVecs[j] == SourceVec) {
5105         if (MinElts[j] > EltNo)
5106           MinElts[j] = EltNo;
5107         if (MaxElts[j] < EltNo)
5108           MaxElts[j] = EltNo;
5109         FoundSource = true;
5110         break;
5111       }
5112     }
5113
5114     // Or record a new source if not...
5115     if (!FoundSource) {
5116       SourceVecs.push_back(SourceVec);
5117       MinElts.push_back(EltNo);
5118       MaxElts.push_back(EltNo);
5119     }
5120   }
5121
5122   // Currently only do something sane when at most two source vectors
5123   // involved.
5124   if (SourceVecs.size() > 2)
5125     return SDValue();
5126
5127   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5128   int VEXTOffsets[2] = {0, 0};
5129
5130   // This loop extracts the usage patterns of the source vectors
5131   // and prepares appropriate SDValues for a shuffle if possible.
5132   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5133     if (SourceVecs[i].getValueType() == VT) {
5134       // No VEXT necessary
5135       ShuffleSrcs[i] = SourceVecs[i];
5136       VEXTOffsets[i] = 0;
5137       continue;
5138     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5139       // It probably isn't worth padding out a smaller vector just to
5140       // break it down again in a shuffle.
5141       return SDValue();
5142     }
5143
5144     // Since only 64-bit and 128-bit vectors are legal on ARM and
5145     // we've eliminated the other cases...
5146     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5147            "unexpected vector sizes in ReconstructShuffle");
5148
5149     if (MaxElts[i] - MinElts[i] >= NumElts) {
5150       // Span too large for a VEXT to cope
5151       return SDValue();
5152     }
5153
5154     if (MinElts[i] >= NumElts) {
5155       // The extraction can just take the second half
5156       VEXTOffsets[i] = NumElts;
5157       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5158                                    SourceVecs[i],
5159                                    DAG.getIntPtrConstant(NumElts));
5160     } else if (MaxElts[i] < NumElts) {
5161       // The extraction can just take the first half
5162       VEXTOffsets[i] = 0;
5163       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5164                                    SourceVecs[i],
5165                                    DAG.getIntPtrConstant(0));
5166     } else {
5167       // An actual VEXT is needed
5168       VEXTOffsets[i] = MinElts[i];
5169       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5170                                      SourceVecs[i],
5171                                      DAG.getIntPtrConstant(0));
5172       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5173                                      SourceVecs[i],
5174                                      DAG.getIntPtrConstant(NumElts));
5175       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5176                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
5177     }
5178   }
5179
5180   SmallVector<int, 8> Mask;
5181
5182   for (unsigned i = 0; i < NumElts; ++i) {
5183     SDValue Entry = Op.getOperand(i);
5184     if (Entry.getOpcode() == ISD::UNDEF) {
5185       Mask.push_back(-1);
5186       continue;
5187     }
5188
5189     SDValue ExtractVec = Entry.getOperand(0);
5190     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5191                                           .getOperand(1))->getSExtValue();
5192     if (ExtractVec == SourceVecs[0]) {
5193       Mask.push_back(ExtractElt - VEXTOffsets[0]);
5194     } else {
5195       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5196     }
5197   }
5198
5199   // Final check before we try to produce nonsense...
5200   if (isShuffleMaskLegal(Mask, VT))
5201     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5202                                 &Mask[0]);
5203
5204   return SDValue();
5205 }
5206
5207 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5208 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5209 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5210 /// are assumed to be legal.
5211 bool
5212 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5213                                       EVT VT) const {
5214   if (VT.getVectorNumElements() == 4 &&
5215       (VT.is128BitVector() || VT.is64BitVector())) {
5216     unsigned PFIndexes[4];
5217     for (unsigned i = 0; i != 4; ++i) {
5218       if (M[i] < 0)
5219         PFIndexes[i] = 8;
5220       else
5221         PFIndexes[i] = M[i];
5222     }
5223
5224     // Compute the index in the perfect shuffle table.
5225     unsigned PFTableIndex =
5226       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5227     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5228     unsigned Cost = (PFEntry >> 30);
5229
5230     if (Cost <= 4)
5231       return true;
5232   }
5233
5234   bool ReverseVEXT;
5235   unsigned Imm, WhichResult;
5236
5237   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5238   return (EltSize >= 32 ||
5239           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5240           isVREVMask(M, VT, 64) ||
5241           isVREVMask(M, VT, 32) ||
5242           isVREVMask(M, VT, 16) ||
5243           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5244           isVTBLMask(M, VT) ||
5245           isVTRNMask(M, VT, WhichResult) ||
5246           isVUZPMask(M, VT, WhichResult) ||
5247           isVZIPMask(M, VT, WhichResult) ||
5248           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5249           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5250           isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5251           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5252 }
5253
5254 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5255 /// the specified operations to build the shuffle.
5256 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5257                                       SDValue RHS, SelectionDAG &DAG,
5258                                       SDLoc dl) {
5259   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5260   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5261   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5262
5263   enum {
5264     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5265     OP_VREV,
5266     OP_VDUP0,
5267     OP_VDUP1,
5268     OP_VDUP2,
5269     OP_VDUP3,
5270     OP_VEXT1,
5271     OP_VEXT2,
5272     OP_VEXT3,
5273     OP_VUZPL, // VUZP, left result
5274     OP_VUZPR, // VUZP, right result
5275     OP_VZIPL, // VZIP, left result
5276     OP_VZIPR, // VZIP, right result
5277     OP_VTRNL, // VTRN, left result
5278     OP_VTRNR  // VTRN, right result
5279   };
5280
5281   if (OpNum == OP_COPY) {
5282     if (LHSID == (1*9+2)*9+3) return LHS;
5283     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5284     return RHS;
5285   }
5286
5287   SDValue OpLHS, OpRHS;
5288   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5289   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5290   EVT VT = OpLHS.getValueType();
5291
5292   switch (OpNum) {
5293   default: llvm_unreachable("Unknown shuffle opcode!");
5294   case OP_VREV:
5295     // VREV divides the vector in half and swaps within the half.
5296     if (VT.getVectorElementType() == MVT::i32 ||
5297         VT.getVectorElementType() == MVT::f32)
5298       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5299     // vrev <4 x i16> -> VREV32
5300     if (VT.getVectorElementType() == MVT::i16)
5301       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5302     // vrev <4 x i8> -> VREV16
5303     assert(VT.getVectorElementType() == MVT::i8);
5304     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5305   case OP_VDUP0:
5306   case OP_VDUP1:
5307   case OP_VDUP2:
5308   case OP_VDUP3:
5309     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5310                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5311   case OP_VEXT1:
5312   case OP_VEXT2:
5313   case OP_VEXT3:
5314     return DAG.getNode(ARMISD::VEXT, dl, VT,
5315                        OpLHS, OpRHS,
5316                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5317   case OP_VUZPL:
5318   case OP_VUZPR:
5319     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5320                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5321   case OP_VZIPL:
5322   case OP_VZIPR:
5323     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5324                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5325   case OP_VTRNL:
5326   case OP_VTRNR:
5327     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5328                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5329   }
5330 }
5331
5332 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5333                                        ArrayRef<int> ShuffleMask,
5334                                        SelectionDAG &DAG) {
5335   // Check to see if we can use the VTBL instruction.
5336   SDValue V1 = Op.getOperand(0);
5337   SDValue V2 = Op.getOperand(1);
5338   SDLoc DL(Op);
5339
5340   SmallVector<SDValue, 8> VTBLMask;
5341   for (ArrayRef<int>::iterator
5342          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5343     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5344
5345   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5346     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5347                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5348
5349   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5350                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5351 }
5352
5353 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5354                                                       SelectionDAG &DAG) {
5355   SDLoc DL(Op);
5356   SDValue OpLHS = Op.getOperand(0);
5357   EVT VT = OpLHS.getValueType();
5358
5359   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5360          "Expect an v8i16/v16i8 type");
5361   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5362   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5363   // extract the first 8 bytes into the top double word and the last 8 bytes
5364   // into the bottom double word. The v8i16 case is similar.
5365   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5366   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5367                      DAG.getConstant(ExtractNum, MVT::i32));
5368 }
5369
5370 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5371   SDValue V1 = Op.getOperand(0);
5372   SDValue V2 = Op.getOperand(1);
5373   SDLoc dl(Op);
5374   EVT VT = Op.getValueType();
5375   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5376
5377   // Convert shuffles that are directly supported on NEON to target-specific
5378   // DAG nodes, instead of keeping them as shuffles and matching them again
5379   // during code selection.  This is more efficient and avoids the possibility
5380   // of inconsistencies between legalization and selection.
5381   // FIXME: floating-point vectors should be canonicalized to integer vectors
5382   // of the same time so that they get CSEd properly.
5383   ArrayRef<int> ShuffleMask = SVN->getMask();
5384
5385   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5386   if (EltSize <= 32) {
5387     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5388       int Lane = SVN->getSplatIndex();
5389       // If this is undef splat, generate it via "just" vdup, if possible.
5390       if (Lane == -1) Lane = 0;
5391
5392       // Test if V1 is a SCALAR_TO_VECTOR.
5393       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5394         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5395       }
5396       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5397       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5398       // reaches it).
5399       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5400           !isa<ConstantSDNode>(V1.getOperand(0))) {
5401         bool IsScalarToVector = true;
5402         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5403           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5404             IsScalarToVector = false;
5405             break;
5406           }
5407         if (IsScalarToVector)
5408           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5409       }
5410       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5411                          DAG.getConstant(Lane, MVT::i32));
5412     }
5413
5414     bool ReverseVEXT;
5415     unsigned Imm;
5416     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5417       if (ReverseVEXT)
5418         std::swap(V1, V2);
5419       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5420                          DAG.getConstant(Imm, MVT::i32));
5421     }
5422
5423     if (isVREVMask(ShuffleMask, VT, 64))
5424       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5425     if (isVREVMask(ShuffleMask, VT, 32))
5426       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5427     if (isVREVMask(ShuffleMask, VT, 16))
5428       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5429
5430     if (V2->getOpcode() == ISD::UNDEF &&
5431         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5432       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5433                          DAG.getConstant(Imm, MVT::i32));
5434     }
5435
5436     // Check for Neon shuffles that modify both input vectors in place.
5437     // If both results are used, i.e., if there are two shuffles with the same
5438     // source operands and with masks corresponding to both results of one of
5439     // these operations, DAG memoization will ensure that a single node is
5440     // used for both shuffles.
5441     unsigned WhichResult;
5442     if (isVTRNMask(ShuffleMask, VT, WhichResult))
5443       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5444                          V1, V2).getValue(WhichResult);
5445     if (isVUZPMask(ShuffleMask, VT, WhichResult))
5446       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5447                          V1, V2).getValue(WhichResult);
5448     if (isVZIPMask(ShuffleMask, VT, WhichResult))
5449       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5450                          V1, V2).getValue(WhichResult);
5451
5452     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5453       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5454                          V1, V1).getValue(WhichResult);
5455     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5456       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5457                          V1, V1).getValue(WhichResult);
5458     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5459       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5460                          V1, V1).getValue(WhichResult);
5461   }
5462
5463   // If the shuffle is not directly supported and it has 4 elements, use
5464   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5465   unsigned NumElts = VT.getVectorNumElements();
5466   if (NumElts == 4) {
5467     unsigned PFIndexes[4];
5468     for (unsigned i = 0; i != 4; ++i) {
5469       if (ShuffleMask[i] < 0)
5470         PFIndexes[i] = 8;
5471       else
5472         PFIndexes[i] = ShuffleMask[i];
5473     }
5474
5475     // Compute the index in the perfect shuffle table.
5476     unsigned PFTableIndex =
5477       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5478     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5479     unsigned Cost = (PFEntry >> 30);
5480
5481     if (Cost <= 4)
5482       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5483   }
5484
5485   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5486   if (EltSize >= 32) {
5487     // Do the expansion with floating-point types, since that is what the VFP
5488     // registers are defined to use, and since i64 is not legal.
5489     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5490     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5491     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5492     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5493     SmallVector<SDValue, 8> Ops;
5494     for (unsigned i = 0; i < NumElts; ++i) {
5495       if (ShuffleMask[i] < 0)
5496         Ops.push_back(DAG.getUNDEF(EltVT));
5497       else
5498         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5499                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
5500                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5501                                                   MVT::i32)));
5502     }
5503     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5504     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5505   }
5506
5507   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5508     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5509
5510   if (VT == MVT::v8i8) {
5511     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5512     if (NewOp.getNode())
5513       return NewOp;
5514   }
5515
5516   return SDValue();
5517 }
5518
5519 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5520   // INSERT_VECTOR_ELT is legal only for immediate indexes.
5521   SDValue Lane = Op.getOperand(2);
5522   if (!isa<ConstantSDNode>(Lane))
5523     return SDValue();
5524
5525   return Op;
5526 }
5527
5528 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5529   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5530   SDValue Lane = Op.getOperand(1);
5531   if (!isa<ConstantSDNode>(Lane))
5532     return SDValue();
5533
5534   SDValue Vec = Op.getOperand(0);
5535   if (Op.getValueType() == MVT::i32 &&
5536       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5537     SDLoc dl(Op);
5538     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5539   }
5540
5541   return Op;
5542 }
5543
5544 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5545   // The only time a CONCAT_VECTORS operation can have legal types is when
5546   // two 64-bit vectors are concatenated to a 128-bit vector.
5547   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5548          "unexpected CONCAT_VECTORS");
5549   SDLoc dl(Op);
5550   SDValue Val = DAG.getUNDEF(MVT::v2f64);
5551   SDValue Op0 = Op.getOperand(0);
5552   SDValue Op1 = Op.getOperand(1);
5553   if (Op0.getOpcode() != ISD::UNDEF)
5554     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5555                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5556                       DAG.getIntPtrConstant(0));
5557   if (Op1.getOpcode() != ISD::UNDEF)
5558     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5559                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5560                       DAG.getIntPtrConstant(1));
5561   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5562 }
5563
5564 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5565 /// element has been zero/sign-extended, depending on the isSigned parameter,
5566 /// from an integer type half its size.
5567 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5568                                    bool isSigned) {
5569   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5570   EVT VT = N->getValueType(0);
5571   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5572     SDNode *BVN = N->getOperand(0).getNode();
5573     if (BVN->getValueType(0) != MVT::v4i32 ||
5574         BVN->getOpcode() != ISD::BUILD_VECTOR)
5575       return false;
5576     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5577     unsigned HiElt = 1 - LoElt;
5578     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5579     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5580     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5581     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5582     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5583       return false;
5584     if (isSigned) {
5585       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5586           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5587         return true;
5588     } else {
5589       if (Hi0->isNullValue() && Hi1->isNullValue())
5590         return true;
5591     }
5592     return false;
5593   }
5594
5595   if (N->getOpcode() != ISD::BUILD_VECTOR)
5596     return false;
5597
5598   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5599     SDNode *Elt = N->getOperand(i).getNode();
5600     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5601       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5602       unsigned HalfSize = EltSize / 2;
5603       if (isSigned) {
5604         if (!isIntN(HalfSize, C->getSExtValue()))
5605           return false;
5606       } else {
5607         if (!isUIntN(HalfSize, C->getZExtValue()))
5608           return false;
5609       }
5610       continue;
5611     }
5612     return false;
5613   }
5614
5615   return true;
5616 }
5617
5618 /// isSignExtended - Check if a node is a vector value that is sign-extended
5619 /// or a constant BUILD_VECTOR with sign-extended elements.
5620 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5621   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5622     return true;
5623   if (isExtendedBUILD_VECTOR(N, DAG, true))
5624     return true;
5625   return false;
5626 }
5627
5628 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5629 /// or a constant BUILD_VECTOR with zero-extended elements.
5630 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5631   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5632     return true;
5633   if (isExtendedBUILD_VECTOR(N, DAG, false))
5634     return true;
5635   return false;
5636 }
5637
5638 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5639   if (OrigVT.getSizeInBits() >= 64)
5640     return OrigVT;
5641
5642   assert(OrigVT.isSimple() && "Expecting a simple value type");
5643
5644   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5645   switch (OrigSimpleTy) {
5646   default: llvm_unreachable("Unexpected Vector Type");
5647   case MVT::v2i8:
5648   case MVT::v2i16:
5649      return MVT::v2i32;
5650   case MVT::v4i8:
5651     return  MVT::v4i16;
5652   }
5653 }
5654
5655 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5656 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5657 /// We insert the required extension here to get the vector to fill a D register.
5658 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5659                                             const EVT &OrigTy,
5660                                             const EVT &ExtTy,
5661                                             unsigned ExtOpcode) {
5662   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5663   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5664   // 64-bits we need to insert a new extension so that it will be 64-bits.
5665   assert(ExtTy.is128BitVector() && "Unexpected extension size");
5666   if (OrigTy.getSizeInBits() >= 64)
5667     return N;
5668
5669   // Must extend size to at least 64 bits to be used as an operand for VMULL.
5670   EVT NewVT = getExtensionTo64Bits(OrigTy);
5671
5672   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5673 }
5674
5675 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5676 /// does not do any sign/zero extension. If the original vector is less
5677 /// than 64 bits, an appropriate extension will be added after the load to
5678 /// reach a total size of 64 bits. We have to add the extension separately
5679 /// because ARM does not have a sign/zero extending load for vectors.
5680 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5681   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5682
5683   // The load already has the right type.
5684   if (ExtendedTy == LD->getMemoryVT())
5685     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5686                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5687                 LD->isNonTemporal(), LD->isInvariant(),
5688                 LD->getAlignment());
5689
5690   // We need to create a zextload/sextload. We cannot just create a load
5691   // followed by a zext/zext node because LowerMUL is also run during normal
5692   // operation legalization where we can't create illegal types.
5693   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5694                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5695                         LD->getMemoryVT(), LD->isVolatile(),
5696                         LD->isNonTemporal(), LD->getAlignment());
5697 }
5698
5699 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5700 /// extending load, or BUILD_VECTOR with extended elements, return the
5701 /// unextended value. The unextended vector should be 64 bits so that it can
5702 /// be used as an operand to a VMULL instruction. If the original vector size
5703 /// before extension is less than 64 bits we add a an extension to resize
5704 /// the vector to 64 bits.
5705 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5706   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5707     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5708                                         N->getOperand(0)->getValueType(0),
5709                                         N->getValueType(0),
5710                                         N->getOpcode());
5711
5712   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5713     return SkipLoadExtensionForVMULL(LD, DAG);
5714
5715   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
5716   // have been legalized as a BITCAST from v4i32.
5717   if (N->getOpcode() == ISD::BITCAST) {
5718     SDNode *BVN = N->getOperand(0).getNode();
5719     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5720            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5721     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5722     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5723                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5724   }
5725   // Construct a new BUILD_VECTOR with elements truncated to half the size.
5726   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5727   EVT VT = N->getValueType(0);
5728   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5729   unsigned NumElts = VT.getVectorNumElements();
5730   MVT TruncVT = MVT::getIntegerVT(EltSize);
5731   SmallVector<SDValue, 8> Ops;
5732   for (unsigned i = 0; i != NumElts; ++i) {
5733     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5734     const APInt &CInt = C->getAPIntValue();
5735     // Element types smaller than 32 bits are not legal, so use i32 elements.
5736     // The values are implicitly truncated so sext vs. zext doesn't matter.
5737     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5738   }
5739   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5740                      MVT::getVectorVT(TruncVT, NumElts), Ops);
5741 }
5742
5743 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5744   unsigned Opcode = N->getOpcode();
5745   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5746     SDNode *N0 = N->getOperand(0).getNode();
5747     SDNode *N1 = N->getOperand(1).getNode();
5748     return N0->hasOneUse() && N1->hasOneUse() &&
5749       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5750   }
5751   return false;
5752 }
5753
5754 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5755   unsigned Opcode = N->getOpcode();
5756   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5757     SDNode *N0 = N->getOperand(0).getNode();
5758     SDNode *N1 = N->getOperand(1).getNode();
5759     return N0->hasOneUse() && N1->hasOneUse() &&
5760       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5761   }
5762   return false;
5763 }
5764
5765 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5766   // Multiplications are only custom-lowered for 128-bit vectors so that
5767   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
5768   EVT VT = Op.getValueType();
5769   assert(VT.is128BitVector() && VT.isInteger() &&
5770          "unexpected type for custom-lowering ISD::MUL");
5771   SDNode *N0 = Op.getOperand(0).getNode();
5772   SDNode *N1 = Op.getOperand(1).getNode();
5773   unsigned NewOpc = 0;
5774   bool isMLA = false;
5775   bool isN0SExt = isSignExtended(N0, DAG);
5776   bool isN1SExt = isSignExtended(N1, DAG);
5777   if (isN0SExt && isN1SExt)
5778     NewOpc = ARMISD::VMULLs;
5779   else {
5780     bool isN0ZExt = isZeroExtended(N0, DAG);
5781     bool isN1ZExt = isZeroExtended(N1, DAG);
5782     if (isN0ZExt && isN1ZExt)
5783       NewOpc = ARMISD::VMULLu;
5784     else if (isN1SExt || isN1ZExt) {
5785       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5786       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5787       if (isN1SExt && isAddSubSExt(N0, DAG)) {
5788         NewOpc = ARMISD::VMULLs;
5789         isMLA = true;
5790       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5791         NewOpc = ARMISD::VMULLu;
5792         isMLA = true;
5793       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5794         std::swap(N0, N1);
5795         NewOpc = ARMISD::VMULLu;
5796         isMLA = true;
5797       }
5798     }
5799
5800     if (!NewOpc) {
5801       if (VT == MVT::v2i64)
5802         // Fall through to expand this.  It is not legal.
5803         return SDValue();
5804       else
5805         // Other vector multiplications are legal.
5806         return Op;
5807     }
5808   }
5809
5810   // Legalize to a VMULL instruction.
5811   SDLoc DL(Op);
5812   SDValue Op0;
5813   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5814   if (!isMLA) {
5815     Op0 = SkipExtensionForVMULL(N0, DAG);
5816     assert(Op0.getValueType().is64BitVector() &&
5817            Op1.getValueType().is64BitVector() &&
5818            "unexpected types for extended operands to VMULL");
5819     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5820   }
5821
5822   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5823   // isel lowering to take advantage of no-stall back to back vmul + vmla.
5824   //   vmull q0, d4, d6
5825   //   vmlal q0, d5, d6
5826   // is faster than
5827   //   vaddl q0, d4, d5
5828   //   vmovl q1, d6
5829   //   vmul  q0, q0, q1
5830   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5831   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5832   EVT Op1VT = Op1.getValueType();
5833   return DAG.getNode(N0->getOpcode(), DL, VT,
5834                      DAG.getNode(NewOpc, DL, VT,
5835                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5836                      DAG.getNode(NewOpc, DL, VT,
5837                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5838 }
5839
5840 static SDValue
5841 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
5842   // Convert to float
5843   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5844   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5845   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5846   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5847   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5848   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5849   // Get reciprocal estimate.
5850   // float4 recip = vrecpeq_f32(yf);
5851   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5852                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5853   // Because char has a smaller range than uchar, we can actually get away
5854   // without any newton steps.  This requires that we use a weird bias
5855   // of 0xb000, however (again, this has been exhaustively tested).
5856   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5857   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5858   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5859   Y = DAG.getConstant(0xb000, MVT::i32);
5860   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5861   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5862   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5863   // Convert back to short.
5864   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5865   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5866   return X;
5867 }
5868
5869 static SDValue
5870 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
5871   SDValue N2;
5872   // Convert to float.
5873   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5874   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5875   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5876   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5877   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5878   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5879
5880   // Use reciprocal estimate and one refinement step.
5881   // float4 recip = vrecpeq_f32(yf);
5882   // recip *= vrecpsq_f32(yf, recip);
5883   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5884                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5885   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5886                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5887                    N1, N2);
5888   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5889   // Because short has a smaller range than ushort, we can actually get away
5890   // with only a single newton step.  This requires that we use a weird bias
5891   // of 89, however (again, this has been exhaustively tested).
5892   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5893   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5894   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5895   N1 = DAG.getConstant(0x89, MVT::i32);
5896   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5897   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5898   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5899   // Convert back to integer and return.
5900   // return vmovn_s32(vcvt_s32_f32(result));
5901   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5902   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5903   return N0;
5904 }
5905
5906 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5907   EVT VT = Op.getValueType();
5908   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5909          "unexpected type for custom-lowering ISD::SDIV");
5910
5911   SDLoc dl(Op);
5912   SDValue N0 = Op.getOperand(0);
5913   SDValue N1 = Op.getOperand(1);
5914   SDValue N2, N3;
5915
5916   if (VT == MVT::v8i8) {
5917     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5918     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5919
5920     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5921                      DAG.getIntPtrConstant(4));
5922     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5923                      DAG.getIntPtrConstant(4));
5924     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5925                      DAG.getIntPtrConstant(0));
5926     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5927                      DAG.getIntPtrConstant(0));
5928
5929     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5930     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5931
5932     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5933     N0 = LowerCONCAT_VECTORS(N0, DAG);
5934
5935     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5936     return N0;
5937   }
5938   return LowerSDIV_v4i16(N0, N1, dl, DAG);
5939 }
5940
5941 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5942   EVT VT = Op.getValueType();
5943   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5944          "unexpected type for custom-lowering ISD::UDIV");
5945
5946   SDLoc dl(Op);
5947   SDValue N0 = Op.getOperand(0);
5948   SDValue N1 = Op.getOperand(1);
5949   SDValue N2, N3;
5950
5951   if (VT == MVT::v8i8) {
5952     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5953     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5954
5955     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5956                      DAG.getIntPtrConstant(4));
5957     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5958                      DAG.getIntPtrConstant(4));
5959     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5960                      DAG.getIntPtrConstant(0));
5961     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5962                      DAG.getIntPtrConstant(0));
5963
5964     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5965     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5966
5967     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5968     N0 = LowerCONCAT_VECTORS(N0, DAG);
5969
5970     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5971                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5972                      N0);
5973     return N0;
5974   }
5975
5976   // v4i16 sdiv ... Convert to float.
5977   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5978   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5979   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5980   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5981   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5982   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5983
5984   // Use reciprocal estimate and two refinement steps.
5985   // float4 recip = vrecpeq_f32(yf);
5986   // recip *= vrecpsq_f32(yf, recip);
5987   // recip *= vrecpsq_f32(yf, recip);
5988   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5989                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5990   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5991                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5992                    BN1, N2);
5993   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5994   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5995                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5996                    BN1, N2);
5997   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5998   // Simply multiplying by the reciprocal estimate can leave us a few ulps
5999   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6000   // and that it will never cause us to return an answer too large).
6001   // float4 result = as_float4(as_int4(xf*recip) + 2);
6002   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6003   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6004   N1 = DAG.getConstant(2, MVT::i32);
6005   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6006   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6007   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6008   // Convert back to integer and return.
6009   // return vmovn_u32(vcvt_s32_f32(result));
6010   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6011   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6012   return N0;
6013 }
6014
6015 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6016   EVT VT = Op.getNode()->getValueType(0);
6017   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6018
6019   unsigned Opc;
6020   bool ExtraOp = false;
6021   switch (Op.getOpcode()) {
6022   default: llvm_unreachable("Invalid code");
6023   case ISD::ADDC: Opc = ARMISD::ADDC; break;
6024   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6025   case ISD::SUBC: Opc = ARMISD::SUBC; break;
6026   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6027   }
6028
6029   if (!ExtraOp)
6030     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6031                        Op.getOperand(1));
6032   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6033                      Op.getOperand(1), Op.getOperand(2));
6034 }
6035
6036 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6037   assert(Subtarget->isTargetDarwin());
6038
6039   // For iOS, we want to call an alternative entry point: __sincos_stret,
6040   // return values are passed via sret.
6041   SDLoc dl(Op);
6042   SDValue Arg = Op.getOperand(0);
6043   EVT ArgVT = Arg.getValueType();
6044   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6045
6046   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6047   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6048
6049   // Pair of floats / doubles used to pass the result.
6050   StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL);
6051
6052   // Create stack object for sret.
6053   const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
6054   const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
6055   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6056   SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
6057
6058   ArgListTy Args;
6059   ArgListEntry Entry;
6060
6061   Entry.Node = SRet;
6062   Entry.Ty = RetTy->getPointerTo();
6063   Entry.isSExt = false;
6064   Entry.isZExt = false;
6065   Entry.isSRet = true;
6066   Args.push_back(Entry);
6067
6068   Entry.Node = Arg;
6069   Entry.Ty = ArgTy;
6070   Entry.isSExt = false;
6071   Entry.isZExt = false;
6072   Args.push_back(Entry);
6073
6074   const char *LibcallName  = (ArgVT == MVT::f64)
6075   ? "__sincos_stret" : "__sincosf_stret";
6076   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
6077
6078   TargetLowering::CallLoweringInfo CLI(DAG);
6079   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6080     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6081                &Args, 0)
6082     .setDiscardResult();
6083
6084   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6085
6086   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6087                                 MachinePointerInfo(), false, false, false, 0);
6088
6089   // Address of cos field.
6090   SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
6091                             DAG.getIntPtrConstant(ArgVT.getStoreSize()));
6092   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6093                                 MachinePointerInfo(), false, false, false, 0);
6094
6095   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6096   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6097                      LoadSin.getValue(0), LoadCos.getValue(0));
6098 }
6099
6100 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6101   // Monotonic load/store is legal for all targets
6102   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6103     return Op;
6104
6105   // Acquire/Release load/store is not legal for targets without a
6106   // dmb or equivalent available.
6107   return SDValue();
6108 }
6109
6110 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6111                                     SmallVectorImpl<SDValue> &Results,
6112                                     SelectionDAG &DAG,
6113                                     const ARMSubtarget *Subtarget) {
6114   SDLoc DL(N);
6115   SDValue Cycles32, OutChain;
6116
6117   if (Subtarget->hasPerfMon()) {
6118     // Under Power Management extensions, the cycle-count is:
6119     //    mrc p15, #0, <Rt>, c9, c13, #0
6120     SDValue Ops[] = { N->getOperand(0), // Chain
6121                       DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
6122                       DAG.getConstant(15, MVT::i32),
6123                       DAG.getConstant(0, MVT::i32),
6124                       DAG.getConstant(9, MVT::i32),
6125                       DAG.getConstant(13, MVT::i32),
6126                       DAG.getConstant(0, MVT::i32)
6127     };
6128
6129     Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6130                            DAG.getVTList(MVT::i32, MVT::Other), Ops);
6131     OutChain = Cycles32.getValue(1);
6132   } else {
6133     // Intrinsic is defined to return 0 on unsupported platforms. Technically
6134     // there are older ARM CPUs that have implementation-specific ways of
6135     // obtaining this information (FIXME!).
6136     Cycles32 = DAG.getConstant(0, MVT::i32);
6137     OutChain = DAG.getEntryNode();
6138   }
6139
6140
6141   SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6142                                  Cycles32, DAG.getConstant(0, MVT::i32));
6143   Results.push_back(Cycles64);
6144   Results.push_back(OutChain);
6145 }
6146
6147 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6148   switch (Op.getOpcode()) {
6149   default: llvm_unreachable("Don't know how to custom lower this!");
6150   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6151   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6152   case ISD::GlobalAddress:
6153     switch (Subtarget->getTargetTriple().getObjectFormat()) {
6154     default: llvm_unreachable("unknown object format");
6155     case Triple::COFF:
6156       return LowerGlobalAddressWindows(Op, DAG);
6157     case Triple::ELF:
6158       return LowerGlobalAddressELF(Op, DAG);
6159     case Triple::MachO:
6160       return LowerGlobalAddressDarwin(Op, DAG);
6161     }
6162   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6163   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6164   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6165   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6166   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6167   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6168   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6169   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6170   case ISD::SINT_TO_FP:
6171   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6172   case ISD::FP_TO_SINT:
6173   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6174   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6175   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6176   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6177   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6178   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6179   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6180   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6181                                                                Subtarget);
6182   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6183   case ISD::SHL:
6184   case ISD::SRL:
6185   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6186   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6187   case ISD::SRL_PARTS:
6188   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6189   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6190   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6191   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6192   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6193   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6194   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6195   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6196   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6197   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6198   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6199   case ISD::MUL:           return LowerMUL(Op, DAG);
6200   case ISD::SDIV:          return LowerSDIV(Op, DAG);
6201   case ISD::UDIV:          return LowerUDIV(Op, DAG);
6202   case ISD::ADDC:
6203   case ISD::ADDE:
6204   case ISD::SUBC:
6205   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6206   case ISD::SADDO:
6207   case ISD::UADDO:
6208   case ISD::SSUBO:
6209   case ISD::USUBO:
6210     return LowerXALUO(Op, DAG);
6211   case ISD::ATOMIC_LOAD:
6212   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6213   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6214   case ISD::SDIVREM:
6215   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6216   }
6217 }
6218
6219 /// ReplaceNodeResults - Replace the results of node with an illegal result
6220 /// type with new values built out of custom code.
6221 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6222                                            SmallVectorImpl<SDValue>&Results,
6223                                            SelectionDAG &DAG) const {
6224   SDValue Res;
6225   switch (N->getOpcode()) {
6226   default:
6227     llvm_unreachable("Don't know how to custom expand this!");
6228   case ISD::BITCAST:
6229     Res = ExpandBITCAST(N, DAG);
6230     break;
6231   case ISD::SRL:
6232   case ISD::SRA:
6233     Res = Expand64BitShift(N, DAG, Subtarget);
6234     break;
6235   case ISD::READCYCLECOUNTER:
6236     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6237     return;
6238   }
6239   if (Res.getNode())
6240     Results.push_back(Res);
6241 }
6242
6243 //===----------------------------------------------------------------------===//
6244 //                           ARM Scheduler Hooks
6245 //===----------------------------------------------------------------------===//
6246
6247 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6248 /// registers the function context.
6249 void ARMTargetLowering::
6250 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6251                        MachineBasicBlock *DispatchBB, int FI) const {
6252   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6253   DebugLoc dl = MI->getDebugLoc();
6254   MachineFunction *MF = MBB->getParent();
6255   MachineRegisterInfo *MRI = &MF->getRegInfo();
6256   MachineConstantPool *MCP = MF->getConstantPool();
6257   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6258   const Function *F = MF->getFunction();
6259
6260   bool isThumb = Subtarget->isThumb();
6261   bool isThumb2 = Subtarget->isThumb2();
6262
6263   unsigned PCLabelId = AFI->createPICLabelUId();
6264   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6265   ARMConstantPoolValue *CPV =
6266     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6267   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6268
6269   const TargetRegisterClass *TRC = isThumb ?
6270     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6271     (const TargetRegisterClass*)&ARM::GPRRegClass;
6272
6273   // Grab constant pool and fixed stack memory operands.
6274   MachineMemOperand *CPMMO =
6275     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6276                              MachineMemOperand::MOLoad, 4, 4);
6277
6278   MachineMemOperand *FIMMOSt =
6279     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6280                              MachineMemOperand::MOStore, 4, 4);
6281
6282   // Load the address of the dispatch MBB into the jump buffer.
6283   if (isThumb2) {
6284     // Incoming value: jbuf
6285     //   ldr.n  r5, LCPI1_1
6286     //   orr    r5, r5, #1
6287     //   add    r5, pc
6288     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6289     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6290     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6291                    .addConstantPoolIndex(CPI)
6292                    .addMemOperand(CPMMO));
6293     // Set the low bit because of thumb mode.
6294     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6295     AddDefaultCC(
6296       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6297                      .addReg(NewVReg1, RegState::Kill)
6298                      .addImm(0x01)));
6299     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6300     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6301       .addReg(NewVReg2, RegState::Kill)
6302       .addImm(PCLabelId);
6303     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6304                    .addReg(NewVReg3, RegState::Kill)
6305                    .addFrameIndex(FI)
6306                    .addImm(36)  // &jbuf[1] :: pc
6307                    .addMemOperand(FIMMOSt));
6308   } else if (isThumb) {
6309     // Incoming value: jbuf
6310     //   ldr.n  r1, LCPI1_4
6311     //   add    r1, pc
6312     //   mov    r2, #1
6313     //   orrs   r1, r2
6314     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6315     //   str    r1, [r2]
6316     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6317     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6318                    .addConstantPoolIndex(CPI)
6319                    .addMemOperand(CPMMO));
6320     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6321     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6322       .addReg(NewVReg1, RegState::Kill)
6323       .addImm(PCLabelId);
6324     // Set the low bit because of thumb mode.
6325     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6326     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6327                    .addReg(ARM::CPSR, RegState::Define)
6328                    .addImm(1));
6329     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6330     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6331                    .addReg(ARM::CPSR, RegState::Define)
6332                    .addReg(NewVReg2, RegState::Kill)
6333                    .addReg(NewVReg3, RegState::Kill));
6334     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6335     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6336                    .addFrameIndex(FI)
6337                    .addImm(36)); // &jbuf[1] :: pc
6338     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6339                    .addReg(NewVReg4, RegState::Kill)
6340                    .addReg(NewVReg5, RegState::Kill)
6341                    .addImm(0)
6342                    .addMemOperand(FIMMOSt));
6343   } else {
6344     // Incoming value: jbuf
6345     //   ldr  r1, LCPI1_1
6346     //   add  r1, pc, r1
6347     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6348     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6349     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6350                    .addConstantPoolIndex(CPI)
6351                    .addImm(0)
6352                    .addMemOperand(CPMMO));
6353     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6354     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6355                    .addReg(NewVReg1, RegState::Kill)
6356                    .addImm(PCLabelId));
6357     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6358                    .addReg(NewVReg2, RegState::Kill)
6359                    .addFrameIndex(FI)
6360                    .addImm(36)  // &jbuf[1] :: pc
6361                    .addMemOperand(FIMMOSt));
6362   }
6363 }
6364
6365 MachineBasicBlock *ARMTargetLowering::
6366 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6367   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6368   DebugLoc dl = MI->getDebugLoc();
6369   MachineFunction *MF = MBB->getParent();
6370   MachineRegisterInfo *MRI = &MF->getRegInfo();
6371   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6372   MachineFrameInfo *MFI = MF->getFrameInfo();
6373   int FI = MFI->getFunctionContextIndex();
6374
6375   const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6376     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6377     (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6378
6379   // Get a mapping of the call site numbers to all of the landing pads they're
6380   // associated with.
6381   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6382   unsigned MaxCSNum = 0;
6383   MachineModuleInfo &MMI = MF->getMMI();
6384   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6385        ++BB) {
6386     if (!BB->isLandingPad()) continue;
6387
6388     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6389     // pad.
6390     for (MachineBasicBlock::iterator
6391            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6392       if (!II->isEHLabel()) continue;
6393
6394       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6395       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6396
6397       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6398       for (SmallVectorImpl<unsigned>::iterator
6399              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6400            CSI != CSE; ++CSI) {
6401         CallSiteNumToLPad[*CSI].push_back(BB);
6402         MaxCSNum = std::max(MaxCSNum, *CSI);
6403       }
6404       break;
6405     }
6406   }
6407
6408   // Get an ordered list of the machine basic blocks for the jump table.
6409   std::vector<MachineBasicBlock*> LPadList;
6410   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6411   LPadList.reserve(CallSiteNumToLPad.size());
6412   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6413     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6414     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6415            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6416       LPadList.push_back(*II);
6417       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6418     }
6419   }
6420
6421   assert(!LPadList.empty() &&
6422          "No landing pad destinations for the dispatch jump table!");
6423
6424   // Create the jump table and associated information.
6425   MachineJumpTableInfo *JTI =
6426     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6427   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6428   unsigned UId = AFI->createJumpTableUId();
6429   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6430
6431   // Create the MBBs for the dispatch code.
6432
6433   // Shove the dispatch's address into the return slot in the function context.
6434   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6435   DispatchBB->setIsLandingPad();
6436
6437   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6438   unsigned trap_opcode;
6439   if (Subtarget->isThumb())
6440     trap_opcode = ARM::tTRAP;
6441   else
6442     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6443
6444   BuildMI(TrapBB, dl, TII->get(trap_opcode));
6445   DispatchBB->addSuccessor(TrapBB);
6446
6447   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6448   DispatchBB->addSuccessor(DispContBB);
6449
6450   // Insert and MBBs.
6451   MF->insert(MF->end(), DispatchBB);
6452   MF->insert(MF->end(), DispContBB);
6453   MF->insert(MF->end(), TrapBB);
6454
6455   // Insert code into the entry block that creates and registers the function
6456   // context.
6457   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6458
6459   MachineMemOperand *FIMMOLd =
6460     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6461                              MachineMemOperand::MOLoad |
6462                              MachineMemOperand::MOVolatile, 4, 4);
6463
6464   MachineInstrBuilder MIB;
6465   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6466
6467   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6468   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6469
6470   // Add a register mask with no preserved registers.  This results in all
6471   // registers being marked as clobbered.
6472   MIB.addRegMask(RI.getNoPreservedMask());
6473
6474   unsigned NumLPads = LPadList.size();
6475   if (Subtarget->isThumb2()) {
6476     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6477     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6478                    .addFrameIndex(FI)
6479                    .addImm(4)
6480                    .addMemOperand(FIMMOLd));
6481
6482     if (NumLPads < 256) {
6483       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6484                      .addReg(NewVReg1)
6485                      .addImm(LPadList.size()));
6486     } else {
6487       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6488       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6489                      .addImm(NumLPads & 0xFFFF));
6490
6491       unsigned VReg2 = VReg1;
6492       if ((NumLPads & 0xFFFF0000) != 0) {
6493         VReg2 = MRI->createVirtualRegister(TRC);
6494         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6495                        .addReg(VReg1)
6496                        .addImm(NumLPads >> 16));
6497       }
6498
6499       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6500                      .addReg(NewVReg1)
6501                      .addReg(VReg2));
6502     }
6503
6504     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6505       .addMBB(TrapBB)
6506       .addImm(ARMCC::HI)
6507       .addReg(ARM::CPSR);
6508
6509     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6510     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6511                    .addJumpTableIndex(MJTI)
6512                    .addImm(UId));
6513
6514     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6515     AddDefaultCC(
6516       AddDefaultPred(
6517         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6518         .addReg(NewVReg3, RegState::Kill)
6519         .addReg(NewVReg1)
6520         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6521
6522     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6523       .addReg(NewVReg4, RegState::Kill)
6524       .addReg(NewVReg1)
6525       .addJumpTableIndex(MJTI)
6526       .addImm(UId);
6527   } else if (Subtarget->isThumb()) {
6528     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6529     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6530                    .addFrameIndex(FI)
6531                    .addImm(1)
6532                    .addMemOperand(FIMMOLd));
6533
6534     if (NumLPads < 256) {
6535       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6536                      .addReg(NewVReg1)
6537                      .addImm(NumLPads));
6538     } else {
6539       MachineConstantPool *ConstantPool = MF->getConstantPool();
6540       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6541       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6542
6543       // MachineConstantPool wants an explicit alignment.
6544       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6545       if (Align == 0)
6546         Align = getDataLayout()->getTypeAllocSize(C->getType());
6547       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6548
6549       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6550       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6551                      .addReg(VReg1, RegState::Define)
6552                      .addConstantPoolIndex(Idx));
6553       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6554                      .addReg(NewVReg1)
6555                      .addReg(VReg1));
6556     }
6557
6558     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6559       .addMBB(TrapBB)
6560       .addImm(ARMCC::HI)
6561       .addReg(ARM::CPSR);
6562
6563     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6564     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6565                    .addReg(ARM::CPSR, RegState::Define)
6566                    .addReg(NewVReg1)
6567                    .addImm(2));
6568
6569     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6570     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6571                    .addJumpTableIndex(MJTI)
6572                    .addImm(UId));
6573
6574     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6575     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6576                    .addReg(ARM::CPSR, RegState::Define)
6577                    .addReg(NewVReg2, RegState::Kill)
6578                    .addReg(NewVReg3));
6579
6580     MachineMemOperand *JTMMOLd =
6581       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6582                                MachineMemOperand::MOLoad, 4, 4);
6583
6584     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6585     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6586                    .addReg(NewVReg4, RegState::Kill)
6587                    .addImm(0)
6588                    .addMemOperand(JTMMOLd));
6589
6590     unsigned NewVReg6 = NewVReg5;
6591     if (RelocM == Reloc::PIC_) {
6592       NewVReg6 = MRI->createVirtualRegister(TRC);
6593       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6594                      .addReg(ARM::CPSR, RegState::Define)
6595                      .addReg(NewVReg5, RegState::Kill)
6596                      .addReg(NewVReg3));
6597     }
6598
6599     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6600       .addReg(NewVReg6, RegState::Kill)
6601       .addJumpTableIndex(MJTI)
6602       .addImm(UId);
6603   } else {
6604     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6605     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6606                    .addFrameIndex(FI)
6607                    .addImm(4)
6608                    .addMemOperand(FIMMOLd));
6609
6610     if (NumLPads < 256) {
6611       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6612                      .addReg(NewVReg1)
6613                      .addImm(NumLPads));
6614     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6615       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6616       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6617                      .addImm(NumLPads & 0xFFFF));
6618
6619       unsigned VReg2 = VReg1;
6620       if ((NumLPads & 0xFFFF0000) != 0) {
6621         VReg2 = MRI->createVirtualRegister(TRC);
6622         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6623                        .addReg(VReg1)
6624                        .addImm(NumLPads >> 16));
6625       }
6626
6627       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6628                      .addReg(NewVReg1)
6629                      .addReg(VReg2));
6630     } else {
6631       MachineConstantPool *ConstantPool = MF->getConstantPool();
6632       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6633       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6634
6635       // MachineConstantPool wants an explicit alignment.
6636       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6637       if (Align == 0)
6638         Align = getDataLayout()->getTypeAllocSize(C->getType());
6639       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6640
6641       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6642       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6643                      .addReg(VReg1, RegState::Define)
6644                      .addConstantPoolIndex(Idx)
6645                      .addImm(0));
6646       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6647                      .addReg(NewVReg1)
6648                      .addReg(VReg1, RegState::Kill));
6649     }
6650
6651     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6652       .addMBB(TrapBB)
6653       .addImm(ARMCC::HI)
6654       .addReg(ARM::CPSR);
6655
6656     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6657     AddDefaultCC(
6658       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6659                      .addReg(NewVReg1)
6660                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6661     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6662     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6663                    .addJumpTableIndex(MJTI)
6664                    .addImm(UId));
6665
6666     MachineMemOperand *JTMMOLd =
6667       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6668                                MachineMemOperand::MOLoad, 4, 4);
6669     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6670     AddDefaultPred(
6671       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6672       .addReg(NewVReg3, RegState::Kill)
6673       .addReg(NewVReg4)
6674       .addImm(0)
6675       .addMemOperand(JTMMOLd));
6676
6677     if (RelocM == Reloc::PIC_) {
6678       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6679         .addReg(NewVReg5, RegState::Kill)
6680         .addReg(NewVReg4)
6681         .addJumpTableIndex(MJTI)
6682         .addImm(UId);
6683     } else {
6684       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6685         .addReg(NewVReg5, RegState::Kill)
6686         .addJumpTableIndex(MJTI)
6687         .addImm(UId);
6688     }
6689   }
6690
6691   // Add the jump table entries as successors to the MBB.
6692   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6693   for (std::vector<MachineBasicBlock*>::iterator
6694          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6695     MachineBasicBlock *CurMBB = *I;
6696     if (SeenMBBs.insert(CurMBB))
6697       DispContBB->addSuccessor(CurMBB);
6698   }
6699
6700   // N.B. the order the invoke BBs are processed in doesn't matter here.
6701   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
6702   SmallVector<MachineBasicBlock*, 64> MBBLPads;
6703   for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6704          I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6705     MachineBasicBlock *BB = *I;
6706
6707     // Remove the landing pad successor from the invoke block and replace it
6708     // with the new dispatch block.
6709     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6710                                                   BB->succ_end());
6711     while (!Successors.empty()) {
6712       MachineBasicBlock *SMBB = Successors.pop_back_val();
6713       if (SMBB->isLandingPad()) {
6714         BB->removeSuccessor(SMBB);
6715         MBBLPads.push_back(SMBB);
6716       }
6717     }
6718
6719     BB->addSuccessor(DispatchBB);
6720
6721     // Find the invoke call and mark all of the callee-saved registers as
6722     // 'implicit defined' so that they're spilled. This prevents code from
6723     // moving instructions to before the EH block, where they will never be
6724     // executed.
6725     for (MachineBasicBlock::reverse_iterator
6726            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6727       if (!II->isCall()) continue;
6728
6729       DenseMap<unsigned, bool> DefRegs;
6730       for (MachineInstr::mop_iterator
6731              OI = II->operands_begin(), OE = II->operands_end();
6732            OI != OE; ++OI) {
6733         if (!OI->isReg()) continue;
6734         DefRegs[OI->getReg()] = true;
6735       }
6736
6737       MachineInstrBuilder MIB(*MF, &*II);
6738
6739       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6740         unsigned Reg = SavedRegs[i];
6741         if (Subtarget->isThumb2() &&
6742             !ARM::tGPRRegClass.contains(Reg) &&
6743             !ARM::hGPRRegClass.contains(Reg))
6744           continue;
6745         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6746           continue;
6747         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6748           continue;
6749         if (!DefRegs[Reg])
6750           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6751       }
6752
6753       break;
6754     }
6755   }
6756
6757   // Mark all former landing pads as non-landing pads. The dispatch is the only
6758   // landing pad now.
6759   for (SmallVectorImpl<MachineBasicBlock*>::iterator
6760          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6761     (*I)->setIsLandingPad(false);
6762
6763   // The instruction is gone now.
6764   MI->eraseFromParent();
6765
6766   return MBB;
6767 }
6768
6769 static
6770 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6771   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6772        E = MBB->succ_end(); I != E; ++I)
6773     if (*I != Succ)
6774       return *I;
6775   llvm_unreachable("Expecting a BB with two successors!");
6776 }
6777
6778 /// Return the load opcode for a given load size. If load size >= 8,
6779 /// neon opcode will be returned.
6780 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
6781   if (LdSize >= 8)
6782     return LdSize == 16 ? ARM::VLD1q32wb_fixed
6783                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
6784   if (IsThumb1)
6785     return LdSize == 4 ? ARM::tLDRi
6786                        : LdSize == 2 ? ARM::tLDRHi
6787                                      : LdSize == 1 ? ARM::tLDRBi : 0;
6788   if (IsThumb2)
6789     return LdSize == 4 ? ARM::t2LDR_POST
6790                        : LdSize == 2 ? ARM::t2LDRH_POST
6791                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
6792   return LdSize == 4 ? ARM::LDR_POST_IMM
6793                      : LdSize == 2 ? ARM::LDRH_POST
6794                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
6795 }
6796
6797 /// Return the store opcode for a given store size. If store size >= 8,
6798 /// neon opcode will be returned.
6799 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
6800   if (StSize >= 8)
6801     return StSize == 16 ? ARM::VST1q32wb_fixed
6802                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
6803   if (IsThumb1)
6804     return StSize == 4 ? ARM::tSTRi
6805                        : StSize == 2 ? ARM::tSTRHi
6806                                      : StSize == 1 ? ARM::tSTRBi : 0;
6807   if (IsThumb2)
6808     return StSize == 4 ? ARM::t2STR_POST
6809                        : StSize == 2 ? ARM::t2STRH_POST
6810                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
6811   return StSize == 4 ? ARM::STR_POST_IMM
6812                      : StSize == 2 ? ARM::STRH_POST
6813                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
6814 }
6815
6816 /// Emit a post-increment load operation with given size. The instructions
6817 /// will be added to BB at Pos.
6818 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
6819                        const TargetInstrInfo *TII, DebugLoc dl,
6820                        unsigned LdSize, unsigned Data, unsigned AddrIn,
6821                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6822   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
6823   assert(LdOpc != 0 && "Should have a load opcode");
6824   if (LdSize >= 8) {
6825     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6826                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6827                        .addImm(0));
6828   } else if (IsThumb1) {
6829     // load + update AddrIn
6830     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6831                        .addReg(AddrIn).addImm(0));
6832     MachineInstrBuilder MIB =
6833         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6834     MIB = AddDefaultT1CC(MIB);
6835     MIB.addReg(AddrIn).addImm(LdSize);
6836     AddDefaultPred(MIB);
6837   } else if (IsThumb2) {
6838     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6839                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6840                        .addImm(LdSize));
6841   } else { // arm
6842     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6843                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6844                        .addReg(0).addImm(LdSize));
6845   }
6846 }
6847
6848 /// Emit a post-increment store operation with given size. The instructions
6849 /// will be added to BB at Pos.
6850 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
6851                        const TargetInstrInfo *TII, DebugLoc dl,
6852                        unsigned StSize, unsigned Data, unsigned AddrIn,
6853                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6854   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
6855   assert(StOpc != 0 && "Should have a store opcode");
6856   if (StSize >= 8) {
6857     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6858                        .addReg(AddrIn).addImm(0).addReg(Data));
6859   } else if (IsThumb1) {
6860     // store + update AddrIn
6861     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
6862                        .addReg(AddrIn).addImm(0));
6863     MachineInstrBuilder MIB =
6864         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6865     MIB = AddDefaultT1CC(MIB);
6866     MIB.addReg(AddrIn).addImm(StSize);
6867     AddDefaultPred(MIB);
6868   } else if (IsThumb2) {
6869     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6870                        .addReg(Data).addReg(AddrIn).addImm(StSize));
6871   } else { // arm
6872     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6873                        .addReg(Data).addReg(AddrIn).addReg(0)
6874                        .addImm(StSize));
6875   }
6876 }
6877
6878 MachineBasicBlock *
6879 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
6880                                    MachineBasicBlock *BB) const {
6881   // This pseudo instruction has 3 operands: dst, src, size
6882   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
6883   // Otherwise, we will generate unrolled scalar copies.
6884   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6885   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6886   MachineFunction::iterator It = BB;
6887   ++It;
6888
6889   unsigned dest = MI->getOperand(0).getReg();
6890   unsigned src = MI->getOperand(1).getReg();
6891   unsigned SizeVal = MI->getOperand(2).getImm();
6892   unsigned Align = MI->getOperand(3).getImm();
6893   DebugLoc dl = MI->getDebugLoc();
6894
6895   MachineFunction *MF = BB->getParent();
6896   MachineRegisterInfo &MRI = MF->getRegInfo();
6897   unsigned UnitSize = 0;
6898   const TargetRegisterClass *TRC = nullptr;
6899   const TargetRegisterClass *VecTRC = nullptr;
6900
6901   bool IsThumb1 = Subtarget->isThumb1Only();
6902   bool IsThumb2 = Subtarget->isThumb2();
6903
6904   if (Align & 1) {
6905     UnitSize = 1;
6906   } else if (Align & 2) {
6907     UnitSize = 2;
6908   } else {
6909     // Check whether we can use NEON instructions.
6910     if (!MF->getFunction()->getAttributes().
6911           hasAttribute(AttributeSet::FunctionIndex,
6912                        Attribute::NoImplicitFloat) &&
6913         Subtarget->hasNEON()) {
6914       if ((Align % 16 == 0) && SizeVal >= 16)
6915         UnitSize = 16;
6916       else if ((Align % 8 == 0) && SizeVal >= 8)
6917         UnitSize = 8;
6918     }
6919     // Can't use NEON instructions.
6920     if (UnitSize == 0)
6921       UnitSize = 4;
6922   }
6923
6924   // Select the correct opcode and register class for unit size load/store
6925   bool IsNeon = UnitSize >= 8;
6926   TRC = (IsThumb1 || IsThumb2) ? (const TargetRegisterClass *)&ARM::tGPRRegClass
6927                                : (const TargetRegisterClass *)&ARM::GPRRegClass;
6928   if (IsNeon)
6929     VecTRC = UnitSize == 16
6930                  ? (const TargetRegisterClass *)&ARM::DPairRegClass
6931                  : UnitSize == 8
6932                        ? (const TargetRegisterClass *)&ARM::DPRRegClass
6933                        : nullptr;
6934
6935   unsigned BytesLeft = SizeVal % UnitSize;
6936   unsigned LoopSize = SizeVal - BytesLeft;
6937
6938   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
6939     // Use LDR and STR to copy.
6940     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
6941     // [destOut] = STR_POST(scratch, destIn, UnitSize)
6942     unsigned srcIn = src;
6943     unsigned destIn = dest;
6944     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
6945       unsigned srcOut = MRI.createVirtualRegister(TRC);
6946       unsigned destOut = MRI.createVirtualRegister(TRC);
6947       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
6948       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
6949                  IsThumb1, IsThumb2);
6950       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
6951                  IsThumb1, IsThumb2);
6952       srcIn = srcOut;
6953       destIn = destOut;
6954     }
6955
6956     // Handle the leftover bytes with LDRB and STRB.
6957     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
6958     // [destOut] = STRB_POST(scratch, destIn, 1)
6959     for (unsigned i = 0; i < BytesLeft; i++) {
6960       unsigned srcOut = MRI.createVirtualRegister(TRC);
6961       unsigned destOut = MRI.createVirtualRegister(TRC);
6962       unsigned scratch = MRI.createVirtualRegister(TRC);
6963       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
6964                  IsThumb1, IsThumb2);
6965       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
6966                  IsThumb1, IsThumb2);
6967       srcIn = srcOut;
6968       destIn = destOut;
6969     }
6970     MI->eraseFromParent();   // The instruction is gone now.
6971     return BB;
6972   }
6973
6974   // Expand the pseudo op to a loop.
6975   // thisMBB:
6976   //   ...
6977   //   movw varEnd, # --> with thumb2
6978   //   movt varEnd, #
6979   //   ldrcp varEnd, idx --> without thumb2
6980   //   fallthrough --> loopMBB
6981   // loopMBB:
6982   //   PHI varPhi, varEnd, varLoop
6983   //   PHI srcPhi, src, srcLoop
6984   //   PHI destPhi, dst, destLoop
6985   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6986   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
6987   //   subs varLoop, varPhi, #UnitSize
6988   //   bne loopMBB
6989   //   fallthrough --> exitMBB
6990   // exitMBB:
6991   //   epilogue to handle left-over bytes
6992   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
6993   //   [destOut] = STRB_POST(scratch, destLoop, 1)
6994   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6995   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6996   MF->insert(It, loopMBB);
6997   MF->insert(It, exitMBB);
6998
6999   // Transfer the remainder of BB and its successor edges to exitMBB.
7000   exitMBB->splice(exitMBB->begin(), BB,
7001                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7002   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7003
7004   // Load an immediate to varEnd.
7005   unsigned varEnd = MRI.createVirtualRegister(TRC);
7006   if (IsThumb2) {
7007     unsigned Vtmp = varEnd;
7008     if ((LoopSize & 0xFFFF0000) != 0)
7009       Vtmp = MRI.createVirtualRegister(TRC);
7010     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp)
7011                        .addImm(LoopSize & 0xFFFF));
7012
7013     if ((LoopSize & 0xFFFF0000) != 0)
7014       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7015                          .addReg(Vtmp).addImm(LoopSize >> 16));
7016   } else {
7017     MachineConstantPool *ConstantPool = MF->getConstantPool();
7018     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7019     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7020
7021     // MachineConstantPool wants an explicit alignment.
7022     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7023     if (Align == 0)
7024       Align = getDataLayout()->getTypeAllocSize(C->getType());
7025     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7026
7027     if (IsThumb1)
7028       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7029           varEnd, RegState::Define).addConstantPoolIndex(Idx));
7030     else
7031       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7032           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7033   }
7034   BB->addSuccessor(loopMBB);
7035
7036   // Generate the loop body:
7037   //   varPhi = PHI(varLoop, varEnd)
7038   //   srcPhi = PHI(srcLoop, src)
7039   //   destPhi = PHI(destLoop, dst)
7040   MachineBasicBlock *entryBB = BB;
7041   BB = loopMBB;
7042   unsigned varLoop = MRI.createVirtualRegister(TRC);
7043   unsigned varPhi = MRI.createVirtualRegister(TRC);
7044   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7045   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7046   unsigned destLoop = MRI.createVirtualRegister(TRC);
7047   unsigned destPhi = MRI.createVirtualRegister(TRC);
7048
7049   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7050     .addReg(varLoop).addMBB(loopMBB)
7051     .addReg(varEnd).addMBB(entryBB);
7052   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7053     .addReg(srcLoop).addMBB(loopMBB)
7054     .addReg(src).addMBB(entryBB);
7055   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7056     .addReg(destLoop).addMBB(loopMBB)
7057     .addReg(dest).addMBB(entryBB);
7058
7059   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7060   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7061   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7062   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7063              IsThumb1, IsThumb2);
7064   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7065              IsThumb1, IsThumb2);
7066
7067   // Decrement loop variable by UnitSize.
7068   if (IsThumb1) {
7069     MachineInstrBuilder MIB =
7070         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7071     MIB = AddDefaultT1CC(MIB);
7072     MIB.addReg(varPhi).addImm(UnitSize);
7073     AddDefaultPred(MIB);
7074   } else {
7075     MachineInstrBuilder MIB =
7076         BuildMI(*BB, BB->end(), dl,
7077                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7078     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7079     MIB->getOperand(5).setReg(ARM::CPSR);
7080     MIB->getOperand(5).setIsDef(true);
7081   }
7082   BuildMI(*BB, BB->end(), dl,
7083           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7084       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7085
7086   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7087   BB->addSuccessor(loopMBB);
7088   BB->addSuccessor(exitMBB);
7089
7090   // Add epilogue to handle BytesLeft.
7091   BB = exitMBB;
7092   MachineInstr *StartOfExit = exitMBB->begin();
7093
7094   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7095   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7096   unsigned srcIn = srcLoop;
7097   unsigned destIn = destLoop;
7098   for (unsigned i = 0; i < BytesLeft; i++) {
7099     unsigned srcOut = MRI.createVirtualRegister(TRC);
7100     unsigned destOut = MRI.createVirtualRegister(TRC);
7101     unsigned scratch = MRI.createVirtualRegister(TRC);
7102     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7103                IsThumb1, IsThumb2);
7104     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7105                IsThumb1, IsThumb2);
7106     srcIn = srcOut;
7107     destIn = destOut;
7108   }
7109
7110   MI->eraseFromParent();   // The instruction is gone now.
7111   return BB;
7112 }
7113
7114 MachineBasicBlock *
7115 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7116                                                MachineBasicBlock *BB) const {
7117   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7118   DebugLoc dl = MI->getDebugLoc();
7119   bool isThumb2 = Subtarget->isThumb2();
7120   switch (MI->getOpcode()) {
7121   default: {
7122     MI->dump();
7123     llvm_unreachable("Unexpected instr type to insert");
7124   }
7125   // The Thumb2 pre-indexed stores have the same MI operands, they just
7126   // define them differently in the .td files from the isel patterns, so
7127   // they need pseudos.
7128   case ARM::t2STR_preidx:
7129     MI->setDesc(TII->get(ARM::t2STR_PRE));
7130     return BB;
7131   case ARM::t2STRB_preidx:
7132     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7133     return BB;
7134   case ARM::t2STRH_preidx:
7135     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7136     return BB;
7137
7138   case ARM::STRi_preidx:
7139   case ARM::STRBi_preidx: {
7140     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7141       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7142     // Decode the offset.
7143     unsigned Offset = MI->getOperand(4).getImm();
7144     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7145     Offset = ARM_AM::getAM2Offset(Offset);
7146     if (isSub)
7147       Offset = -Offset;
7148
7149     MachineMemOperand *MMO = *MI->memoperands_begin();
7150     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7151       .addOperand(MI->getOperand(0))  // Rn_wb
7152       .addOperand(MI->getOperand(1))  // Rt
7153       .addOperand(MI->getOperand(2))  // Rn
7154       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7155       .addOperand(MI->getOperand(5))  // pred
7156       .addOperand(MI->getOperand(6))
7157       .addMemOperand(MMO);
7158     MI->eraseFromParent();
7159     return BB;
7160   }
7161   case ARM::STRr_preidx:
7162   case ARM::STRBr_preidx:
7163   case ARM::STRH_preidx: {
7164     unsigned NewOpc;
7165     switch (MI->getOpcode()) {
7166     default: llvm_unreachable("unexpected opcode!");
7167     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7168     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7169     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7170     }
7171     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7172     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7173       MIB.addOperand(MI->getOperand(i));
7174     MI->eraseFromParent();
7175     return BB;
7176   }
7177
7178   case ARM::tMOVCCr_pseudo: {
7179     // To "insert" a SELECT_CC instruction, we actually have to insert the
7180     // diamond control-flow pattern.  The incoming instruction knows the
7181     // destination vreg to set, the condition code register to branch on, the
7182     // true/false values to select between, and a branch opcode to use.
7183     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7184     MachineFunction::iterator It = BB;
7185     ++It;
7186
7187     //  thisMBB:
7188     //  ...
7189     //   TrueVal = ...
7190     //   cmpTY ccX, r1, r2
7191     //   bCC copy1MBB
7192     //   fallthrough --> copy0MBB
7193     MachineBasicBlock *thisMBB  = BB;
7194     MachineFunction *F = BB->getParent();
7195     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7196     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7197     F->insert(It, copy0MBB);
7198     F->insert(It, sinkMBB);
7199
7200     // Transfer the remainder of BB and its successor edges to sinkMBB.
7201     sinkMBB->splice(sinkMBB->begin(), BB,
7202                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7203     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7204
7205     BB->addSuccessor(copy0MBB);
7206     BB->addSuccessor(sinkMBB);
7207
7208     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7209       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7210
7211     //  copy0MBB:
7212     //   %FalseValue = ...
7213     //   # fallthrough to sinkMBB
7214     BB = copy0MBB;
7215
7216     // Update machine-CFG edges
7217     BB->addSuccessor(sinkMBB);
7218
7219     //  sinkMBB:
7220     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7221     //  ...
7222     BB = sinkMBB;
7223     BuildMI(*BB, BB->begin(), dl,
7224             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7225       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7226       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7227
7228     MI->eraseFromParent();   // The pseudo instruction is gone now.
7229     return BB;
7230   }
7231
7232   case ARM::BCCi64:
7233   case ARM::BCCZi64: {
7234     // If there is an unconditional branch to the other successor, remove it.
7235     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7236
7237     // Compare both parts that make up the double comparison separately for
7238     // equality.
7239     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7240
7241     unsigned LHS1 = MI->getOperand(1).getReg();
7242     unsigned LHS2 = MI->getOperand(2).getReg();
7243     if (RHSisZero) {
7244       AddDefaultPred(BuildMI(BB, dl,
7245                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7246                      .addReg(LHS1).addImm(0));
7247       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7248         .addReg(LHS2).addImm(0)
7249         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7250     } else {
7251       unsigned RHS1 = MI->getOperand(3).getReg();
7252       unsigned RHS2 = MI->getOperand(4).getReg();
7253       AddDefaultPred(BuildMI(BB, dl,
7254                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7255                      .addReg(LHS1).addReg(RHS1));
7256       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7257         .addReg(LHS2).addReg(RHS2)
7258         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7259     }
7260
7261     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7262     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7263     if (MI->getOperand(0).getImm() == ARMCC::NE)
7264       std::swap(destMBB, exitMBB);
7265
7266     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7267       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7268     if (isThumb2)
7269       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7270     else
7271       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7272
7273     MI->eraseFromParent();   // The pseudo instruction is gone now.
7274     return BB;
7275   }
7276
7277   case ARM::Int_eh_sjlj_setjmp:
7278   case ARM::Int_eh_sjlj_setjmp_nofp:
7279   case ARM::tInt_eh_sjlj_setjmp:
7280   case ARM::t2Int_eh_sjlj_setjmp:
7281   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7282     EmitSjLjDispatchBlock(MI, BB);
7283     return BB;
7284
7285   case ARM::ABS:
7286   case ARM::t2ABS: {
7287     // To insert an ABS instruction, we have to insert the
7288     // diamond control-flow pattern.  The incoming instruction knows the
7289     // source vreg to test against 0, the destination vreg to set,
7290     // the condition code register to branch on, the
7291     // true/false values to select between, and a branch opcode to use.
7292     // It transforms
7293     //     V1 = ABS V0
7294     // into
7295     //     V2 = MOVS V0
7296     //     BCC                      (branch to SinkBB if V0 >= 0)
7297     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7298     //     SinkBB: V1 = PHI(V2, V3)
7299     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7300     MachineFunction::iterator BBI = BB;
7301     ++BBI;
7302     MachineFunction *Fn = BB->getParent();
7303     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7304     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7305     Fn->insert(BBI, RSBBB);
7306     Fn->insert(BBI, SinkBB);
7307
7308     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7309     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7310     bool isThumb2 = Subtarget->isThumb2();
7311     MachineRegisterInfo &MRI = Fn->getRegInfo();
7312     // In Thumb mode S must not be specified if source register is the SP or
7313     // PC and if destination register is the SP, so restrict register class
7314     unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7315       (const TargetRegisterClass*)&ARM::rGPRRegClass :
7316       (const TargetRegisterClass*)&ARM::GPRRegClass);
7317
7318     // Transfer the remainder of BB and its successor edges to sinkMBB.
7319     SinkBB->splice(SinkBB->begin(), BB,
7320                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
7321     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7322
7323     BB->addSuccessor(RSBBB);
7324     BB->addSuccessor(SinkBB);
7325
7326     // fall through to SinkMBB
7327     RSBBB->addSuccessor(SinkBB);
7328
7329     // insert a cmp at the end of BB
7330     AddDefaultPred(BuildMI(BB, dl,
7331                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7332                    .addReg(ABSSrcReg).addImm(0));
7333
7334     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7335     BuildMI(BB, dl,
7336       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7337       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7338
7339     // insert rsbri in RSBBB
7340     // Note: BCC and rsbri will be converted into predicated rsbmi
7341     // by if-conversion pass
7342     BuildMI(*RSBBB, RSBBB->begin(), dl,
7343       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7344       .addReg(ABSSrcReg, RegState::Kill)
7345       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7346
7347     // insert PHI in SinkBB,
7348     // reuse ABSDstReg to not change uses of ABS instruction
7349     BuildMI(*SinkBB, SinkBB->begin(), dl,
7350       TII->get(ARM::PHI), ABSDstReg)
7351       .addReg(NewRsbDstReg).addMBB(RSBBB)
7352       .addReg(ABSSrcReg).addMBB(BB);
7353
7354     // remove ABS instruction
7355     MI->eraseFromParent();
7356
7357     // return last added BB
7358     return SinkBB;
7359   }
7360   case ARM::COPY_STRUCT_BYVAL_I32:
7361     ++NumLoopByVals;
7362     return EmitStructByval(MI, BB);
7363   }
7364 }
7365
7366 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7367                                                       SDNode *Node) const {
7368   if (!MI->hasPostISelHook()) {
7369     assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7370            "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7371     return;
7372   }
7373
7374   const MCInstrDesc *MCID = &MI->getDesc();
7375   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7376   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7377   // operand is still set to noreg. If needed, set the optional operand's
7378   // register to CPSR, and remove the redundant implicit def.
7379   //
7380   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7381
7382   // Rename pseudo opcodes.
7383   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7384   if (NewOpc) {
7385     const ARMBaseInstrInfo *TII =
7386       static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
7387     MCID = &TII->get(NewOpc);
7388
7389     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7390            "converted opcode should be the same except for cc_out");
7391
7392     MI->setDesc(*MCID);
7393
7394     // Add the optional cc_out operand
7395     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7396   }
7397   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7398
7399   // Any ARM instruction that sets the 's' bit should specify an optional
7400   // "cc_out" operand in the last operand position.
7401   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7402     assert(!NewOpc && "Optional cc_out operand required");
7403     return;
7404   }
7405   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7406   // since we already have an optional CPSR def.
7407   bool definesCPSR = false;
7408   bool deadCPSR = false;
7409   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7410        i != e; ++i) {
7411     const MachineOperand &MO = MI->getOperand(i);
7412     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7413       definesCPSR = true;
7414       if (MO.isDead())
7415         deadCPSR = true;
7416       MI->RemoveOperand(i);
7417       break;
7418     }
7419   }
7420   if (!definesCPSR) {
7421     assert(!NewOpc && "Optional cc_out operand required");
7422     return;
7423   }
7424   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7425   if (deadCPSR) {
7426     assert(!MI->getOperand(ccOutIdx).getReg() &&
7427            "expect uninitialized optional cc_out operand");
7428     return;
7429   }
7430
7431   // If this instruction was defined with an optional CPSR def and its dag node
7432   // had a live implicit CPSR def, then activate the optional CPSR def.
7433   MachineOperand &MO = MI->getOperand(ccOutIdx);
7434   MO.setReg(ARM::CPSR);
7435   MO.setIsDef(true);
7436 }
7437
7438 //===----------------------------------------------------------------------===//
7439 //                           ARM Optimization Hooks
7440 //===----------------------------------------------------------------------===//
7441
7442 // Helper function that checks if N is a null or all ones constant.
7443 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7444   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7445   if (!C)
7446     return false;
7447   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7448 }
7449
7450 // Return true if N is conditionally 0 or all ones.
7451 // Detects these expressions where cc is an i1 value:
7452 //
7453 //   (select cc 0, y)   [AllOnes=0]
7454 //   (select cc y, 0)   [AllOnes=0]
7455 //   (zext cc)          [AllOnes=0]
7456 //   (sext cc)          [AllOnes=0/1]
7457 //   (select cc -1, y)  [AllOnes=1]
7458 //   (select cc y, -1)  [AllOnes=1]
7459 //
7460 // Invert is set when N is the null/all ones constant when CC is false.
7461 // OtherOp is set to the alternative value of N.
7462 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7463                                        SDValue &CC, bool &Invert,
7464                                        SDValue &OtherOp,
7465                                        SelectionDAG &DAG) {
7466   switch (N->getOpcode()) {
7467   default: return false;
7468   case ISD::SELECT: {
7469     CC = N->getOperand(0);
7470     SDValue N1 = N->getOperand(1);
7471     SDValue N2 = N->getOperand(2);
7472     if (isZeroOrAllOnes(N1, AllOnes)) {
7473       Invert = false;
7474       OtherOp = N2;
7475       return true;
7476     }
7477     if (isZeroOrAllOnes(N2, AllOnes)) {
7478       Invert = true;
7479       OtherOp = N1;
7480       return true;
7481     }
7482     return false;
7483   }
7484   case ISD::ZERO_EXTEND:
7485     // (zext cc) can never be the all ones value.
7486     if (AllOnes)
7487       return false;
7488     // Fall through.
7489   case ISD::SIGN_EXTEND: {
7490     EVT VT = N->getValueType(0);
7491     CC = N->getOperand(0);
7492     if (CC.getValueType() != MVT::i1)
7493       return false;
7494     Invert = !AllOnes;
7495     if (AllOnes)
7496       // When looking for an AllOnes constant, N is an sext, and the 'other'
7497       // value is 0.
7498       OtherOp = DAG.getConstant(0, VT);
7499     else if (N->getOpcode() == ISD::ZERO_EXTEND)
7500       // When looking for a 0 constant, N can be zext or sext.
7501       OtherOp = DAG.getConstant(1, VT);
7502     else
7503       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7504     return true;
7505   }
7506   }
7507 }
7508
7509 // Combine a constant select operand into its use:
7510 //
7511 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
7512 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
7513 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
7514 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
7515 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
7516 //
7517 // The transform is rejected if the select doesn't have a constant operand that
7518 // is null, or all ones when AllOnes is set.
7519 //
7520 // Also recognize sext/zext from i1:
7521 //
7522 //   (add (zext cc), x) -> (select cc (add x, 1), x)
7523 //   (add (sext cc), x) -> (select cc (add x, -1), x)
7524 //
7525 // These transformations eventually create predicated instructions.
7526 //
7527 // @param N       The node to transform.
7528 // @param Slct    The N operand that is a select.
7529 // @param OtherOp The other N operand (x above).
7530 // @param DCI     Context.
7531 // @param AllOnes Require the select constant to be all ones instead of null.
7532 // @returns The new node, or SDValue() on failure.
7533 static
7534 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7535                             TargetLowering::DAGCombinerInfo &DCI,
7536                             bool AllOnes = false) {
7537   SelectionDAG &DAG = DCI.DAG;
7538   EVT VT = N->getValueType(0);
7539   SDValue NonConstantVal;
7540   SDValue CCOp;
7541   bool SwapSelectOps;
7542   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7543                                   NonConstantVal, DAG))
7544     return SDValue();
7545
7546   // Slct is now know to be the desired identity constant when CC is true.
7547   SDValue TrueVal = OtherOp;
7548   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7549                                  OtherOp, NonConstantVal);
7550   // Unless SwapSelectOps says CC should be false.
7551   if (SwapSelectOps)
7552     std::swap(TrueVal, FalseVal);
7553
7554   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7555                      CCOp, TrueVal, FalseVal);
7556 }
7557
7558 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7559 static
7560 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7561                                        TargetLowering::DAGCombinerInfo &DCI) {
7562   SDValue N0 = N->getOperand(0);
7563   SDValue N1 = N->getOperand(1);
7564   if (N0.getNode()->hasOneUse()) {
7565     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7566     if (Result.getNode())
7567       return Result;
7568   }
7569   if (N1.getNode()->hasOneUse()) {
7570     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7571     if (Result.getNode())
7572       return Result;
7573   }
7574   return SDValue();
7575 }
7576
7577 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7578 // (only after legalization).
7579 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7580                                  TargetLowering::DAGCombinerInfo &DCI,
7581                                  const ARMSubtarget *Subtarget) {
7582
7583   // Only perform optimization if after legalize, and if NEON is available. We
7584   // also expected both operands to be BUILD_VECTORs.
7585   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7586       || N0.getOpcode() != ISD::BUILD_VECTOR
7587       || N1.getOpcode() != ISD::BUILD_VECTOR)
7588     return SDValue();
7589
7590   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7591   EVT VT = N->getValueType(0);
7592   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7593     return SDValue();
7594
7595   // Check that the vector operands are of the right form.
7596   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7597   // operands, where N is the size of the formed vector.
7598   // Each EXTRACT_VECTOR should have the same input vector and odd or even
7599   // index such that we have a pair wise add pattern.
7600
7601   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7602   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7603     return SDValue();
7604   SDValue Vec = N0->getOperand(0)->getOperand(0);
7605   SDNode *V = Vec.getNode();
7606   unsigned nextIndex = 0;
7607
7608   // For each operands to the ADD which are BUILD_VECTORs,
7609   // check to see if each of their operands are an EXTRACT_VECTOR with
7610   // the same vector and appropriate index.
7611   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7612     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7613         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7614
7615       SDValue ExtVec0 = N0->getOperand(i);
7616       SDValue ExtVec1 = N1->getOperand(i);
7617
7618       // First operand is the vector, verify its the same.
7619       if (V != ExtVec0->getOperand(0).getNode() ||
7620           V != ExtVec1->getOperand(0).getNode())
7621         return SDValue();
7622
7623       // Second is the constant, verify its correct.
7624       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7625       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7626
7627       // For the constant, we want to see all the even or all the odd.
7628       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7629           || C1->getZExtValue() != nextIndex+1)
7630         return SDValue();
7631
7632       // Increment index.
7633       nextIndex+=2;
7634     } else
7635       return SDValue();
7636   }
7637
7638   // Create VPADDL node.
7639   SelectionDAG &DAG = DCI.DAG;
7640   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7641
7642   // Build operand list.
7643   SmallVector<SDValue, 8> Ops;
7644   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7645                                 TLI.getPointerTy()));
7646
7647   // Input is the vector.
7648   Ops.push_back(Vec);
7649
7650   // Get widened type and narrowed type.
7651   MVT widenType;
7652   unsigned numElem = VT.getVectorNumElements();
7653   
7654   EVT inputLaneType = Vec.getValueType().getVectorElementType();
7655   switch (inputLaneType.getSimpleVT().SimpleTy) {
7656     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7657     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7658     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7659     default:
7660       llvm_unreachable("Invalid vector element type for padd optimization.");
7661   }
7662
7663   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), widenType, Ops);
7664   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
7665   return DAG.getNode(ExtOp, SDLoc(N), VT, tmp);
7666 }
7667
7668 static SDValue findMUL_LOHI(SDValue V) {
7669   if (V->getOpcode() == ISD::UMUL_LOHI ||
7670       V->getOpcode() == ISD::SMUL_LOHI)
7671     return V;
7672   return SDValue();
7673 }
7674
7675 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7676                                      TargetLowering::DAGCombinerInfo &DCI,
7677                                      const ARMSubtarget *Subtarget) {
7678
7679   if (Subtarget->isThumb1Only()) return SDValue();
7680
7681   // Only perform the checks after legalize when the pattern is available.
7682   if (DCI.isBeforeLegalize()) return SDValue();
7683
7684   // Look for multiply add opportunities.
7685   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7686   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7687   // a glue link from the first add to the second add.
7688   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7689   // a S/UMLAL instruction.
7690   //          loAdd   UMUL_LOHI
7691   //            \    / :lo    \ :hi
7692   //             \  /          \          [no multiline comment]
7693   //              ADDC         |  hiAdd
7694   //                 \ :glue  /  /
7695   //                  \      /  /
7696   //                    ADDE
7697   //
7698   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7699   SDValue AddcOp0 = AddcNode->getOperand(0);
7700   SDValue AddcOp1 = AddcNode->getOperand(1);
7701
7702   // Check if the two operands are from the same mul_lohi node.
7703   if (AddcOp0.getNode() == AddcOp1.getNode())
7704     return SDValue();
7705
7706   assert(AddcNode->getNumValues() == 2 &&
7707          AddcNode->getValueType(0) == MVT::i32 &&
7708          "Expect ADDC with two result values. First: i32");
7709
7710   // Check that we have a glued ADDC node.
7711   if (AddcNode->getValueType(1) != MVT::Glue)
7712     return SDValue();
7713
7714   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7715   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7716       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7717       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7718       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7719     return SDValue();
7720
7721   // Look for the glued ADDE.
7722   SDNode* AddeNode = AddcNode->getGluedUser();
7723   if (!AddeNode)
7724     return SDValue();
7725
7726   // Make sure it is really an ADDE.
7727   if (AddeNode->getOpcode() != ISD::ADDE)
7728     return SDValue();
7729
7730   assert(AddeNode->getNumOperands() == 3 &&
7731          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
7732          "ADDE node has the wrong inputs");
7733
7734   // Check for the triangle shape.
7735   SDValue AddeOp0 = AddeNode->getOperand(0);
7736   SDValue AddeOp1 = AddeNode->getOperand(1);
7737
7738   // Make sure that the ADDE operands are not coming from the same node.
7739   if (AddeOp0.getNode() == AddeOp1.getNode())
7740     return SDValue();
7741
7742   // Find the MUL_LOHI node walking up ADDE's operands.
7743   bool IsLeftOperandMUL = false;
7744   SDValue MULOp = findMUL_LOHI(AddeOp0);
7745   if (MULOp == SDValue())
7746    MULOp = findMUL_LOHI(AddeOp1);
7747   else
7748     IsLeftOperandMUL = true;
7749   if (MULOp == SDValue())
7750      return SDValue();
7751
7752   // Figure out the right opcode.
7753   unsigned Opc = MULOp->getOpcode();
7754   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
7755
7756   // Figure out the high and low input values to the MLAL node.
7757   SDValue* HiMul = &MULOp;
7758   SDValue* HiAdd = nullptr;
7759   SDValue* LoMul = nullptr;
7760   SDValue* LowAdd = nullptr;
7761
7762   if (IsLeftOperandMUL)
7763     HiAdd = &AddeOp1;
7764   else
7765     HiAdd = &AddeOp0;
7766
7767
7768   if (AddcOp0->getOpcode() == Opc) {
7769     LoMul = &AddcOp0;
7770     LowAdd = &AddcOp1;
7771   }
7772   if (AddcOp1->getOpcode() == Opc) {
7773     LoMul = &AddcOp1;
7774     LowAdd = &AddcOp0;
7775   }
7776
7777   if (!LoMul)
7778     return SDValue();
7779
7780   if (LoMul->getNode() != HiMul->getNode())
7781     return SDValue();
7782
7783   // Create the merged node.
7784   SelectionDAG &DAG = DCI.DAG;
7785
7786   // Build operand list.
7787   SmallVector<SDValue, 8> Ops;
7788   Ops.push_back(LoMul->getOperand(0));
7789   Ops.push_back(LoMul->getOperand(1));
7790   Ops.push_back(*LowAdd);
7791   Ops.push_back(*HiAdd);
7792
7793   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
7794                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
7795
7796   // Replace the ADDs' nodes uses by the MLA node's values.
7797   SDValue HiMLALResult(MLALNode.getNode(), 1);
7798   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
7799
7800   SDValue LoMLALResult(MLALNode.getNode(), 0);
7801   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
7802
7803   // Return original node to notify the driver to stop replacing.
7804   SDValue resNode(AddcNode, 0);
7805   return resNode;
7806 }
7807
7808 /// PerformADDCCombine - Target-specific dag combine transform from
7809 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
7810 static SDValue PerformADDCCombine(SDNode *N,
7811                                  TargetLowering::DAGCombinerInfo &DCI,
7812                                  const ARMSubtarget *Subtarget) {
7813
7814   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
7815
7816 }
7817
7818 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
7819 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
7820 /// called with the default operands, and if that fails, with commuted
7821 /// operands.
7822 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
7823                                           TargetLowering::DAGCombinerInfo &DCI,
7824                                           const ARMSubtarget *Subtarget){
7825
7826   // Attempt to create vpaddl for this add.
7827   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
7828   if (Result.getNode())
7829     return Result;
7830
7831   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7832   if (N0.getNode()->hasOneUse()) {
7833     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
7834     if (Result.getNode()) return Result;
7835   }
7836   return SDValue();
7837 }
7838
7839 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
7840 ///
7841 static SDValue PerformADDCombine(SDNode *N,
7842                                  TargetLowering::DAGCombinerInfo &DCI,
7843                                  const ARMSubtarget *Subtarget) {
7844   SDValue N0 = N->getOperand(0);
7845   SDValue N1 = N->getOperand(1);
7846
7847   // First try with the default operand order.
7848   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
7849   if (Result.getNode())
7850     return Result;
7851
7852   // If that didn't work, try again with the operands commuted.
7853   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
7854 }
7855
7856 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
7857 ///
7858 static SDValue PerformSUBCombine(SDNode *N,
7859                                  TargetLowering::DAGCombinerInfo &DCI) {
7860   SDValue N0 = N->getOperand(0);
7861   SDValue N1 = N->getOperand(1);
7862
7863   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7864   if (N1.getNode()->hasOneUse()) {
7865     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
7866     if (Result.getNode()) return Result;
7867   }
7868
7869   return SDValue();
7870 }
7871
7872 /// PerformVMULCombine
7873 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
7874 /// special multiplier accumulator forwarding.
7875 ///   vmul d3, d0, d2
7876 ///   vmla d3, d1, d2
7877 /// is faster than
7878 ///   vadd d3, d0, d1
7879 ///   vmul d3, d3, d2
7880 //  However, for (A + B) * (A + B),
7881 //    vadd d2, d0, d1
7882 //    vmul d3, d0, d2
7883 //    vmla d3, d1, d2
7884 //  is slower than
7885 //    vadd d2, d0, d1
7886 //    vmul d3, d2, d2
7887 static SDValue PerformVMULCombine(SDNode *N,
7888                                   TargetLowering::DAGCombinerInfo &DCI,
7889                                   const ARMSubtarget *Subtarget) {
7890   if (!Subtarget->hasVMLxForwarding())
7891     return SDValue();
7892
7893   SelectionDAG &DAG = DCI.DAG;
7894   SDValue N0 = N->getOperand(0);
7895   SDValue N1 = N->getOperand(1);
7896   unsigned Opcode = N0.getOpcode();
7897   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7898       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
7899     Opcode = N1.getOpcode();
7900     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7901         Opcode != ISD::FADD && Opcode != ISD::FSUB)
7902       return SDValue();
7903     std::swap(N0, N1);
7904   }
7905
7906   if (N0 == N1)
7907     return SDValue();
7908
7909   EVT VT = N->getValueType(0);
7910   SDLoc DL(N);
7911   SDValue N00 = N0->getOperand(0);
7912   SDValue N01 = N0->getOperand(1);
7913   return DAG.getNode(Opcode, DL, VT,
7914                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
7915                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
7916 }
7917
7918 static SDValue PerformMULCombine(SDNode *N,
7919                                  TargetLowering::DAGCombinerInfo &DCI,
7920                                  const ARMSubtarget *Subtarget) {
7921   SelectionDAG &DAG = DCI.DAG;
7922
7923   if (Subtarget->isThumb1Only())
7924     return SDValue();
7925
7926   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
7927     return SDValue();
7928
7929   EVT VT = N->getValueType(0);
7930   if (VT.is64BitVector() || VT.is128BitVector())
7931     return PerformVMULCombine(N, DCI, Subtarget);
7932   if (VT != MVT::i32)
7933     return SDValue();
7934
7935   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7936   if (!C)
7937     return SDValue();
7938
7939   int64_t MulAmt = C->getSExtValue();
7940   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
7941
7942   ShiftAmt = ShiftAmt & (32 - 1);
7943   SDValue V = N->getOperand(0);
7944   SDLoc DL(N);
7945
7946   SDValue Res;
7947   MulAmt >>= ShiftAmt;
7948
7949   if (MulAmt >= 0) {
7950     if (isPowerOf2_32(MulAmt - 1)) {
7951       // (mul x, 2^N + 1) => (add (shl x, N), x)
7952       Res = DAG.getNode(ISD::ADD, DL, VT,
7953                         V,
7954                         DAG.getNode(ISD::SHL, DL, VT,
7955                                     V,
7956                                     DAG.getConstant(Log2_32(MulAmt - 1),
7957                                                     MVT::i32)));
7958     } else if (isPowerOf2_32(MulAmt + 1)) {
7959       // (mul x, 2^N - 1) => (sub (shl x, N), x)
7960       Res = DAG.getNode(ISD::SUB, DL, VT,
7961                         DAG.getNode(ISD::SHL, DL, VT,
7962                                     V,
7963                                     DAG.getConstant(Log2_32(MulAmt + 1),
7964                                                     MVT::i32)),
7965                         V);
7966     } else
7967       return SDValue();
7968   } else {
7969     uint64_t MulAmtAbs = -MulAmt;
7970     if (isPowerOf2_32(MulAmtAbs + 1)) {
7971       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7972       Res = DAG.getNode(ISD::SUB, DL, VT,
7973                         V,
7974                         DAG.getNode(ISD::SHL, DL, VT,
7975                                     V,
7976                                     DAG.getConstant(Log2_32(MulAmtAbs + 1),
7977                                                     MVT::i32)));
7978     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
7979       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7980       Res = DAG.getNode(ISD::ADD, DL, VT,
7981                         V,
7982                         DAG.getNode(ISD::SHL, DL, VT,
7983                                     V,
7984                                     DAG.getConstant(Log2_32(MulAmtAbs-1),
7985                                                     MVT::i32)));
7986       Res = DAG.getNode(ISD::SUB, DL, VT,
7987                         DAG.getConstant(0, MVT::i32),Res);
7988
7989     } else
7990       return SDValue();
7991   }
7992
7993   if (ShiftAmt != 0)
7994     Res = DAG.getNode(ISD::SHL, DL, VT,
7995                       Res, DAG.getConstant(ShiftAmt, MVT::i32));
7996
7997   // Do not add new nodes to DAG combiner worklist.
7998   DCI.CombineTo(N, Res, false);
7999   return SDValue();
8000 }
8001
8002 static SDValue PerformANDCombine(SDNode *N,
8003                                  TargetLowering::DAGCombinerInfo &DCI,
8004                                  const ARMSubtarget *Subtarget) {
8005
8006   // Attempt to use immediate-form VBIC
8007   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8008   SDLoc dl(N);
8009   EVT VT = N->getValueType(0);
8010   SelectionDAG &DAG = DCI.DAG;
8011
8012   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8013     return SDValue();
8014
8015   APInt SplatBits, SplatUndef;
8016   unsigned SplatBitSize;
8017   bool HasAnyUndefs;
8018   if (BVN &&
8019       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8020     if (SplatBitSize <= 64) {
8021       EVT VbicVT;
8022       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8023                                       SplatUndef.getZExtValue(), SplatBitSize,
8024                                       DAG, VbicVT, VT.is128BitVector(),
8025                                       OtherModImm);
8026       if (Val.getNode()) {
8027         SDValue Input =
8028           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8029         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8030         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8031       }
8032     }
8033   }
8034
8035   if (!Subtarget->isThumb1Only()) {
8036     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8037     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8038     if (Result.getNode())
8039       return Result;
8040   }
8041
8042   return SDValue();
8043 }
8044
8045 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8046 static SDValue PerformORCombine(SDNode *N,
8047                                 TargetLowering::DAGCombinerInfo &DCI,
8048                                 const ARMSubtarget *Subtarget) {
8049   // Attempt to use immediate-form VORR
8050   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8051   SDLoc dl(N);
8052   EVT VT = N->getValueType(0);
8053   SelectionDAG &DAG = DCI.DAG;
8054
8055   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8056     return SDValue();
8057
8058   APInt SplatBits, SplatUndef;
8059   unsigned SplatBitSize;
8060   bool HasAnyUndefs;
8061   if (BVN && Subtarget->hasNEON() &&
8062       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8063     if (SplatBitSize <= 64) {
8064       EVT VorrVT;
8065       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8066                                       SplatUndef.getZExtValue(), SplatBitSize,
8067                                       DAG, VorrVT, VT.is128BitVector(),
8068                                       OtherModImm);
8069       if (Val.getNode()) {
8070         SDValue Input =
8071           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8072         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8073         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8074       }
8075     }
8076   }
8077
8078   if (!Subtarget->isThumb1Only()) {
8079     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8080     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8081     if (Result.getNode())
8082       return Result;
8083   }
8084
8085   // The code below optimizes (or (and X, Y), Z).
8086   // The AND operand needs to have a single user to make these optimizations
8087   // profitable.
8088   SDValue N0 = N->getOperand(0);
8089   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8090     return SDValue();
8091   SDValue N1 = N->getOperand(1);
8092
8093   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8094   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8095       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8096     APInt SplatUndef;
8097     unsigned SplatBitSize;
8098     bool HasAnyUndefs;
8099
8100     APInt SplatBits0, SplatBits1;
8101     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8102     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8103     // Ensure that the second operand of both ands are constants
8104     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8105                                       HasAnyUndefs) && !HasAnyUndefs) {
8106         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8107                                           HasAnyUndefs) && !HasAnyUndefs) {
8108             // Ensure that the bit width of the constants are the same and that
8109             // the splat arguments are logical inverses as per the pattern we
8110             // are trying to simplify.
8111             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8112                 SplatBits0 == ~SplatBits1) {
8113                 // Canonicalize the vector type to make instruction selection
8114                 // simpler.
8115                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8116                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8117                                              N0->getOperand(1),
8118                                              N0->getOperand(0),
8119                                              N1->getOperand(0));
8120                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8121             }
8122         }
8123     }
8124   }
8125
8126   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8127   // reasonable.
8128
8129   // BFI is only available on V6T2+
8130   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8131     return SDValue();
8132
8133   SDLoc DL(N);
8134   // 1) or (and A, mask), val => ARMbfi A, val, mask
8135   //      iff (val & mask) == val
8136   //
8137   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8138   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8139   //          && mask == ~mask2
8140   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8141   //          && ~mask == mask2
8142   //  (i.e., copy a bitfield value into another bitfield of the same width)
8143
8144   if (VT != MVT::i32)
8145     return SDValue();
8146
8147   SDValue N00 = N0.getOperand(0);
8148
8149   // The value and the mask need to be constants so we can verify this is
8150   // actually a bitfield set. If the mask is 0xffff, we can do better
8151   // via a movt instruction, so don't use BFI in that case.
8152   SDValue MaskOp = N0.getOperand(1);
8153   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8154   if (!MaskC)
8155     return SDValue();
8156   unsigned Mask = MaskC->getZExtValue();
8157   if (Mask == 0xffff)
8158     return SDValue();
8159   SDValue Res;
8160   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8161   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8162   if (N1C) {
8163     unsigned Val = N1C->getZExtValue();
8164     if ((Val & ~Mask) != Val)
8165       return SDValue();
8166
8167     if (ARM::isBitFieldInvertedMask(Mask)) {
8168       Val >>= countTrailingZeros(~Mask);
8169
8170       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8171                         DAG.getConstant(Val, MVT::i32),
8172                         DAG.getConstant(Mask, MVT::i32));
8173
8174       // Do not add new nodes to DAG combiner worklist.
8175       DCI.CombineTo(N, Res, false);
8176       return SDValue();
8177     }
8178   } else if (N1.getOpcode() == ISD::AND) {
8179     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8180     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8181     if (!N11C)
8182       return SDValue();
8183     unsigned Mask2 = N11C->getZExtValue();
8184
8185     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8186     // as is to match.
8187     if (ARM::isBitFieldInvertedMask(Mask) &&
8188         (Mask == ~Mask2)) {
8189       // The pack halfword instruction works better for masks that fit it,
8190       // so use that when it's available.
8191       if (Subtarget->hasT2ExtractPack() &&
8192           (Mask == 0xffff || Mask == 0xffff0000))
8193         return SDValue();
8194       // 2a
8195       unsigned amt = countTrailingZeros(Mask2);
8196       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8197                         DAG.getConstant(amt, MVT::i32));
8198       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8199                         DAG.getConstant(Mask, MVT::i32));
8200       // Do not add new nodes to DAG combiner worklist.
8201       DCI.CombineTo(N, Res, false);
8202       return SDValue();
8203     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8204                (~Mask == Mask2)) {
8205       // The pack halfword instruction works better for masks that fit it,
8206       // so use that when it's available.
8207       if (Subtarget->hasT2ExtractPack() &&
8208           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8209         return SDValue();
8210       // 2b
8211       unsigned lsb = countTrailingZeros(Mask);
8212       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8213                         DAG.getConstant(lsb, MVT::i32));
8214       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8215                         DAG.getConstant(Mask2, MVT::i32));
8216       // Do not add new nodes to DAG combiner worklist.
8217       DCI.CombineTo(N, Res, false);
8218       return SDValue();
8219     }
8220   }
8221
8222   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8223       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8224       ARM::isBitFieldInvertedMask(~Mask)) {
8225     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8226     // where lsb(mask) == #shamt and masked bits of B are known zero.
8227     SDValue ShAmt = N00.getOperand(1);
8228     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8229     unsigned LSB = countTrailingZeros(Mask);
8230     if (ShAmtC != LSB)
8231       return SDValue();
8232
8233     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8234                       DAG.getConstant(~Mask, MVT::i32));
8235
8236     // Do not add new nodes to DAG combiner worklist.
8237     DCI.CombineTo(N, Res, false);
8238   }
8239
8240   return SDValue();
8241 }
8242
8243 static SDValue PerformXORCombine(SDNode *N,
8244                                  TargetLowering::DAGCombinerInfo &DCI,
8245                                  const ARMSubtarget *Subtarget) {
8246   EVT VT = N->getValueType(0);
8247   SelectionDAG &DAG = DCI.DAG;
8248
8249   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8250     return SDValue();
8251
8252   if (!Subtarget->isThumb1Only()) {
8253     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8254     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8255     if (Result.getNode())
8256       return Result;
8257   }
8258
8259   return SDValue();
8260 }
8261
8262 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8263 /// the bits being cleared by the AND are not demanded by the BFI.
8264 static SDValue PerformBFICombine(SDNode *N,
8265                                  TargetLowering::DAGCombinerInfo &DCI) {
8266   SDValue N1 = N->getOperand(1);
8267   if (N1.getOpcode() == ISD::AND) {
8268     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8269     if (!N11C)
8270       return SDValue();
8271     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8272     unsigned LSB = countTrailingZeros(~InvMask);
8273     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8274     unsigned Mask = (1 << Width)-1;
8275     unsigned Mask2 = N11C->getZExtValue();
8276     if ((Mask & (~Mask2)) == 0)
8277       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8278                              N->getOperand(0), N1.getOperand(0),
8279                              N->getOperand(2));
8280   }
8281   return SDValue();
8282 }
8283
8284 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8285 /// ARMISD::VMOVRRD.
8286 static SDValue PerformVMOVRRDCombine(SDNode *N,
8287                                      TargetLowering::DAGCombinerInfo &DCI) {
8288   // vmovrrd(vmovdrr x, y) -> x,y
8289   SDValue InDouble = N->getOperand(0);
8290   if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8291     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8292
8293   // vmovrrd(load f64) -> (load i32), (load i32)
8294   SDNode *InNode = InDouble.getNode();
8295   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8296       InNode->getValueType(0) == MVT::f64 &&
8297       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8298       !cast<LoadSDNode>(InNode)->isVolatile()) {
8299     // TODO: Should this be done for non-FrameIndex operands?
8300     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8301
8302     SelectionDAG &DAG = DCI.DAG;
8303     SDLoc DL(LD);
8304     SDValue BasePtr = LD->getBasePtr();
8305     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8306                                  LD->getPointerInfo(), LD->isVolatile(),
8307                                  LD->isNonTemporal(), LD->isInvariant(),
8308                                  LD->getAlignment());
8309
8310     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8311                                     DAG.getConstant(4, MVT::i32));
8312     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8313                                  LD->getPointerInfo(), LD->isVolatile(),
8314                                  LD->isNonTemporal(), LD->isInvariant(),
8315                                  std::min(4U, LD->getAlignment() / 2));
8316
8317     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8318     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8319     DCI.RemoveFromWorklist(LD);
8320     DAG.DeleteNode(LD);
8321     return Result;
8322   }
8323
8324   return SDValue();
8325 }
8326
8327 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8328 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8329 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8330   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8331   SDValue Op0 = N->getOperand(0);
8332   SDValue Op1 = N->getOperand(1);
8333   if (Op0.getOpcode() == ISD::BITCAST)
8334     Op0 = Op0.getOperand(0);
8335   if (Op1.getOpcode() == ISD::BITCAST)
8336     Op1 = Op1.getOperand(0);
8337   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8338       Op0.getNode() == Op1.getNode() &&
8339       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8340     return DAG.getNode(ISD::BITCAST, SDLoc(N),
8341                        N->getValueType(0), Op0.getOperand(0));
8342   return SDValue();
8343 }
8344
8345 /// PerformSTORECombine - Target-specific dag combine xforms for
8346 /// ISD::STORE.
8347 static SDValue PerformSTORECombine(SDNode *N,
8348                                    TargetLowering::DAGCombinerInfo &DCI) {
8349   StoreSDNode *St = cast<StoreSDNode>(N);
8350   if (St->isVolatile())
8351     return SDValue();
8352
8353   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
8354   // pack all of the elements in one place.  Next, store to memory in fewer
8355   // chunks.
8356   SDValue StVal = St->getValue();
8357   EVT VT = StVal.getValueType();
8358   if (St->isTruncatingStore() && VT.isVector()) {
8359     SelectionDAG &DAG = DCI.DAG;
8360     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8361     EVT StVT = St->getMemoryVT();
8362     unsigned NumElems = VT.getVectorNumElements();
8363     assert(StVT != VT && "Cannot truncate to the same type");
8364     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8365     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8366
8367     // From, To sizes and ElemCount must be pow of two
8368     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8369
8370     // We are going to use the original vector elt for storing.
8371     // Accumulated smaller vector elements must be a multiple of the store size.
8372     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8373
8374     unsigned SizeRatio  = FromEltSz / ToEltSz;
8375     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8376
8377     // Create a type on which we perform the shuffle.
8378     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8379                                      NumElems*SizeRatio);
8380     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8381
8382     SDLoc DL(St);
8383     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8384     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8385     for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
8386
8387     // Can't shuffle using an illegal type.
8388     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8389
8390     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8391                                 DAG.getUNDEF(WideVec.getValueType()),
8392                                 ShuffleVec.data());
8393     // At this point all of the data is stored at the bottom of the
8394     // register. We now need to save it to mem.
8395
8396     // Find the largest store unit
8397     MVT StoreType = MVT::i8;
8398     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8399          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8400       MVT Tp = (MVT::SimpleValueType)tp;
8401       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8402         StoreType = Tp;
8403     }
8404     // Didn't find a legal store type.
8405     if (!TLI.isTypeLegal(StoreType))
8406       return SDValue();
8407
8408     // Bitcast the original vector into a vector of store-size units
8409     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8410             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8411     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8412     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8413     SmallVector<SDValue, 8> Chains;
8414     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8415                                         TLI.getPointerTy());
8416     SDValue BasePtr = St->getBasePtr();
8417
8418     // Perform one or more big stores into memory.
8419     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8420     for (unsigned I = 0; I < E; I++) {
8421       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8422                                    StoreType, ShuffWide,
8423                                    DAG.getIntPtrConstant(I));
8424       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8425                                 St->getPointerInfo(), St->isVolatile(),
8426                                 St->isNonTemporal(), St->getAlignment());
8427       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8428                             Increment);
8429       Chains.push_back(Ch);
8430     }
8431     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
8432   }
8433
8434   if (!ISD::isNormalStore(St))
8435     return SDValue();
8436
8437   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8438   // ARM stores of arguments in the same cache line.
8439   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8440       StVal.getNode()->hasOneUse()) {
8441     SelectionDAG  &DAG = DCI.DAG;
8442     bool isBigEndian = DAG.getTargetLoweringInfo().isBigEndian();
8443     SDLoc DL(St);
8444     SDValue BasePtr = St->getBasePtr();
8445     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8446                                   StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
8447                                   BasePtr, St->getPointerInfo(), St->isVolatile(),
8448                                   St->isNonTemporal(), St->getAlignment());
8449
8450     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8451                                     DAG.getConstant(4, MVT::i32));
8452     return DAG.getStore(NewST1.getValue(0), DL,
8453                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
8454                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8455                         St->isNonTemporal(),
8456                         std::min(4U, St->getAlignment() / 2));
8457   }
8458
8459   if (StVal.getValueType() != MVT::i64 ||
8460       StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8461     return SDValue();
8462
8463   // Bitcast an i64 store extracted from a vector to f64.
8464   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8465   SelectionDAG &DAG = DCI.DAG;
8466   SDLoc dl(StVal);
8467   SDValue IntVec = StVal.getOperand(0);
8468   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8469                                  IntVec.getValueType().getVectorNumElements());
8470   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8471   SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8472                                Vec, StVal.getOperand(1));
8473   dl = SDLoc(N);
8474   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8475   // Make the DAGCombiner fold the bitcasts.
8476   DCI.AddToWorklist(Vec.getNode());
8477   DCI.AddToWorklist(ExtElt.getNode());
8478   DCI.AddToWorklist(V.getNode());
8479   return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8480                       St->getPointerInfo(), St->isVolatile(),
8481                       St->isNonTemporal(), St->getAlignment(),
8482                       St->getTBAAInfo());
8483 }
8484
8485 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8486 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8487 /// i64 vector to have f64 elements, since the value can then be loaded
8488 /// directly into a VFP register.
8489 static bool hasNormalLoadOperand(SDNode *N) {
8490   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8491   for (unsigned i = 0; i < NumElts; ++i) {
8492     SDNode *Elt = N->getOperand(i).getNode();
8493     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8494       return true;
8495   }
8496   return false;
8497 }
8498
8499 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8500 /// ISD::BUILD_VECTOR.
8501 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8502                                           TargetLowering::DAGCombinerInfo &DCI){
8503   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8504   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
8505   // into a pair of GPRs, which is fine when the value is used as a scalar,
8506   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8507   SelectionDAG &DAG = DCI.DAG;
8508   if (N->getNumOperands() == 2) {
8509     SDValue RV = PerformVMOVDRRCombine(N, DAG);
8510     if (RV.getNode())
8511       return RV;
8512   }
8513
8514   // Load i64 elements as f64 values so that type legalization does not split
8515   // them up into i32 values.
8516   EVT VT = N->getValueType(0);
8517   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8518     return SDValue();
8519   SDLoc dl(N);
8520   SmallVector<SDValue, 8> Ops;
8521   unsigned NumElts = VT.getVectorNumElements();
8522   for (unsigned i = 0; i < NumElts; ++i) {
8523     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8524     Ops.push_back(V);
8525     // Make the DAGCombiner fold the bitcast.
8526     DCI.AddToWorklist(V.getNode());
8527   }
8528   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8529   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8530   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8531 }
8532
8533 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8534 static SDValue
8535 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8536   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8537   // At that time, we may have inserted bitcasts from integer to float.
8538   // If these bitcasts have survived DAGCombine, change the lowering of this
8539   // BUILD_VECTOR in something more vector friendly, i.e., that does not
8540   // force to use floating point types.
8541
8542   // Make sure we can change the type of the vector.
8543   // This is possible iff:
8544   // 1. The vector is only used in a bitcast to a integer type. I.e.,
8545   //    1.1. Vector is used only once.
8546   //    1.2. Use is a bit convert to an integer type.
8547   // 2. The size of its operands are 32-bits (64-bits are not legal).
8548   EVT VT = N->getValueType(0);
8549   EVT EltVT = VT.getVectorElementType();
8550
8551   // Check 1.1. and 2.
8552   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8553     return SDValue();
8554
8555   // By construction, the input type must be float.
8556   assert(EltVT == MVT::f32 && "Unexpected type!");
8557
8558   // Check 1.2.
8559   SDNode *Use = *N->use_begin();
8560   if (Use->getOpcode() != ISD::BITCAST ||
8561       Use->getValueType(0).isFloatingPoint())
8562     return SDValue();
8563
8564   // Check profitability.
8565   // Model is, if more than half of the relevant operands are bitcast from
8566   // i32, turn the build_vector into a sequence of insert_vector_elt.
8567   // Relevant operands are everything that is not statically
8568   // (i.e., at compile time) bitcasted.
8569   unsigned NumOfBitCastedElts = 0;
8570   unsigned NumElts = VT.getVectorNumElements();
8571   unsigned NumOfRelevantElts = NumElts;
8572   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8573     SDValue Elt = N->getOperand(Idx);
8574     if (Elt->getOpcode() == ISD::BITCAST) {
8575       // Assume only bit cast to i32 will go away.
8576       if (Elt->getOperand(0).getValueType() == MVT::i32)
8577         ++NumOfBitCastedElts;
8578     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8579       // Constants are statically casted, thus do not count them as
8580       // relevant operands.
8581       --NumOfRelevantElts;
8582   }
8583
8584   // Check if more than half of the elements require a non-free bitcast.
8585   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8586     return SDValue();
8587
8588   SelectionDAG &DAG = DCI.DAG;
8589   // Create the new vector type.
8590   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8591   // Check if the type is legal.
8592   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8593   if (!TLI.isTypeLegal(VecVT))
8594     return SDValue();
8595
8596   // Combine:
8597   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8598   // => BITCAST INSERT_VECTOR_ELT
8599   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8600   //                      (BITCAST EN), N.
8601   SDValue Vec = DAG.getUNDEF(VecVT);
8602   SDLoc dl(N);
8603   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8604     SDValue V = N->getOperand(Idx);
8605     if (V.getOpcode() == ISD::UNDEF)
8606       continue;
8607     if (V.getOpcode() == ISD::BITCAST &&
8608         V->getOperand(0).getValueType() == MVT::i32)
8609       // Fold obvious case.
8610       V = V.getOperand(0);
8611     else {
8612       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
8613       // Make the DAGCombiner fold the bitcasts.
8614       DCI.AddToWorklist(V.getNode());
8615     }
8616     SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
8617     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8618   }
8619   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8620   // Make the DAGCombiner fold the bitcasts.
8621   DCI.AddToWorklist(Vec.getNode());
8622   return Vec;
8623 }
8624
8625 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8626 /// ISD::INSERT_VECTOR_ELT.
8627 static SDValue PerformInsertEltCombine(SDNode *N,
8628                                        TargetLowering::DAGCombinerInfo &DCI) {
8629   // Bitcast an i64 load inserted into a vector to f64.
8630   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8631   EVT VT = N->getValueType(0);
8632   SDNode *Elt = N->getOperand(1).getNode();
8633   if (VT.getVectorElementType() != MVT::i64 ||
8634       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8635     return SDValue();
8636
8637   SelectionDAG &DAG = DCI.DAG;
8638   SDLoc dl(N);
8639   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8640                                  VT.getVectorNumElements());
8641   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8642   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8643   // Make the DAGCombiner fold the bitcasts.
8644   DCI.AddToWorklist(Vec.getNode());
8645   DCI.AddToWorklist(V.getNode());
8646   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8647                                Vec, V, N->getOperand(2));
8648   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8649 }
8650
8651 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8652 /// ISD::VECTOR_SHUFFLE.
8653 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8654   // The LLVM shufflevector instruction does not require the shuffle mask
8655   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8656   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
8657   // operands do not match the mask length, they are extended by concatenating
8658   // them with undef vectors.  That is probably the right thing for other
8659   // targets, but for NEON it is better to concatenate two double-register
8660   // size vector operands into a single quad-register size vector.  Do that
8661   // transformation here:
8662   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
8663   //   shuffle(concat(v1, v2), undef)
8664   SDValue Op0 = N->getOperand(0);
8665   SDValue Op1 = N->getOperand(1);
8666   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8667       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8668       Op0.getNumOperands() != 2 ||
8669       Op1.getNumOperands() != 2)
8670     return SDValue();
8671   SDValue Concat0Op1 = Op0.getOperand(1);
8672   SDValue Concat1Op1 = Op1.getOperand(1);
8673   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8674       Concat1Op1.getOpcode() != ISD::UNDEF)
8675     return SDValue();
8676   // Skip the transformation if any of the types are illegal.
8677   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8678   EVT VT = N->getValueType(0);
8679   if (!TLI.isTypeLegal(VT) ||
8680       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8681       !TLI.isTypeLegal(Concat1Op1.getValueType()))
8682     return SDValue();
8683
8684   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
8685                                   Op0.getOperand(0), Op1.getOperand(0));
8686   // Translate the shuffle mask.
8687   SmallVector<int, 16> NewMask;
8688   unsigned NumElts = VT.getVectorNumElements();
8689   unsigned HalfElts = NumElts/2;
8690   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8691   for (unsigned n = 0; n < NumElts; ++n) {
8692     int MaskElt = SVN->getMaskElt(n);
8693     int NewElt = -1;
8694     if (MaskElt < (int)HalfElts)
8695       NewElt = MaskElt;
8696     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8697       NewElt = HalfElts + MaskElt - NumElts;
8698     NewMask.push_back(NewElt);
8699   }
8700   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
8701                               DAG.getUNDEF(VT), NewMask.data());
8702 }
8703
8704 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
8705 /// NEON load/store intrinsics to merge base address updates.
8706 static SDValue CombineBaseUpdate(SDNode *N,
8707                                  TargetLowering::DAGCombinerInfo &DCI) {
8708   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8709     return SDValue();
8710
8711   SelectionDAG &DAG = DCI.DAG;
8712   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8713                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8714   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
8715   SDValue Addr = N->getOperand(AddrOpIdx);
8716
8717   // Search for a use of the address operand that is an increment.
8718   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8719          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8720     SDNode *User = *UI;
8721     if (User->getOpcode() != ISD::ADD ||
8722         UI.getUse().getResNo() != Addr.getResNo())
8723       continue;
8724
8725     // Check that the add is independent of the load/store.  Otherwise, folding
8726     // it would create a cycle.
8727     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8728       continue;
8729
8730     // Find the new opcode for the updating load/store.
8731     bool isLoad = true;
8732     bool isLaneOp = false;
8733     unsigned NewOpc = 0;
8734     unsigned NumVecs = 0;
8735     if (isIntrinsic) {
8736       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8737       switch (IntNo) {
8738       default: llvm_unreachable("unexpected intrinsic for Neon base update");
8739       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
8740         NumVecs = 1; break;
8741       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
8742         NumVecs = 2; break;
8743       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
8744         NumVecs = 3; break;
8745       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
8746         NumVecs = 4; break;
8747       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8748         NumVecs = 2; isLaneOp = true; break;
8749       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8750         NumVecs = 3; isLaneOp = true; break;
8751       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8752         NumVecs = 4; isLaneOp = true; break;
8753       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
8754         NumVecs = 1; isLoad = false; break;
8755       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
8756         NumVecs = 2; isLoad = false; break;
8757       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
8758         NumVecs = 3; isLoad = false; break;
8759       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
8760         NumVecs = 4; isLoad = false; break;
8761       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8762         NumVecs = 2; isLoad = false; isLaneOp = true; break;
8763       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8764         NumVecs = 3; isLoad = false; isLaneOp = true; break;
8765       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8766         NumVecs = 4; isLoad = false; isLaneOp = true; break;
8767       }
8768     } else {
8769       isLaneOp = true;
8770       switch (N->getOpcode()) {
8771       default: llvm_unreachable("unexpected opcode for Neon base update");
8772       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8773       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8774       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8775       }
8776     }
8777
8778     // Find the size of memory referenced by the load/store.
8779     EVT VecTy;
8780     if (isLoad)
8781       VecTy = N->getValueType(0);
8782     else
8783       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8784     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8785     if (isLaneOp)
8786       NumBytes /= VecTy.getVectorNumElements();
8787
8788     // If the increment is a constant, it must match the memory ref size.
8789     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8790     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8791       uint64_t IncVal = CInc->getZExtValue();
8792       if (IncVal != NumBytes)
8793         continue;
8794     } else if (NumBytes >= 3 * 16) {
8795       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8796       // separate instructions that make it harder to use a non-constant update.
8797       continue;
8798     }
8799
8800     // Create the new updating load/store node.
8801     EVT Tys[6];
8802     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
8803     unsigned n;
8804     for (n = 0; n < NumResultVecs; ++n)
8805       Tys[n] = VecTy;
8806     Tys[n++] = MVT::i32;
8807     Tys[n] = MVT::Other;
8808     SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumResultVecs+2));
8809     SmallVector<SDValue, 8> Ops;
8810     Ops.push_back(N->getOperand(0)); // incoming chain
8811     Ops.push_back(N->getOperand(AddrOpIdx));
8812     Ops.push_back(Inc);
8813     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
8814       Ops.push_back(N->getOperand(i));
8815     }
8816     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8817     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
8818                                            Ops, MemInt->getMemoryVT(),
8819                                            MemInt->getMemOperand());
8820
8821     // Update the uses.
8822     std::vector<SDValue> NewResults;
8823     for (unsigned i = 0; i < NumResultVecs; ++i) {
8824       NewResults.push_back(SDValue(UpdN.getNode(), i));
8825     }
8826     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8827     DCI.CombineTo(N, NewResults);
8828     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8829
8830     break;
8831   }
8832   return SDValue();
8833 }
8834
8835 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
8836 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
8837 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
8838 /// return true.
8839 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8840   SelectionDAG &DAG = DCI.DAG;
8841   EVT VT = N->getValueType(0);
8842   // vldN-dup instructions only support 64-bit vectors for N > 1.
8843   if (!VT.is64BitVector())
8844     return false;
8845
8846   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
8847   SDNode *VLD = N->getOperand(0).getNode();
8848   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
8849     return false;
8850   unsigned NumVecs = 0;
8851   unsigned NewOpc = 0;
8852   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
8853   if (IntNo == Intrinsic::arm_neon_vld2lane) {
8854     NumVecs = 2;
8855     NewOpc = ARMISD::VLD2DUP;
8856   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
8857     NumVecs = 3;
8858     NewOpc = ARMISD::VLD3DUP;
8859   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
8860     NumVecs = 4;
8861     NewOpc = ARMISD::VLD4DUP;
8862   } else {
8863     return false;
8864   }
8865
8866   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
8867   // numbers match the load.
8868   unsigned VLDLaneNo =
8869     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
8870   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8871        UI != UE; ++UI) {
8872     // Ignore uses of the chain result.
8873     if (UI.getUse().getResNo() == NumVecs)
8874       continue;
8875     SDNode *User = *UI;
8876     if (User->getOpcode() != ARMISD::VDUPLANE ||
8877         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
8878       return false;
8879   }
8880
8881   // Create the vldN-dup node.
8882   EVT Tys[5];
8883   unsigned n;
8884   for (n = 0; n < NumVecs; ++n)
8885     Tys[n] = VT;
8886   Tys[n] = MVT::Other;
8887   SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumVecs+1));
8888   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
8889   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
8890   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
8891                                            Ops, VLDMemInt->getMemoryVT(),
8892                                            VLDMemInt->getMemOperand());
8893
8894   // Update the uses.
8895   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8896        UI != UE; ++UI) {
8897     unsigned ResNo = UI.getUse().getResNo();
8898     // Ignore uses of the chain result.
8899     if (ResNo == NumVecs)
8900       continue;
8901     SDNode *User = *UI;
8902     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
8903   }
8904
8905   // Now the vldN-lane intrinsic is dead except for its chain result.
8906   // Update uses of the chain.
8907   std::vector<SDValue> VLDDupResults;
8908   for (unsigned n = 0; n < NumVecs; ++n)
8909     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
8910   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
8911   DCI.CombineTo(VLD, VLDDupResults);
8912
8913   return true;
8914 }
8915
8916 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
8917 /// ARMISD::VDUPLANE.
8918 static SDValue PerformVDUPLANECombine(SDNode *N,
8919                                       TargetLowering::DAGCombinerInfo &DCI) {
8920   SDValue Op = N->getOperand(0);
8921
8922   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
8923   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
8924   if (CombineVLDDUP(N, DCI))
8925     return SDValue(N, 0);
8926
8927   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
8928   // redundant.  Ignore bit_converts for now; element sizes are checked below.
8929   while (Op.getOpcode() == ISD::BITCAST)
8930     Op = Op.getOperand(0);
8931   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
8932     return SDValue();
8933
8934   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
8935   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
8936   // The canonical VMOV for a zero vector uses a 32-bit element size.
8937   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8938   unsigned EltBits;
8939   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
8940     EltSize = 8;
8941   EVT VT = N->getValueType(0);
8942   if (EltSize > VT.getVectorElementType().getSizeInBits())
8943     return SDValue();
8944
8945   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
8946 }
8947
8948 // isConstVecPow2 - Return true if each vector element is a power of 2, all
8949 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
8950 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
8951 {
8952   integerPart cN;
8953   integerPart c0 = 0;
8954   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
8955        I != E; I++) {
8956     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
8957     if (!C)
8958       return false;
8959
8960     bool isExact;
8961     APFloat APF = C->getValueAPF();
8962     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
8963         != APFloat::opOK || !isExact)
8964       return false;
8965
8966     c0 = (I == 0) ? cN : c0;
8967     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
8968       return false;
8969   }
8970   C = c0;
8971   return true;
8972 }
8973
8974 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
8975 /// can replace combinations of VMUL and VCVT (floating-point to integer)
8976 /// when the VMUL has a constant operand that is a power of 2.
8977 ///
8978 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
8979 ///  vmul.f32        d16, d17, d16
8980 ///  vcvt.s32.f32    d16, d16
8981 /// becomes:
8982 ///  vcvt.s32.f32    d16, d16, #3
8983 static SDValue PerformVCVTCombine(SDNode *N,
8984                                   TargetLowering::DAGCombinerInfo &DCI,
8985                                   const ARMSubtarget *Subtarget) {
8986   SelectionDAG &DAG = DCI.DAG;
8987   SDValue Op = N->getOperand(0);
8988
8989   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
8990       Op.getOpcode() != ISD::FMUL)
8991     return SDValue();
8992
8993   uint64_t C;
8994   SDValue N0 = Op->getOperand(0);
8995   SDValue ConstVec = Op->getOperand(1);
8996   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
8997
8998   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
8999       !isConstVecPow2(ConstVec, isSigned, C))
9000     return SDValue();
9001
9002   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9003   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9004   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9005     // These instructions only exist converting from f32 to i32. We can handle
9006     // smaller integers by generating an extra truncate, but larger ones would
9007     // be lossy.
9008     return SDValue();
9009   }
9010
9011   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9012     Intrinsic::arm_neon_vcvtfp2fxu;
9013   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9014   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9015                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9016                                  DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9017                                  DAG.getConstant(Log2_64(C), MVT::i32));
9018
9019   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9020     FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9021
9022   return FixConv;
9023 }
9024
9025 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9026 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9027 /// when the VDIV has a constant operand that is a power of 2.
9028 ///
9029 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9030 ///  vcvt.f32.s32    d16, d16
9031 ///  vdiv.f32        d16, d17, d16
9032 /// becomes:
9033 ///  vcvt.f32.s32    d16, d16, #3
9034 static SDValue PerformVDIVCombine(SDNode *N,
9035                                   TargetLowering::DAGCombinerInfo &DCI,
9036                                   const ARMSubtarget *Subtarget) {
9037   SelectionDAG &DAG = DCI.DAG;
9038   SDValue Op = N->getOperand(0);
9039   unsigned OpOpcode = Op.getNode()->getOpcode();
9040
9041   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9042       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9043     return SDValue();
9044
9045   uint64_t C;
9046   SDValue ConstVec = N->getOperand(1);
9047   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9048
9049   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9050       !isConstVecPow2(ConstVec, isSigned, C))
9051     return SDValue();
9052
9053   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9054   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9055   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9056     // These instructions only exist converting from i32 to f32. We can handle
9057     // smaller integers by generating an extra extend, but larger ones would
9058     // be lossy.
9059     return SDValue();
9060   }
9061
9062   SDValue ConvInput = Op.getOperand(0);
9063   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9064   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9065     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9066                             SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9067                             ConvInput);
9068
9069   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9070     Intrinsic::arm_neon_vcvtfxu2fp;
9071   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9072                      Op.getValueType(),
9073                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
9074                      ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9075 }
9076
9077 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9078 /// operand of a vector shift operation, where all the elements of the
9079 /// build_vector must have the same constant integer value.
9080 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9081   // Ignore bit_converts.
9082   while (Op.getOpcode() == ISD::BITCAST)
9083     Op = Op.getOperand(0);
9084   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9085   APInt SplatBits, SplatUndef;
9086   unsigned SplatBitSize;
9087   bool HasAnyUndefs;
9088   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9089                                       HasAnyUndefs, ElementBits) ||
9090       SplatBitSize > ElementBits)
9091     return false;
9092   Cnt = SplatBits.getSExtValue();
9093   return true;
9094 }
9095
9096 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9097 /// operand of a vector shift left operation.  That value must be in the range:
9098 ///   0 <= Value < ElementBits for a left shift; or
9099 ///   0 <= Value <= ElementBits for a long left shift.
9100 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9101   assert(VT.isVector() && "vector shift count is not a vector type");
9102   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9103   if (! getVShiftImm(Op, ElementBits, Cnt))
9104     return false;
9105   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9106 }
9107
9108 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9109 /// operand of a vector shift right operation.  For a shift opcode, the value
9110 /// is positive, but for an intrinsic the value count must be negative. The
9111 /// absolute value must be in the range:
9112 ///   1 <= |Value| <= ElementBits for a right shift; or
9113 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9114 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9115                          int64_t &Cnt) {
9116   assert(VT.isVector() && "vector shift count is not a vector type");
9117   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9118   if (! getVShiftImm(Op, ElementBits, Cnt))
9119     return false;
9120   if (isIntrinsic)
9121     Cnt = -Cnt;
9122   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9123 }
9124
9125 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9126 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9127   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9128   switch (IntNo) {
9129   default:
9130     // Don't do anything for most intrinsics.
9131     break;
9132
9133   // Vector shifts: check for immediate versions and lower them.
9134   // Note: This is done during DAG combining instead of DAG legalizing because
9135   // the build_vectors for 64-bit vector element shift counts are generally
9136   // not legal, and it is hard to see their values after they get legalized to
9137   // loads from a constant pool.
9138   case Intrinsic::arm_neon_vshifts:
9139   case Intrinsic::arm_neon_vshiftu:
9140   case Intrinsic::arm_neon_vrshifts:
9141   case Intrinsic::arm_neon_vrshiftu:
9142   case Intrinsic::arm_neon_vrshiftn:
9143   case Intrinsic::arm_neon_vqshifts:
9144   case Intrinsic::arm_neon_vqshiftu:
9145   case Intrinsic::arm_neon_vqshiftsu:
9146   case Intrinsic::arm_neon_vqshiftns:
9147   case Intrinsic::arm_neon_vqshiftnu:
9148   case Intrinsic::arm_neon_vqshiftnsu:
9149   case Intrinsic::arm_neon_vqrshiftns:
9150   case Intrinsic::arm_neon_vqrshiftnu:
9151   case Intrinsic::arm_neon_vqrshiftnsu: {
9152     EVT VT = N->getOperand(1).getValueType();
9153     int64_t Cnt;
9154     unsigned VShiftOpc = 0;
9155
9156     switch (IntNo) {
9157     case Intrinsic::arm_neon_vshifts:
9158     case Intrinsic::arm_neon_vshiftu:
9159       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9160         VShiftOpc = ARMISD::VSHL;
9161         break;
9162       }
9163       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9164         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9165                      ARMISD::VSHRs : ARMISD::VSHRu);
9166         break;
9167       }
9168       return SDValue();
9169
9170     case Intrinsic::arm_neon_vrshifts:
9171     case Intrinsic::arm_neon_vrshiftu:
9172       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9173         break;
9174       return SDValue();
9175
9176     case Intrinsic::arm_neon_vqshifts:
9177     case Intrinsic::arm_neon_vqshiftu:
9178       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9179         break;
9180       return SDValue();
9181
9182     case Intrinsic::arm_neon_vqshiftsu:
9183       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9184         break;
9185       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9186
9187     case Intrinsic::arm_neon_vrshiftn:
9188     case Intrinsic::arm_neon_vqshiftns:
9189     case Intrinsic::arm_neon_vqshiftnu:
9190     case Intrinsic::arm_neon_vqshiftnsu:
9191     case Intrinsic::arm_neon_vqrshiftns:
9192     case Intrinsic::arm_neon_vqrshiftnu:
9193     case Intrinsic::arm_neon_vqrshiftnsu:
9194       // Narrowing shifts require an immediate right shift.
9195       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9196         break;
9197       llvm_unreachable("invalid shift count for narrowing vector shift "
9198                        "intrinsic");
9199
9200     default:
9201       llvm_unreachable("unhandled vector shift");
9202     }
9203
9204     switch (IntNo) {
9205     case Intrinsic::arm_neon_vshifts:
9206     case Intrinsic::arm_neon_vshiftu:
9207       // Opcode already set above.
9208       break;
9209     case Intrinsic::arm_neon_vrshifts:
9210       VShiftOpc = ARMISD::VRSHRs; break;
9211     case Intrinsic::arm_neon_vrshiftu:
9212       VShiftOpc = ARMISD::VRSHRu; break;
9213     case Intrinsic::arm_neon_vrshiftn:
9214       VShiftOpc = ARMISD::VRSHRN; break;
9215     case Intrinsic::arm_neon_vqshifts:
9216       VShiftOpc = ARMISD::VQSHLs; break;
9217     case Intrinsic::arm_neon_vqshiftu:
9218       VShiftOpc = ARMISD::VQSHLu; break;
9219     case Intrinsic::arm_neon_vqshiftsu:
9220       VShiftOpc = ARMISD::VQSHLsu; break;
9221     case Intrinsic::arm_neon_vqshiftns:
9222       VShiftOpc = ARMISD::VQSHRNs; break;
9223     case Intrinsic::arm_neon_vqshiftnu:
9224       VShiftOpc = ARMISD::VQSHRNu; break;
9225     case Intrinsic::arm_neon_vqshiftnsu:
9226       VShiftOpc = ARMISD::VQSHRNsu; break;
9227     case Intrinsic::arm_neon_vqrshiftns:
9228       VShiftOpc = ARMISD::VQRSHRNs; break;
9229     case Intrinsic::arm_neon_vqrshiftnu:
9230       VShiftOpc = ARMISD::VQRSHRNu; break;
9231     case Intrinsic::arm_neon_vqrshiftnsu:
9232       VShiftOpc = ARMISD::VQRSHRNsu; break;
9233     }
9234
9235     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9236                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9237   }
9238
9239   case Intrinsic::arm_neon_vshiftins: {
9240     EVT VT = N->getOperand(1).getValueType();
9241     int64_t Cnt;
9242     unsigned VShiftOpc = 0;
9243
9244     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9245       VShiftOpc = ARMISD::VSLI;
9246     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9247       VShiftOpc = ARMISD::VSRI;
9248     else {
9249       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9250     }
9251
9252     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9253                        N->getOperand(1), N->getOperand(2),
9254                        DAG.getConstant(Cnt, MVT::i32));
9255   }
9256
9257   case Intrinsic::arm_neon_vqrshifts:
9258   case Intrinsic::arm_neon_vqrshiftu:
9259     // No immediate versions of these to check for.
9260     break;
9261   }
9262
9263   return SDValue();
9264 }
9265
9266 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9267 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9268 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9269 /// vector element shift counts are generally not legal, and it is hard to see
9270 /// their values after they get legalized to loads from a constant pool.
9271 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9272                                    const ARMSubtarget *ST) {
9273   EVT VT = N->getValueType(0);
9274   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9275     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9276     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9277     SDValue N1 = N->getOperand(1);
9278     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9279       SDValue N0 = N->getOperand(0);
9280       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9281           DAG.MaskedValueIsZero(N0.getOperand(0),
9282                                 APInt::getHighBitsSet(32, 16)))
9283         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9284     }
9285   }
9286
9287   // Nothing to be done for scalar shifts.
9288   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9289   if (!VT.isVector() || !TLI.isTypeLegal(VT))
9290     return SDValue();
9291
9292   assert(ST->hasNEON() && "unexpected vector shift");
9293   int64_t Cnt;
9294
9295   switch (N->getOpcode()) {
9296   default: llvm_unreachable("unexpected shift opcode");
9297
9298   case ISD::SHL:
9299     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9300       return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9301                          DAG.getConstant(Cnt, MVT::i32));
9302     break;
9303
9304   case ISD::SRA:
9305   case ISD::SRL:
9306     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9307       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9308                             ARMISD::VSHRs : ARMISD::VSHRu);
9309       return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9310                          DAG.getConstant(Cnt, MVT::i32));
9311     }
9312   }
9313   return SDValue();
9314 }
9315
9316 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9317 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9318 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9319                                     const ARMSubtarget *ST) {
9320   SDValue N0 = N->getOperand(0);
9321
9322   // Check for sign- and zero-extensions of vector extract operations of 8-
9323   // and 16-bit vector elements.  NEON supports these directly.  They are
9324   // handled during DAG combining because type legalization will promote them
9325   // to 32-bit types and it is messy to recognize the operations after that.
9326   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9327     SDValue Vec = N0.getOperand(0);
9328     SDValue Lane = N0.getOperand(1);
9329     EVT VT = N->getValueType(0);
9330     EVT EltVT = N0.getValueType();
9331     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9332
9333     if (VT == MVT::i32 &&
9334         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9335         TLI.isTypeLegal(Vec.getValueType()) &&
9336         isa<ConstantSDNode>(Lane)) {
9337
9338       unsigned Opc = 0;
9339       switch (N->getOpcode()) {
9340       default: llvm_unreachable("unexpected opcode");
9341       case ISD::SIGN_EXTEND:
9342         Opc = ARMISD::VGETLANEs;
9343         break;
9344       case ISD::ZERO_EXTEND:
9345       case ISD::ANY_EXTEND:
9346         Opc = ARMISD::VGETLANEu;
9347         break;
9348       }
9349       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9350     }
9351   }
9352
9353   return SDValue();
9354 }
9355
9356 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9357 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9358 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9359                                        const ARMSubtarget *ST) {
9360   // If the target supports NEON, try to use vmax/vmin instructions for f32
9361   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
9362   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
9363   // a NaN; only do the transformation when it matches that behavior.
9364
9365   // For now only do this when using NEON for FP operations; if using VFP, it
9366   // is not obvious that the benefit outweighs the cost of switching to the
9367   // NEON pipeline.
9368   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9369       N->getValueType(0) != MVT::f32)
9370     return SDValue();
9371
9372   SDValue CondLHS = N->getOperand(0);
9373   SDValue CondRHS = N->getOperand(1);
9374   SDValue LHS = N->getOperand(2);
9375   SDValue RHS = N->getOperand(3);
9376   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9377
9378   unsigned Opcode = 0;
9379   bool IsReversed;
9380   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9381     IsReversed = false; // x CC y ? x : y
9382   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9383     IsReversed = true ; // x CC y ? y : x
9384   } else {
9385     return SDValue();
9386   }
9387
9388   bool IsUnordered;
9389   switch (CC) {
9390   default: break;
9391   case ISD::SETOLT:
9392   case ISD::SETOLE:
9393   case ISD::SETLT:
9394   case ISD::SETLE:
9395   case ISD::SETULT:
9396   case ISD::SETULE:
9397     // If LHS is NaN, an ordered comparison will be false and the result will
9398     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
9399     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9400     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9401     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9402       break;
9403     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9404     // will return -0, so vmin can only be used for unsafe math or if one of
9405     // the operands is known to be nonzero.
9406     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9407         !DAG.getTarget().Options.UnsafeFPMath &&
9408         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9409       break;
9410     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9411     break;
9412
9413   case ISD::SETOGT:
9414   case ISD::SETOGE:
9415   case ISD::SETGT:
9416   case ISD::SETGE:
9417   case ISD::SETUGT:
9418   case ISD::SETUGE:
9419     // If LHS is NaN, an ordered comparison will be false and the result will
9420     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
9421     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9422     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9423     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9424       break;
9425     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9426     // will return +0, so vmax can only be used for unsafe math or if one of
9427     // the operands is known to be nonzero.
9428     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9429         !DAG.getTarget().Options.UnsafeFPMath &&
9430         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9431       break;
9432     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9433     break;
9434   }
9435
9436   if (!Opcode)
9437     return SDValue();
9438   return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9439 }
9440
9441 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9442 SDValue
9443 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9444   SDValue Cmp = N->getOperand(4);
9445   if (Cmp.getOpcode() != ARMISD::CMPZ)
9446     // Only looking at EQ and NE cases.
9447     return SDValue();
9448
9449   EVT VT = N->getValueType(0);
9450   SDLoc dl(N);
9451   SDValue LHS = Cmp.getOperand(0);
9452   SDValue RHS = Cmp.getOperand(1);
9453   SDValue FalseVal = N->getOperand(0);
9454   SDValue TrueVal = N->getOperand(1);
9455   SDValue ARMcc = N->getOperand(2);
9456   ARMCC::CondCodes CC =
9457     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9458
9459   // Simplify
9460   //   mov     r1, r0
9461   //   cmp     r1, x
9462   //   mov     r0, y
9463   //   moveq   r0, x
9464   // to
9465   //   cmp     r0, x
9466   //   movne   r0, y
9467   //
9468   //   mov     r1, r0
9469   //   cmp     r1, x
9470   //   mov     r0, x
9471   //   movne   r0, y
9472   // to
9473   //   cmp     r0, x
9474   //   movne   r0, y
9475   /// FIXME: Turn this into a target neutral optimization?
9476   SDValue Res;
9477   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9478     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9479                       N->getOperand(3), Cmp);
9480   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9481     SDValue ARMcc;
9482     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9483     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9484                       N->getOperand(3), NewCmp);
9485   }
9486
9487   if (Res.getNode()) {
9488     APInt KnownZero, KnownOne;
9489     DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
9490     // Capture demanded bits information that would be otherwise lost.
9491     if (KnownZero == 0xfffffffe)
9492       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9493                         DAG.getValueType(MVT::i1));
9494     else if (KnownZero == 0xffffff00)
9495       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9496                         DAG.getValueType(MVT::i8));
9497     else if (KnownZero == 0xffff0000)
9498       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9499                         DAG.getValueType(MVT::i16));
9500   }
9501
9502   return Res;
9503 }
9504
9505 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9506                                              DAGCombinerInfo &DCI) const {
9507   switch (N->getOpcode()) {
9508   default: break;
9509   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
9510   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
9511   case ISD::SUB:        return PerformSUBCombine(N, DCI);
9512   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
9513   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
9514   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
9515   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
9516   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
9517   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
9518   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9519   case ISD::STORE:      return PerformSTORECombine(N, DCI);
9520   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
9521   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9522   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9523   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9524   case ISD::FP_TO_SINT:
9525   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9526   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
9527   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9528   case ISD::SHL:
9529   case ISD::SRA:
9530   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
9531   case ISD::SIGN_EXTEND:
9532   case ISD::ZERO_EXTEND:
9533   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9534   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9535   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9536   case ARMISD::VLD2DUP:
9537   case ARMISD::VLD3DUP:
9538   case ARMISD::VLD4DUP:
9539     return CombineBaseUpdate(N, DCI);
9540   case ARMISD::BUILD_VECTOR:
9541     return PerformARMBUILD_VECTORCombine(N, DCI);
9542   case ISD::INTRINSIC_VOID:
9543   case ISD::INTRINSIC_W_CHAIN:
9544     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9545     case Intrinsic::arm_neon_vld1:
9546     case Intrinsic::arm_neon_vld2:
9547     case Intrinsic::arm_neon_vld3:
9548     case Intrinsic::arm_neon_vld4:
9549     case Intrinsic::arm_neon_vld2lane:
9550     case Intrinsic::arm_neon_vld3lane:
9551     case Intrinsic::arm_neon_vld4lane:
9552     case Intrinsic::arm_neon_vst1:
9553     case Intrinsic::arm_neon_vst2:
9554     case Intrinsic::arm_neon_vst3:
9555     case Intrinsic::arm_neon_vst4:
9556     case Intrinsic::arm_neon_vst2lane:
9557     case Intrinsic::arm_neon_vst3lane:
9558     case Intrinsic::arm_neon_vst4lane:
9559       return CombineBaseUpdate(N, DCI);
9560     default: break;
9561     }
9562     break;
9563   }
9564   return SDValue();
9565 }
9566
9567 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9568                                                           EVT VT) const {
9569   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9570 }
9571
9572 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, unsigned,
9573                                                       bool *Fast) const {
9574   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9575   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9576
9577   switch (VT.getSimpleVT().SimpleTy) {
9578   default:
9579     return false;
9580   case MVT::i8:
9581   case MVT::i16:
9582   case MVT::i32: {
9583     // Unaligned access can use (for example) LRDB, LRDH, LDR
9584     if (AllowsUnaligned) {
9585       if (Fast)
9586         *Fast = Subtarget->hasV7Ops();
9587       return true;
9588     }
9589     return false;
9590   }
9591   case MVT::f64:
9592   case MVT::v2f64: {
9593     // For any little-endian targets with neon, we can support unaligned ld/st
9594     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9595     // A big-endian target may also explicitly support unaligned accesses
9596     if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9597       if (Fast)
9598         *Fast = true;
9599       return true;
9600     }
9601     return false;
9602   }
9603   }
9604 }
9605
9606 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9607                        unsigned AlignCheck) {
9608   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9609           (DstAlign == 0 || DstAlign % AlignCheck == 0));
9610 }
9611
9612 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9613                                            unsigned DstAlign, unsigned SrcAlign,
9614                                            bool IsMemset, bool ZeroMemset,
9615                                            bool MemcpyStrSrc,
9616                                            MachineFunction &MF) const {
9617   const Function *F = MF.getFunction();
9618
9619   // See if we can use NEON instructions for this...
9620   if ((!IsMemset || ZeroMemset) &&
9621       Subtarget->hasNEON() &&
9622       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
9623                                        Attribute::NoImplicitFloat)) {
9624     bool Fast;
9625     if (Size >= 16 &&
9626         (memOpAlign(SrcAlign, DstAlign, 16) ||
9627          (allowsUnalignedMemoryAccesses(MVT::v2f64, 0, &Fast) && Fast))) {
9628       return MVT::v2f64;
9629     } else if (Size >= 8 &&
9630                (memOpAlign(SrcAlign, DstAlign, 8) ||
9631                 (allowsUnalignedMemoryAccesses(MVT::f64, 0, &Fast) && Fast))) {
9632       return MVT::f64;
9633     }
9634   }
9635
9636   // Lowering to i32/i16 if the size permits.
9637   if (Size >= 4)
9638     return MVT::i32;
9639   else if (Size >= 2)
9640     return MVT::i16;
9641
9642   // Let the target-independent logic figure it out.
9643   return MVT::Other;
9644 }
9645
9646 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9647   if (Val.getOpcode() != ISD::LOAD)
9648     return false;
9649
9650   EVT VT1 = Val.getValueType();
9651   if (!VT1.isSimple() || !VT1.isInteger() ||
9652       !VT2.isSimple() || !VT2.isInteger())
9653     return false;
9654
9655   switch (VT1.getSimpleVT().SimpleTy) {
9656   default: break;
9657   case MVT::i1:
9658   case MVT::i8:
9659   case MVT::i16:
9660     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
9661     return true;
9662   }
9663
9664   return false;
9665 }
9666
9667 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
9668   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9669     return false;
9670
9671   if (!isTypeLegal(EVT::getEVT(Ty1)))
9672     return false;
9673
9674   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
9675
9676   // Assuming the caller doesn't have a zeroext or signext return parameter,
9677   // truncation all the way down to i1 is valid.
9678   return true;
9679 }
9680
9681
9682 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9683   if (V < 0)
9684     return false;
9685
9686   unsigned Scale = 1;
9687   switch (VT.getSimpleVT().SimpleTy) {
9688   default: return false;
9689   case MVT::i1:
9690   case MVT::i8:
9691     // Scale == 1;
9692     break;
9693   case MVT::i16:
9694     // Scale == 2;
9695     Scale = 2;
9696     break;
9697   case MVT::i32:
9698     // Scale == 4;
9699     Scale = 4;
9700     break;
9701   }
9702
9703   if ((V & (Scale - 1)) != 0)
9704     return false;
9705   V /= Scale;
9706   return V == (V & ((1LL << 5) - 1));
9707 }
9708
9709 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
9710                                       const ARMSubtarget *Subtarget) {
9711   bool isNeg = false;
9712   if (V < 0) {
9713     isNeg = true;
9714     V = - V;
9715   }
9716
9717   switch (VT.getSimpleVT().SimpleTy) {
9718   default: return false;
9719   case MVT::i1:
9720   case MVT::i8:
9721   case MVT::i16:
9722   case MVT::i32:
9723     // + imm12 or - imm8
9724     if (isNeg)
9725       return V == (V & ((1LL << 8) - 1));
9726     return V == (V & ((1LL << 12) - 1));
9727   case MVT::f32:
9728   case MVT::f64:
9729     // Same as ARM mode. FIXME: NEON?
9730     if (!Subtarget->hasVFP2())
9731       return false;
9732     if ((V & 3) != 0)
9733       return false;
9734     V >>= 2;
9735     return V == (V & ((1LL << 8) - 1));
9736   }
9737 }
9738
9739 /// isLegalAddressImmediate - Return true if the integer value can be used
9740 /// as the offset of the target addressing mode for load / store of the
9741 /// given type.
9742 static bool isLegalAddressImmediate(int64_t V, EVT VT,
9743                                     const ARMSubtarget *Subtarget) {
9744   if (V == 0)
9745     return true;
9746
9747   if (!VT.isSimple())
9748     return false;
9749
9750   if (Subtarget->isThumb1Only())
9751     return isLegalT1AddressImmediate(V, VT);
9752   else if (Subtarget->isThumb2())
9753     return isLegalT2AddressImmediate(V, VT, Subtarget);
9754
9755   // ARM mode.
9756   if (V < 0)
9757     V = - V;
9758   switch (VT.getSimpleVT().SimpleTy) {
9759   default: return false;
9760   case MVT::i1:
9761   case MVT::i8:
9762   case MVT::i32:
9763     // +- imm12
9764     return V == (V & ((1LL << 12) - 1));
9765   case MVT::i16:
9766     // +- imm8
9767     return V == (V & ((1LL << 8) - 1));
9768   case MVT::f32:
9769   case MVT::f64:
9770     if (!Subtarget->hasVFP2()) // FIXME: NEON?
9771       return false;
9772     if ((V & 3) != 0)
9773       return false;
9774     V >>= 2;
9775     return V == (V & ((1LL << 8) - 1));
9776   }
9777 }
9778
9779 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
9780                                                       EVT VT) const {
9781   int Scale = AM.Scale;
9782   if (Scale < 0)
9783     return false;
9784
9785   switch (VT.getSimpleVT().SimpleTy) {
9786   default: return false;
9787   case MVT::i1:
9788   case MVT::i8:
9789   case MVT::i16:
9790   case MVT::i32:
9791     if (Scale == 1)
9792       return true;
9793     // r + r << imm
9794     Scale = Scale & ~1;
9795     return Scale == 2 || Scale == 4 || Scale == 8;
9796   case MVT::i64:
9797     // r + r
9798     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9799       return true;
9800     return false;
9801   case MVT::isVoid:
9802     // Note, we allow "void" uses (basically, uses that aren't loads or
9803     // stores), because arm allows folding a scale into many arithmetic
9804     // operations.  This should be made more precise and revisited later.
9805
9806     // Allow r << imm, but the imm has to be a multiple of two.
9807     if (Scale & 1) return false;
9808     return isPowerOf2_32(Scale);
9809   }
9810 }
9811
9812 /// isLegalAddressingMode - Return true if the addressing mode represented
9813 /// by AM is legal for this target, for a load/store of the specified type.
9814 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9815                                               Type *Ty) const {
9816   EVT VT = getValueType(Ty, true);
9817   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
9818     return false;
9819
9820   // Can never fold addr of global into load/store.
9821   if (AM.BaseGV)
9822     return false;
9823
9824   switch (AM.Scale) {
9825   case 0:  // no scale reg, must be "r+i" or "r", or "i".
9826     break;
9827   case 1:
9828     if (Subtarget->isThumb1Only())
9829       return false;
9830     // FALL THROUGH.
9831   default:
9832     // ARM doesn't support any R+R*scale+imm addr modes.
9833     if (AM.BaseOffs)
9834       return false;
9835
9836     if (!VT.isSimple())
9837       return false;
9838
9839     if (Subtarget->isThumb2())
9840       return isLegalT2ScaledAddressingMode(AM, VT);
9841
9842     int Scale = AM.Scale;
9843     switch (VT.getSimpleVT().SimpleTy) {
9844     default: return false;
9845     case MVT::i1:
9846     case MVT::i8:
9847     case MVT::i32:
9848       if (Scale < 0) Scale = -Scale;
9849       if (Scale == 1)
9850         return true;
9851       // r + r << imm
9852       return isPowerOf2_32(Scale & ~1);
9853     case MVT::i16:
9854     case MVT::i64:
9855       // r + r
9856       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9857         return true;
9858       return false;
9859
9860     case MVT::isVoid:
9861       // Note, we allow "void" uses (basically, uses that aren't loads or
9862       // stores), because arm allows folding a scale into many arithmetic
9863       // operations.  This should be made more precise and revisited later.
9864
9865       // Allow r << imm, but the imm has to be a multiple of two.
9866       if (Scale & 1) return false;
9867       return isPowerOf2_32(Scale);
9868     }
9869   }
9870   return true;
9871 }
9872
9873 /// isLegalICmpImmediate - Return true if the specified immediate is legal
9874 /// icmp immediate, that is the target has icmp instructions which can compare
9875 /// a register against the immediate without having to materialize the
9876 /// immediate into a register.
9877 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
9878   // Thumb2 and ARM modes can use cmn for negative immediates.
9879   if (!Subtarget->isThumb())
9880     return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
9881   if (Subtarget->isThumb2())
9882     return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
9883   // Thumb1 doesn't have cmn, and only 8-bit immediates.
9884   return Imm >= 0 && Imm <= 255;
9885 }
9886
9887 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
9888 /// *or sub* immediate, that is the target has add or sub instructions which can
9889 /// add a register with the immediate without having to materialize the
9890 /// immediate into a register.
9891 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
9892   // Same encoding for add/sub, just flip the sign.
9893   int64_t AbsImm = llvm::abs64(Imm);
9894   if (!Subtarget->isThumb())
9895     return ARM_AM::getSOImmVal(AbsImm) != -1;
9896   if (Subtarget->isThumb2())
9897     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
9898   // Thumb1 only has 8-bit unsigned immediate.
9899   return AbsImm >= 0 && AbsImm <= 255;
9900 }
9901
9902 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
9903                                       bool isSEXTLoad, SDValue &Base,
9904                                       SDValue &Offset, bool &isInc,
9905                                       SelectionDAG &DAG) {
9906   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9907     return false;
9908
9909   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
9910     // AddressingMode 3
9911     Base = Ptr->getOperand(0);
9912     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9913       int RHSC = (int)RHS->getZExtValue();
9914       if (RHSC < 0 && RHSC > -256) {
9915         assert(Ptr->getOpcode() == ISD::ADD);
9916         isInc = false;
9917         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9918         return true;
9919       }
9920     }
9921     isInc = (Ptr->getOpcode() == ISD::ADD);
9922     Offset = Ptr->getOperand(1);
9923     return true;
9924   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
9925     // AddressingMode 2
9926     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9927       int RHSC = (int)RHS->getZExtValue();
9928       if (RHSC < 0 && RHSC > -0x1000) {
9929         assert(Ptr->getOpcode() == ISD::ADD);
9930         isInc = false;
9931         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9932         Base = Ptr->getOperand(0);
9933         return true;
9934       }
9935     }
9936
9937     if (Ptr->getOpcode() == ISD::ADD) {
9938       isInc = true;
9939       ARM_AM::ShiftOpc ShOpcVal=
9940         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
9941       if (ShOpcVal != ARM_AM::no_shift) {
9942         Base = Ptr->getOperand(1);
9943         Offset = Ptr->getOperand(0);
9944       } else {
9945         Base = Ptr->getOperand(0);
9946         Offset = Ptr->getOperand(1);
9947       }
9948       return true;
9949     }
9950
9951     isInc = (Ptr->getOpcode() == ISD::ADD);
9952     Base = Ptr->getOperand(0);
9953     Offset = Ptr->getOperand(1);
9954     return true;
9955   }
9956
9957   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
9958   return false;
9959 }
9960
9961 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
9962                                      bool isSEXTLoad, SDValue &Base,
9963                                      SDValue &Offset, bool &isInc,
9964                                      SelectionDAG &DAG) {
9965   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9966     return false;
9967
9968   Base = Ptr->getOperand(0);
9969   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9970     int RHSC = (int)RHS->getZExtValue();
9971     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
9972       assert(Ptr->getOpcode() == ISD::ADD);
9973       isInc = false;
9974       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9975       return true;
9976     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
9977       isInc = Ptr->getOpcode() == ISD::ADD;
9978       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
9979       return true;
9980     }
9981   }
9982
9983   return false;
9984 }
9985
9986 /// getPreIndexedAddressParts - returns true by value, base pointer and
9987 /// offset pointer and addressing mode by reference if the node's address
9988 /// can be legally represented as pre-indexed load / store address.
9989 bool
9990 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
9991                                              SDValue &Offset,
9992                                              ISD::MemIndexedMode &AM,
9993                                              SelectionDAG &DAG) const {
9994   if (Subtarget->isThumb1Only())
9995     return false;
9996
9997   EVT VT;
9998   SDValue Ptr;
9999   bool isSEXTLoad = false;
10000   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10001     Ptr = LD->getBasePtr();
10002     VT  = LD->getMemoryVT();
10003     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10004   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10005     Ptr = ST->getBasePtr();
10006     VT  = ST->getMemoryVT();
10007   } else
10008     return false;
10009
10010   bool isInc;
10011   bool isLegal = false;
10012   if (Subtarget->isThumb2())
10013     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10014                                        Offset, isInc, DAG);
10015   else
10016     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10017                                         Offset, isInc, DAG);
10018   if (!isLegal)
10019     return false;
10020
10021   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10022   return true;
10023 }
10024
10025 /// getPostIndexedAddressParts - returns true by value, base pointer and
10026 /// offset pointer and addressing mode by reference if this node can be
10027 /// combined with a load / store to form a post-indexed load / store.
10028 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10029                                                    SDValue &Base,
10030                                                    SDValue &Offset,
10031                                                    ISD::MemIndexedMode &AM,
10032                                                    SelectionDAG &DAG) const {
10033   if (Subtarget->isThumb1Only())
10034     return false;
10035
10036   EVT VT;
10037   SDValue Ptr;
10038   bool isSEXTLoad = false;
10039   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10040     VT  = LD->getMemoryVT();
10041     Ptr = LD->getBasePtr();
10042     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10043   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10044     VT  = ST->getMemoryVT();
10045     Ptr = ST->getBasePtr();
10046   } else
10047     return false;
10048
10049   bool isInc;
10050   bool isLegal = false;
10051   if (Subtarget->isThumb2())
10052     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10053                                        isInc, DAG);
10054   else
10055     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10056                                         isInc, DAG);
10057   if (!isLegal)
10058     return false;
10059
10060   if (Ptr != Base) {
10061     // Swap base ptr and offset to catch more post-index load / store when
10062     // it's legal. In Thumb2 mode, offset must be an immediate.
10063     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10064         !Subtarget->isThumb2())
10065       std::swap(Base, Offset);
10066
10067     // Post-indexed load / store update the base pointer.
10068     if (Ptr != Base)
10069       return false;
10070   }
10071
10072   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10073   return true;
10074 }
10075
10076 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10077                                                       APInt &KnownZero,
10078                                                       APInt &KnownOne,
10079                                                       const SelectionDAG &DAG,
10080                                                       unsigned Depth) const {
10081   unsigned BitWidth = KnownOne.getBitWidth();
10082   KnownZero = KnownOne = APInt(BitWidth, 0);
10083   switch (Op.getOpcode()) {
10084   default: break;
10085   case ARMISD::ADDC:
10086   case ARMISD::ADDE:
10087   case ARMISD::SUBC:
10088   case ARMISD::SUBE:
10089     // These nodes' second result is a boolean
10090     if (Op.getResNo() == 0)
10091       break;
10092     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10093     break;
10094   case ARMISD::CMOV: {
10095     // Bits are known zero/one if known on the LHS and RHS.
10096     DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10097     if (KnownZero == 0 && KnownOne == 0) return;
10098
10099     APInt KnownZeroRHS, KnownOneRHS;
10100     DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10101     KnownZero &= KnownZeroRHS;
10102     KnownOne  &= KnownOneRHS;
10103     return;
10104   }
10105   case ISD::INTRINSIC_W_CHAIN: {
10106     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10107     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10108     switch (IntID) {
10109     default: return;
10110     case Intrinsic::arm_ldaex:
10111     case Intrinsic::arm_ldrex: {
10112       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10113       unsigned MemBits = VT.getScalarType().getSizeInBits();
10114       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10115       return;
10116     }
10117     }
10118   }
10119   }
10120 }
10121
10122 //===----------------------------------------------------------------------===//
10123 //                           ARM Inline Assembly Support
10124 //===----------------------------------------------------------------------===//
10125
10126 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10127   // Looking for "rev" which is V6+.
10128   if (!Subtarget->hasV6Ops())
10129     return false;
10130
10131   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10132   std::string AsmStr = IA->getAsmString();
10133   SmallVector<StringRef, 4> AsmPieces;
10134   SplitString(AsmStr, AsmPieces, ";\n");
10135
10136   switch (AsmPieces.size()) {
10137   default: return false;
10138   case 1:
10139     AsmStr = AsmPieces[0];
10140     AsmPieces.clear();
10141     SplitString(AsmStr, AsmPieces, " \t,");
10142
10143     // rev $0, $1
10144     if (AsmPieces.size() == 3 &&
10145         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10146         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10147       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10148       if (Ty && Ty->getBitWidth() == 32)
10149         return IntrinsicLowering::LowerToByteSwap(CI);
10150     }
10151     break;
10152   }
10153
10154   return false;
10155 }
10156
10157 /// getConstraintType - Given a constraint letter, return the type of
10158 /// constraint it is for this target.
10159 ARMTargetLowering::ConstraintType
10160 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10161   if (Constraint.size() == 1) {
10162     switch (Constraint[0]) {
10163     default:  break;
10164     case 'l': return C_RegisterClass;
10165     case 'w': return C_RegisterClass;
10166     case 'h': return C_RegisterClass;
10167     case 'x': return C_RegisterClass;
10168     case 't': return C_RegisterClass;
10169     case 'j': return C_Other; // Constant for movw.
10170       // An address with a single base register. Due to the way we
10171       // currently handle addresses it is the same as an 'r' memory constraint.
10172     case 'Q': return C_Memory;
10173     }
10174   } else if (Constraint.size() == 2) {
10175     switch (Constraint[0]) {
10176     default: break;
10177     // All 'U+' constraints are addresses.
10178     case 'U': return C_Memory;
10179     }
10180   }
10181   return TargetLowering::getConstraintType(Constraint);
10182 }
10183
10184 /// Examine constraint type and operand type and determine a weight value.
10185 /// This object must already have been set up with the operand type
10186 /// and the current alternative constraint selected.
10187 TargetLowering::ConstraintWeight
10188 ARMTargetLowering::getSingleConstraintMatchWeight(
10189     AsmOperandInfo &info, const char *constraint) const {
10190   ConstraintWeight weight = CW_Invalid;
10191   Value *CallOperandVal = info.CallOperandVal;
10192     // If we don't have a value, we can't do a match,
10193     // but allow it at the lowest weight.
10194   if (!CallOperandVal)
10195     return CW_Default;
10196   Type *type = CallOperandVal->getType();
10197   // Look at the constraint type.
10198   switch (*constraint) {
10199   default:
10200     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10201     break;
10202   case 'l':
10203     if (type->isIntegerTy()) {
10204       if (Subtarget->isThumb())
10205         weight = CW_SpecificReg;
10206       else
10207         weight = CW_Register;
10208     }
10209     break;
10210   case 'w':
10211     if (type->isFloatingPointTy())
10212       weight = CW_Register;
10213     break;
10214   }
10215   return weight;
10216 }
10217
10218 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10219 RCPair
10220 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10221                                                 MVT VT) const {
10222   if (Constraint.size() == 1) {
10223     // GCC ARM Constraint Letters
10224     switch (Constraint[0]) {
10225     case 'l': // Low regs or general regs.
10226       if (Subtarget->isThumb())
10227         return RCPair(0U, &ARM::tGPRRegClass);
10228       return RCPair(0U, &ARM::GPRRegClass);
10229     case 'h': // High regs or no regs.
10230       if (Subtarget->isThumb())
10231         return RCPair(0U, &ARM::hGPRRegClass);
10232       break;
10233     case 'r':
10234       return RCPair(0U, &ARM::GPRRegClass);
10235     case 'w':
10236       if (VT == MVT::Other)
10237         break;
10238       if (VT == MVT::f32)
10239         return RCPair(0U, &ARM::SPRRegClass);
10240       if (VT.getSizeInBits() == 64)
10241         return RCPair(0U, &ARM::DPRRegClass);
10242       if (VT.getSizeInBits() == 128)
10243         return RCPair(0U, &ARM::QPRRegClass);
10244       break;
10245     case 'x':
10246       if (VT == MVT::Other)
10247         break;
10248       if (VT == MVT::f32)
10249         return RCPair(0U, &ARM::SPR_8RegClass);
10250       if (VT.getSizeInBits() == 64)
10251         return RCPair(0U, &ARM::DPR_8RegClass);
10252       if (VT.getSizeInBits() == 128)
10253         return RCPair(0U, &ARM::QPR_8RegClass);
10254       break;
10255     case 't':
10256       if (VT == MVT::f32)
10257         return RCPair(0U, &ARM::SPRRegClass);
10258       break;
10259     }
10260   }
10261   if (StringRef("{cc}").equals_lower(Constraint))
10262     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10263
10264   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10265 }
10266
10267 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10268 /// vector.  If it is invalid, don't add anything to Ops.
10269 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10270                                                      std::string &Constraint,
10271                                                      std::vector<SDValue>&Ops,
10272                                                      SelectionDAG &DAG) const {
10273   SDValue Result;
10274
10275   // Currently only support length 1 constraints.
10276   if (Constraint.length() != 1) return;
10277
10278   char ConstraintLetter = Constraint[0];
10279   switch (ConstraintLetter) {
10280   default: break;
10281   case 'j':
10282   case 'I': case 'J': case 'K': case 'L':
10283   case 'M': case 'N': case 'O':
10284     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10285     if (!C)
10286       return;
10287
10288     int64_t CVal64 = C->getSExtValue();
10289     int CVal = (int) CVal64;
10290     // None of these constraints allow values larger than 32 bits.  Check
10291     // that the value fits in an int.
10292     if (CVal != CVal64)
10293       return;
10294
10295     switch (ConstraintLetter) {
10296       case 'j':
10297         // Constant suitable for movw, must be between 0 and
10298         // 65535.
10299         if (Subtarget->hasV6T2Ops())
10300           if (CVal >= 0 && CVal <= 65535)
10301             break;
10302         return;
10303       case 'I':
10304         if (Subtarget->isThumb1Only()) {
10305           // This must be a constant between 0 and 255, for ADD
10306           // immediates.
10307           if (CVal >= 0 && CVal <= 255)
10308             break;
10309         } else if (Subtarget->isThumb2()) {
10310           // A constant that can be used as an immediate value in a
10311           // data-processing instruction.
10312           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10313             break;
10314         } else {
10315           // A constant that can be used as an immediate value in a
10316           // data-processing instruction.
10317           if (ARM_AM::getSOImmVal(CVal) != -1)
10318             break;
10319         }
10320         return;
10321
10322       case 'J':
10323         if (Subtarget->isThumb()) {  // FIXME thumb2
10324           // This must be a constant between -255 and -1, for negated ADD
10325           // immediates. This can be used in GCC with an "n" modifier that
10326           // prints the negated value, for use with SUB instructions. It is
10327           // not useful otherwise but is implemented for compatibility.
10328           if (CVal >= -255 && CVal <= -1)
10329             break;
10330         } else {
10331           // This must be a constant between -4095 and 4095. It is not clear
10332           // what this constraint is intended for. Implemented for
10333           // compatibility with GCC.
10334           if (CVal >= -4095 && CVal <= 4095)
10335             break;
10336         }
10337         return;
10338
10339       case 'K':
10340         if (Subtarget->isThumb1Only()) {
10341           // A 32-bit value where only one byte has a nonzero value. Exclude
10342           // zero to match GCC. This constraint is used by GCC internally for
10343           // constants that can be loaded with a move/shift combination.
10344           // It is not useful otherwise but is implemented for compatibility.
10345           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10346             break;
10347         } else if (Subtarget->isThumb2()) {
10348           // A constant whose bitwise inverse can be used as an immediate
10349           // value in a data-processing instruction. This can be used in GCC
10350           // with a "B" modifier that prints the inverted value, for use with
10351           // BIC and MVN instructions. It is not useful otherwise but is
10352           // implemented for compatibility.
10353           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10354             break;
10355         } else {
10356           // A constant whose bitwise inverse can be used as an immediate
10357           // value in a data-processing instruction. This can be used in GCC
10358           // with a "B" modifier that prints the inverted value, for use with
10359           // BIC and MVN instructions. It is not useful otherwise but is
10360           // implemented for compatibility.
10361           if (ARM_AM::getSOImmVal(~CVal) != -1)
10362             break;
10363         }
10364         return;
10365
10366       case 'L':
10367         if (Subtarget->isThumb1Only()) {
10368           // This must be a constant between -7 and 7,
10369           // for 3-operand ADD/SUB immediate instructions.
10370           if (CVal >= -7 && CVal < 7)
10371             break;
10372         } else if (Subtarget->isThumb2()) {
10373           // A constant whose negation can be used as an immediate value in a
10374           // data-processing instruction. This can be used in GCC with an "n"
10375           // modifier that prints the negated value, for use with SUB
10376           // instructions. It is not useful otherwise but is implemented for
10377           // compatibility.
10378           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10379             break;
10380         } else {
10381           // A constant whose negation can be used as an immediate value in a
10382           // data-processing instruction. This can be used in GCC with an "n"
10383           // modifier that prints the negated value, for use with SUB
10384           // instructions. It is not useful otherwise but is implemented for
10385           // compatibility.
10386           if (ARM_AM::getSOImmVal(-CVal) != -1)
10387             break;
10388         }
10389         return;
10390
10391       case 'M':
10392         if (Subtarget->isThumb()) { // FIXME thumb2
10393           // This must be a multiple of 4 between 0 and 1020, for
10394           // ADD sp + immediate.
10395           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10396             break;
10397         } else {
10398           // A power of two or a constant between 0 and 32.  This is used in
10399           // GCC for the shift amount on shifted register operands, but it is
10400           // useful in general for any shift amounts.
10401           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10402             break;
10403         }
10404         return;
10405
10406       case 'N':
10407         if (Subtarget->isThumb()) {  // FIXME thumb2
10408           // This must be a constant between 0 and 31, for shift amounts.
10409           if (CVal >= 0 && CVal <= 31)
10410             break;
10411         }
10412         return;
10413
10414       case 'O':
10415         if (Subtarget->isThumb()) {  // FIXME thumb2
10416           // This must be a multiple of 4 between -508 and 508, for
10417           // ADD/SUB sp = sp + immediate.
10418           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10419             break;
10420         }
10421         return;
10422     }
10423     Result = DAG.getTargetConstant(CVal, Op.getValueType());
10424     break;
10425   }
10426
10427   if (Result.getNode()) {
10428     Ops.push_back(Result);
10429     return;
10430   }
10431   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10432 }
10433
10434 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10435   assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10436   unsigned Opcode = Op->getOpcode();
10437   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10438       "Invalid opcode for Div/Rem lowering");
10439   bool isSigned = (Opcode == ISD::SDIVREM);
10440   EVT VT = Op->getValueType(0);
10441   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10442
10443   RTLIB::Libcall LC;
10444   switch (VT.getSimpleVT().SimpleTy) {
10445   default: llvm_unreachable("Unexpected request for libcall!");
10446   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
10447   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10448   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10449   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10450   }
10451
10452   SDValue InChain = DAG.getEntryNode();
10453
10454   TargetLowering::ArgListTy Args;
10455   TargetLowering::ArgListEntry Entry;
10456   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
10457     EVT ArgVT = Op->getOperand(i).getValueType();
10458     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10459     Entry.Node = Op->getOperand(i);
10460     Entry.Ty = ArgTy;
10461     Entry.isSExt = isSigned;
10462     Entry.isZExt = !isSigned;
10463     Args.push_back(Entry);
10464   }
10465
10466   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
10467                                          getPointerTy());
10468
10469   Type *RetTy = (Type*)StructType::get(Ty, Ty, NULL);
10470
10471   SDLoc dl(Op);
10472   TargetLowering::CallLoweringInfo CLI(DAG);
10473   CLI.setDebugLoc(dl).setChain(InChain)
10474     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, &Args, 0)
10475     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
10476
10477   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
10478   return CallInfo.first;
10479 }
10480
10481 bool
10482 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10483   // The ARM target isn't yet aware of offsets.
10484   return false;
10485 }
10486
10487 bool ARM::isBitFieldInvertedMask(unsigned v) {
10488   if (v == 0xffffffff)
10489     return false;
10490
10491   // there can be 1's on either or both "outsides", all the "inside"
10492   // bits must be 0's
10493   unsigned TO = CountTrailingOnes_32(v);
10494   unsigned LO = CountLeadingOnes_32(v);
10495   v = (v >> TO) << TO;
10496   v = (v << LO) >> LO;
10497   return v == 0;
10498 }
10499
10500 /// isFPImmLegal - Returns true if the target can instruction select the
10501 /// specified FP immediate natively. If false, the legalizer will
10502 /// materialize the FP immediate as a load from a constant pool.
10503 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10504   if (!Subtarget->hasVFP3())
10505     return false;
10506   if (VT == MVT::f32)
10507     return ARM_AM::getFP32Imm(Imm) != -1;
10508   if (VT == MVT::f64)
10509     return ARM_AM::getFP64Imm(Imm) != -1;
10510   return false;
10511 }
10512
10513 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10514 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
10515 /// specified in the intrinsic calls.
10516 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10517                                            const CallInst &I,
10518                                            unsigned Intrinsic) const {
10519   switch (Intrinsic) {
10520   case Intrinsic::arm_neon_vld1:
10521   case Intrinsic::arm_neon_vld2:
10522   case Intrinsic::arm_neon_vld3:
10523   case Intrinsic::arm_neon_vld4:
10524   case Intrinsic::arm_neon_vld2lane:
10525   case Intrinsic::arm_neon_vld3lane:
10526   case Intrinsic::arm_neon_vld4lane: {
10527     Info.opc = ISD::INTRINSIC_W_CHAIN;
10528     // Conservatively set memVT to the entire set of vectors loaded.
10529     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10530     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10531     Info.ptrVal = I.getArgOperand(0);
10532     Info.offset = 0;
10533     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10534     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10535     Info.vol = false; // volatile loads with NEON intrinsics not supported
10536     Info.readMem = true;
10537     Info.writeMem = false;
10538     return true;
10539   }
10540   case Intrinsic::arm_neon_vst1:
10541   case Intrinsic::arm_neon_vst2:
10542   case Intrinsic::arm_neon_vst3:
10543   case Intrinsic::arm_neon_vst4:
10544   case Intrinsic::arm_neon_vst2lane:
10545   case Intrinsic::arm_neon_vst3lane:
10546   case Intrinsic::arm_neon_vst4lane: {
10547     Info.opc = ISD::INTRINSIC_VOID;
10548     // Conservatively set memVT to the entire set of vectors stored.
10549     unsigned NumElts = 0;
10550     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10551       Type *ArgTy = I.getArgOperand(ArgI)->getType();
10552       if (!ArgTy->isVectorTy())
10553         break;
10554       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10555     }
10556     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10557     Info.ptrVal = I.getArgOperand(0);
10558     Info.offset = 0;
10559     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10560     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10561     Info.vol = false; // volatile stores with NEON intrinsics not supported
10562     Info.readMem = false;
10563     Info.writeMem = true;
10564     return true;
10565   }
10566   case Intrinsic::arm_ldaex:
10567   case Intrinsic::arm_ldrex: {
10568     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
10569     Info.opc = ISD::INTRINSIC_W_CHAIN;
10570     Info.memVT = MVT::getVT(PtrTy->getElementType());
10571     Info.ptrVal = I.getArgOperand(0);
10572     Info.offset = 0;
10573     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10574     Info.vol = true;
10575     Info.readMem = true;
10576     Info.writeMem = false;
10577     return true;
10578   }
10579   case Intrinsic::arm_stlex:
10580   case Intrinsic::arm_strex: {
10581     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
10582     Info.opc = ISD::INTRINSIC_W_CHAIN;
10583     Info.memVT = MVT::getVT(PtrTy->getElementType());
10584     Info.ptrVal = I.getArgOperand(1);
10585     Info.offset = 0;
10586     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10587     Info.vol = true;
10588     Info.readMem = false;
10589     Info.writeMem = true;
10590     return true;
10591   }
10592   case Intrinsic::arm_stlexd:
10593   case Intrinsic::arm_strexd: {
10594     Info.opc = ISD::INTRINSIC_W_CHAIN;
10595     Info.memVT = MVT::i64;
10596     Info.ptrVal = I.getArgOperand(2);
10597     Info.offset = 0;
10598     Info.align = 8;
10599     Info.vol = true;
10600     Info.readMem = false;
10601     Info.writeMem = true;
10602     return true;
10603   }
10604   case Intrinsic::arm_ldaexd:
10605   case Intrinsic::arm_ldrexd: {
10606     Info.opc = ISD::INTRINSIC_W_CHAIN;
10607     Info.memVT = MVT::i64;
10608     Info.ptrVal = I.getArgOperand(0);
10609     Info.offset = 0;
10610     Info.align = 8;
10611     Info.vol = true;
10612     Info.readMem = true;
10613     Info.writeMem = false;
10614     return true;
10615   }
10616   default:
10617     break;
10618   }
10619
10620   return false;
10621 }
10622
10623 /// \brief Returns true if it is beneficial to convert a load of a constant
10624 /// to just the constant itself.
10625 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
10626                                                           Type *Ty) const {
10627   assert(Ty->isIntegerTy());
10628
10629   unsigned Bits = Ty->getPrimitiveSizeInBits();
10630   if (Bits == 0 || Bits > 32)
10631     return false;
10632   return true;
10633 }
10634
10635 bool ARMTargetLowering::shouldExpandAtomicInIR(Instruction *Inst) const {
10636   // Loads and stores less than 64-bits are already atomic; ones above that
10637   // are doomed anyway, so defer to the default libcall and blame the OS when
10638   // things go wrong:
10639   if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
10640     return SI->getValueOperand()->getType()->getPrimitiveSizeInBits() == 64;
10641   else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
10642     return LI->getType()->getPrimitiveSizeInBits() == 64;
10643
10644   // For the real atomic operations, we have ldrex/strex up to 64 bits.
10645   return Inst->getType()->getPrimitiveSizeInBits() <= 64;
10646 }
10647
10648 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
10649                                          AtomicOrdering Ord) const {
10650   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10651   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
10652   bool IsAcquire =
10653       Ord == Acquire || Ord == AcquireRelease || Ord == SequentiallyConsistent;
10654
10655   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
10656   // intrinsic must return {i32, i32} and we have to recombine them into a
10657   // single i64 here.
10658   if (ValTy->getPrimitiveSizeInBits() == 64) {
10659     Intrinsic::ID Int =
10660         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
10661     Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
10662
10663     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10664     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
10665
10666     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
10667     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
10668     if (!Subtarget->isLittle())
10669       std::swap (Lo, Hi);
10670     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
10671     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
10672     return Builder.CreateOr(
10673         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
10674   }
10675
10676   Type *Tys[] = { Addr->getType() };
10677   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
10678   Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
10679
10680   return Builder.CreateTruncOrBitCast(
10681       Builder.CreateCall(Ldrex, Addr),
10682       cast<PointerType>(Addr->getType())->getElementType());
10683 }
10684
10685 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
10686                                                Value *Addr,
10687                                                AtomicOrdering Ord) const {
10688   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10689   bool IsRelease =
10690       Ord == Release || Ord == AcquireRelease || Ord == SequentiallyConsistent;
10691
10692   // Since the intrinsics must have legal type, the i64 intrinsics take two
10693   // parameters: "i32, i32". We must marshal Val into the appropriate form
10694   // before the call.
10695   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
10696     Intrinsic::ID Int =
10697         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
10698     Function *Strex = Intrinsic::getDeclaration(M, Int);
10699     Type *Int32Ty = Type::getInt32Ty(M->getContext());
10700
10701     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
10702     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
10703     if (!Subtarget->isLittle())
10704       std::swap (Lo, Hi);
10705     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10706     return Builder.CreateCall3(Strex, Lo, Hi, Addr);
10707   }
10708
10709   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
10710   Type *Tys[] = { Addr->getType() };
10711   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
10712
10713   return Builder.CreateCall2(
10714       Strex, Builder.CreateZExtOrBitCast(
10715                  Val, Strex->getFunctionType()->getParamType(0)),
10716       Addr);
10717 }
10718
10719 enum HABaseType {
10720   HA_UNKNOWN = 0,
10721   HA_FLOAT,
10722   HA_DOUBLE,
10723   HA_VECT64,
10724   HA_VECT128
10725 };
10726
10727 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
10728                                    uint64_t &Members) {
10729   if (const StructType *ST = dyn_cast<StructType>(Ty)) {
10730     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
10731       uint64_t SubMembers = 0;
10732       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
10733         return false;
10734       Members += SubMembers;
10735     }
10736   } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
10737     uint64_t SubMembers = 0;
10738     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
10739       return false;
10740     Members += SubMembers * AT->getNumElements();
10741   } else if (Ty->isFloatTy()) {
10742     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
10743       return false;
10744     Members = 1;
10745     Base = HA_FLOAT;
10746   } else if (Ty->isDoubleTy()) {
10747     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
10748       return false;
10749     Members = 1;
10750     Base = HA_DOUBLE;
10751   } else if (const VectorType *VT = dyn_cast<VectorType>(Ty)) {
10752     Members = 1;
10753     switch (Base) {
10754     case HA_FLOAT:
10755     case HA_DOUBLE:
10756       return false;
10757     case HA_VECT64:
10758       return VT->getBitWidth() == 64;
10759     case HA_VECT128:
10760       return VT->getBitWidth() == 128;
10761     case HA_UNKNOWN:
10762       switch (VT->getBitWidth()) {
10763       case 64:
10764         Base = HA_VECT64;
10765         return true;
10766       case 128:
10767         Base = HA_VECT128;
10768         return true;
10769       default:
10770         return false;
10771       }
10772     }
10773   }
10774
10775   return (Members > 0 && Members <= 4);
10776 }
10777
10778 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate.
10779 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
10780     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
10781   if (getEffectiveCallingConv(CallConv, isVarArg) !=
10782       CallingConv::ARM_AAPCS_VFP)
10783     return false;
10784
10785   HABaseType Base = HA_UNKNOWN;
10786   uint64_t Members = 0;
10787   bool result = isHomogeneousAggregate(Ty, Base, Members);
10788   DEBUG(dbgs() << "isHA: " << result << " "; Ty->dump(); dbgs() << "\n");
10789   return result;
10790 }