ARM: support legalisation of "fptrunc ... to half" operations.
[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
401   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
402        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
403     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
404          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
405       setTruncStoreAction((MVT::SimpleValueType)VT,
406                           (MVT::SimpleValueType)InnerVT, Expand);
407     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
408     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
409     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
410
411     setOperationAction(ISD::MULHS, (MVT::SimpleValueType)VT, Expand);
412     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
413     setOperationAction(ISD::MULHU, (MVT::SimpleValueType)VT, Expand);
414     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
415
416     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
417   }
418
419   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
420   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
421
422   if (Subtarget->hasNEON()) {
423     addDRTypeForNEON(MVT::v2f32);
424     addDRTypeForNEON(MVT::v8i8);
425     addDRTypeForNEON(MVT::v4i16);
426     addDRTypeForNEON(MVT::v2i32);
427     addDRTypeForNEON(MVT::v1i64);
428
429     addQRTypeForNEON(MVT::v4f32);
430     addQRTypeForNEON(MVT::v2f64);
431     addQRTypeForNEON(MVT::v16i8);
432     addQRTypeForNEON(MVT::v8i16);
433     addQRTypeForNEON(MVT::v4i32);
434     addQRTypeForNEON(MVT::v2i64);
435
436     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
437     // neither Neon nor VFP support any arithmetic operations on it.
438     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
439     // supported for v4f32.
440     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
441     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
442     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
443     // FIXME: Code duplication: FDIV and FREM are expanded always, see
444     // ARMTargetLowering::addTypeForNEON method for details.
445     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
446     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
447     // FIXME: Create unittest.
448     // In another words, find a way when "copysign" appears in DAG with vector
449     // operands.
450     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
451     // FIXME: Code duplication: SETCC has custom operation action, see
452     // ARMTargetLowering::addTypeForNEON method for details.
453     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
454     // FIXME: Create unittest for FNEG and for FABS.
455     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
456     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
457     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
458     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
459     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
460     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
461     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
462     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
463     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
464     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
465     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
466     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
467     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
468     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
469     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
470     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
471     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
472     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
473     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
474
475     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
476     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
477     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
478     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
479     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
480     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
481     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
482     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
483     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
484     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
485     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
486     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
487     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
488     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
489     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
490
491     // Mark v2f32 intrinsics.
492     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
493     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
494     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
495     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
496     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
497     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
498     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
499     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
500     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
501     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
502     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
503     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
504     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
505     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
506     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
507
508     // Neon does not support some operations on v1i64 and v2i64 types.
509     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
510     // Custom handling for some quad-vector types to detect VMULL.
511     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
512     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
513     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
514     // Custom handling for some vector types to avoid expensive expansions
515     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
516     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
517     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
518     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
519     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
520     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
521     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
522     // a destination type that is wider than the source, and nor does
523     // it have a FP_TO_[SU]INT instruction with a narrower destination than
524     // source.
525     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
526     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
527     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
528     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
529
530     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
531     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
532
533     // NEON does not have single instruction CTPOP for vectors with element
534     // types wider than 8-bits.  However, custom lowering can leverage the
535     // v8i8/v16i8 vcnt instruction.
536     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
537     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
538     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
539     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
540
541     // NEON only has FMA instructions as of VFP4.
542     if (!Subtarget->hasVFP4()) {
543       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
544       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
545     }
546
547     setTargetDAGCombine(ISD::INTRINSIC_VOID);
548     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
549     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
550     setTargetDAGCombine(ISD::SHL);
551     setTargetDAGCombine(ISD::SRL);
552     setTargetDAGCombine(ISD::SRA);
553     setTargetDAGCombine(ISD::SIGN_EXTEND);
554     setTargetDAGCombine(ISD::ZERO_EXTEND);
555     setTargetDAGCombine(ISD::ANY_EXTEND);
556     setTargetDAGCombine(ISD::SELECT_CC);
557     setTargetDAGCombine(ISD::BUILD_VECTOR);
558     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
559     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
560     setTargetDAGCombine(ISD::STORE);
561     setTargetDAGCombine(ISD::FP_TO_SINT);
562     setTargetDAGCombine(ISD::FP_TO_UINT);
563     setTargetDAGCombine(ISD::FDIV);
564
565     // It is legal to extload from v4i8 to v4i16 or v4i32.
566     MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
567                   MVT::v4i16, MVT::v2i16,
568                   MVT::v2i32};
569     for (unsigned i = 0; i < 6; ++i) {
570       setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
571       setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
572       setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
573     }
574   }
575
576   // ARM and Thumb2 support UMLAL/SMLAL.
577   if (!Subtarget->isThumb1Only())
578     setTargetDAGCombine(ISD::ADDC);
579
580
581   computeRegisterProperties();
582
583   // ARM does not have floating-point extending loads.
584   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
585   setLoadExtAction(ISD::EXTLOAD, MVT::f16, Expand);
586
587   // ... or truncating stores
588   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
589   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
590   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
591
592   // ARM does not have i1 sign extending load.
593   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
594
595   // ARM supports all 4 flavors of integer indexed load / store.
596   if (!Subtarget->isThumb1Only()) {
597     for (unsigned im = (unsigned)ISD::PRE_INC;
598          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
599       setIndexedLoadAction(im,  MVT::i1,  Legal);
600       setIndexedLoadAction(im,  MVT::i8,  Legal);
601       setIndexedLoadAction(im,  MVT::i16, Legal);
602       setIndexedLoadAction(im,  MVT::i32, Legal);
603       setIndexedStoreAction(im, MVT::i1,  Legal);
604       setIndexedStoreAction(im, MVT::i8,  Legal);
605       setIndexedStoreAction(im, MVT::i16, Legal);
606       setIndexedStoreAction(im, MVT::i32, Legal);
607     }
608   }
609
610   setOperationAction(ISD::SADDO, MVT::i32, Custom);
611   setOperationAction(ISD::UADDO, MVT::i32, Custom);
612   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
613   setOperationAction(ISD::USUBO, MVT::i32, Custom);
614
615   // i64 operation support.
616   setOperationAction(ISD::MUL,     MVT::i64, Expand);
617   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
618   if (Subtarget->isThumb1Only()) {
619     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
620     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
621   }
622   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
623       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
624     setOperationAction(ISD::MULHS, MVT::i32, Expand);
625
626   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
627   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
628   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
629   setOperationAction(ISD::SRL,       MVT::i64, Custom);
630   setOperationAction(ISD::SRA,       MVT::i64, Custom);
631
632   if (!Subtarget->isThumb1Only()) {
633     // FIXME: We should do this for Thumb1 as well.
634     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
635     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
636     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
637     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
638   }
639
640   // ARM does not have ROTL.
641   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
642   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
643   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
644   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
645     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
646
647   // These just redirect to CTTZ and CTLZ on ARM.
648   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
649   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
650
651   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
652
653   // Only ARMv6 has BSWAP.
654   if (!Subtarget->hasV6Ops())
655     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
656
657   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
658       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
659     // These are expanded into libcalls if the cpu doesn't have HW divider.
660     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
661     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
662   }
663
664   // FIXME: Also set divmod for SREM on EABI
665   setOperationAction(ISD::SREM,  MVT::i32, Expand);
666   setOperationAction(ISD::UREM,  MVT::i32, Expand);
667   // Register based DivRem for AEABI (RTABI 4.2)
668   if (Subtarget->isTargetAEABI()) {
669     setLibcallName(RTLIB::SDIVREM_I8,  "__aeabi_idivmod");
670     setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
671     setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
672     setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
673     setLibcallName(RTLIB::UDIVREM_I8,  "__aeabi_uidivmod");
674     setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
675     setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
676     setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
677
678     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
679     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
680     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
681     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
682     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
683     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
684     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
685     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
686
687     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
688     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
689   } else {
690     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
691     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
692   }
693
694   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
695   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
696   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
697   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
698   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
699
700   setOperationAction(ISD::TRAP, MVT::Other, Legal);
701
702   // Use the default implementation.
703   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
704   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
705   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
706   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
707   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
708   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
709
710   if (!Subtarget->isTargetMachO()) {
711     // Non-MachO platforms may return values in these registers via the
712     // personality function.
713     setExceptionPointerRegister(ARM::R0);
714     setExceptionSelectorRegister(ARM::R1);
715   }
716
717   if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
718     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
719   else
720     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
721
722   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
723   // the default expansion.
724   if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
725     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
726     // to ldrex/strex loops already.
727     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
728
729     // On v8, we have particularly efficient implementations of atomic fences
730     // if they can be combined with nearby atomic loads and stores.
731     if (!Subtarget->hasV8Ops()) {
732       // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
733       setInsertFencesForAtomic(true);
734     }
735   } else {
736     // If there's anything we can use as a barrier, go through custom lowering
737     // for ATOMIC_FENCE.
738     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
739                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
740
741     // Set them all for expansion, which will force libcalls.
742     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
743     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
744     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
745     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
746     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
747     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
748     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
749     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
750     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
751     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
752     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
753     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
754     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
755     // Unordered/Monotonic case.
756     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
757     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
758   }
759
760   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
761
762   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
763   if (!Subtarget->hasV6Ops()) {
764     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
765     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
766   }
767   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
768
769   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
770       !Subtarget->isThumb1Only()) {
771     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
772     // iff target supports vfp2.
773     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
774     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
775   }
776
777   // We want to custom lower some of our intrinsics.
778   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
779   if (Subtarget->isTargetDarwin()) {
780     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
781     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
782     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
783   }
784
785   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
786   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
787   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
788   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
789   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
790   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
791   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
792   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
793   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
794
795   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
796   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
797   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
798   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
799   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
800
801   // We don't support sin/cos/fmod/copysign/pow
802   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
803   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
804   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
805   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
806   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
807   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
808   setOperationAction(ISD::FREM,      MVT::f64, Expand);
809   setOperationAction(ISD::FREM,      MVT::f32, Expand);
810   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
811       !Subtarget->isThumb1Only()) {
812     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
813     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
814   }
815   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
816   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
817
818   if (!Subtarget->hasVFP4()) {
819     setOperationAction(ISD::FMA, MVT::f64, Expand);
820     setOperationAction(ISD::FMA, MVT::f32, Expand);
821   }
822
823   // Various VFP goodness
824   if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
825     // int <-> fp are custom expanded into bit_convert + ARMISD ops.
826     if (Subtarget->hasVFP2()) {
827       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
828       setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
829       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
830       setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
831     }
832
833     // v8 adds f64 <-> f16 conversion. Before that it should be expanded.
834     if (!Subtarget->hasV8Ops()) {
835       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
836       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
837     }
838
839     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
840     if (!Subtarget->hasFP16()) {
841       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
842       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
843     }
844   }
845
846   // Combine sin / cos into one node or libcall if possible.
847   if (Subtarget->hasSinCos()) {
848     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
849     setLibcallName(RTLIB::SINCOS_F64, "sincos");
850     if (Subtarget->getTargetTriple().getOS() == Triple::IOS) {
851       // For iOS, we don't want to the normal expansion of a libcall to
852       // sincos. We want to issue a libcall to __sincos_stret.
853       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
854       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
855     }
856   }
857
858   // We have target-specific dag combine patterns for the following nodes:
859   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
860   setTargetDAGCombine(ISD::ADD);
861   setTargetDAGCombine(ISD::SUB);
862   setTargetDAGCombine(ISD::MUL);
863   setTargetDAGCombine(ISD::AND);
864   setTargetDAGCombine(ISD::OR);
865   setTargetDAGCombine(ISD::XOR);
866
867   if (Subtarget->hasV6Ops())
868     setTargetDAGCombine(ISD::SRL);
869
870   setStackPointerRegisterToSaveRestore(ARM::SP);
871
872   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
873       !Subtarget->hasVFP2())
874     setSchedulingPreference(Sched::RegPressure);
875   else
876     setSchedulingPreference(Sched::Hybrid);
877
878   //// temporary - rewrite interface to use type
879   MaxStoresPerMemset = 8;
880   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
881   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
882   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
883   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
884   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
885
886   // On ARM arguments smaller than 4 bytes are extended, so all arguments
887   // are at least 4 bytes aligned.
888   setMinStackArgumentAlignment(4);
889
890   // Prefer likely predicted branches to selects on out-of-order cores.
891   PredictableSelectIsExpensive = Subtarget->isLikeA9();
892
893   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
894 }
895
896 // FIXME: It might make sense to define the representative register class as the
897 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
898 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
899 // SPR's representative would be DPR_VFP2. This should work well if register
900 // pressure tracking were modified such that a register use would increment the
901 // pressure of the register class's representative and all of it's super
902 // classes' representatives transitively. We have not implemented this because
903 // of the difficulty prior to coalescing of modeling operand register classes
904 // due to the common occurrence of cross class copies and subregister insertions
905 // and extractions.
906 std::pair<const TargetRegisterClass*, uint8_t>
907 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
908   const TargetRegisterClass *RRC = nullptr;
909   uint8_t Cost = 1;
910   switch (VT.SimpleTy) {
911   default:
912     return TargetLowering::findRepresentativeClass(VT);
913   // Use DPR as representative register class for all floating point
914   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
915   // the cost is 1 for both f32 and f64.
916   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
917   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
918     RRC = &ARM::DPRRegClass;
919     // When NEON is used for SP, only half of the register file is available
920     // because operations that define both SP and DP results will be constrained
921     // to the VFP2 class (D0-D15). We currently model this constraint prior to
922     // coalescing by double-counting the SP regs. See the FIXME above.
923     if (Subtarget->useNEONForSinglePrecisionFP())
924       Cost = 2;
925     break;
926   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
927   case MVT::v4f32: case MVT::v2f64:
928     RRC = &ARM::DPRRegClass;
929     Cost = 2;
930     break;
931   case MVT::v4i64:
932     RRC = &ARM::DPRRegClass;
933     Cost = 4;
934     break;
935   case MVT::v8i64:
936     RRC = &ARM::DPRRegClass;
937     Cost = 8;
938     break;
939   }
940   return std::make_pair(RRC, Cost);
941 }
942
943 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
944   switch (Opcode) {
945   default: return nullptr;
946   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
947   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
948   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
949   case ARMISD::CALL:          return "ARMISD::CALL";
950   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
951   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
952   case ARMISD::tCALL:         return "ARMISD::tCALL";
953   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
954   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
955   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
956   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
957   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
958   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
959   case ARMISD::CMP:           return "ARMISD::CMP";
960   case ARMISD::CMN:           return "ARMISD::CMN";
961   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
962   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
963   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
964   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
965   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
966
967   case ARMISD::CMOV:          return "ARMISD::CMOV";
968
969   case ARMISD::RBIT:          return "ARMISD::RBIT";
970
971   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
972   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
973   case ARMISD::SITOF:         return "ARMISD::SITOF";
974   case ARMISD::UITOF:         return "ARMISD::UITOF";
975
976   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
977   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
978   case ARMISD::RRX:           return "ARMISD::RRX";
979
980   case ARMISD::ADDC:          return "ARMISD::ADDC";
981   case ARMISD::ADDE:          return "ARMISD::ADDE";
982   case ARMISD::SUBC:          return "ARMISD::SUBC";
983   case ARMISD::SUBE:          return "ARMISD::SUBE";
984
985   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
986   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
987
988   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
989   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
990
991   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
992
993   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
994
995   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
996
997   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
998
999   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1000
1001   case ARMISD::WIN__CHKSTK:   return "ARMISD:::WIN__CHKSTK";
1002
1003   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1004   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1005   case ARMISD::VCGE:          return "ARMISD::VCGE";
1006   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1007   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1008   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1009   case ARMISD::VCGT:          return "ARMISD::VCGT";
1010   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1011   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1012   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1013   case ARMISD::VTST:          return "ARMISD::VTST";
1014
1015   case ARMISD::VSHL:          return "ARMISD::VSHL";
1016   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1017   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1018   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1019   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1020   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1021   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1022   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1023   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1024   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1025   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1026   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1027   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1028   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1029   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1030   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1031   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1032   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1033   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1034   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1035   case ARMISD::VDUP:          return "ARMISD::VDUP";
1036   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1037   case ARMISD::VEXT:          return "ARMISD::VEXT";
1038   case ARMISD::VREV64:        return "ARMISD::VREV64";
1039   case ARMISD::VREV32:        return "ARMISD::VREV32";
1040   case ARMISD::VREV16:        return "ARMISD::VREV16";
1041   case ARMISD::VZIP:          return "ARMISD::VZIP";
1042   case ARMISD::VUZP:          return "ARMISD::VUZP";
1043   case ARMISD::VTRN:          return "ARMISD::VTRN";
1044   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1045   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1046   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1047   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1048   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1049   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1050   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1051   case ARMISD::FMAX:          return "ARMISD::FMAX";
1052   case ARMISD::FMIN:          return "ARMISD::FMIN";
1053   case ARMISD::VMAXNM:        return "ARMISD::VMAX";
1054   case ARMISD::VMINNM:        return "ARMISD::VMIN";
1055   case ARMISD::BFI:           return "ARMISD::BFI";
1056   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1057   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1058   case ARMISD::VBSL:          return "ARMISD::VBSL";
1059   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1060   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1061   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1062   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1063   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1064   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1065   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1066   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1067   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1068   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1069   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1070   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1071   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1072   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1073   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1074   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1075   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1076   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1077   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1078   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1079   }
1080 }
1081
1082 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1083   if (!VT.isVector()) return getPointerTy();
1084   return VT.changeVectorElementTypeToInteger();
1085 }
1086
1087 /// getRegClassFor - Return the register class that should be used for the
1088 /// specified value type.
1089 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1090   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1091   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1092   // load / store 4 to 8 consecutive D registers.
1093   if (Subtarget->hasNEON()) {
1094     if (VT == MVT::v4i64)
1095       return &ARM::QQPRRegClass;
1096     if (VT == MVT::v8i64)
1097       return &ARM::QQQQPRRegClass;
1098   }
1099   return TargetLowering::getRegClassFor(VT);
1100 }
1101
1102 // Create a fast isel object.
1103 FastISel *
1104 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1105                                   const TargetLibraryInfo *libInfo) const {
1106   return ARM::createFastISel(funcInfo, libInfo);
1107 }
1108
1109 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1110 /// be used for loads / stores from the global.
1111 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1112   return (Subtarget->isThumb1Only() ? 127 : 4095);
1113 }
1114
1115 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1116   unsigned NumVals = N->getNumValues();
1117   if (!NumVals)
1118     return Sched::RegPressure;
1119
1120   for (unsigned i = 0; i != NumVals; ++i) {
1121     EVT VT = N->getValueType(i);
1122     if (VT == MVT::Glue || VT == MVT::Other)
1123       continue;
1124     if (VT.isFloatingPoint() || VT.isVector())
1125       return Sched::ILP;
1126   }
1127
1128   if (!N->isMachineOpcode())
1129     return Sched::RegPressure;
1130
1131   // Load are scheduled for latency even if there instruction itinerary
1132   // is not available.
1133   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1134   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1135
1136   if (MCID.getNumDefs() == 0)
1137     return Sched::RegPressure;
1138   if (!Itins->isEmpty() &&
1139       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1140     return Sched::ILP;
1141
1142   return Sched::RegPressure;
1143 }
1144
1145 //===----------------------------------------------------------------------===//
1146 // Lowering Code
1147 //===----------------------------------------------------------------------===//
1148
1149 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1150 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1151   switch (CC) {
1152   default: llvm_unreachable("Unknown condition code!");
1153   case ISD::SETNE:  return ARMCC::NE;
1154   case ISD::SETEQ:  return ARMCC::EQ;
1155   case ISD::SETGT:  return ARMCC::GT;
1156   case ISD::SETGE:  return ARMCC::GE;
1157   case ISD::SETLT:  return ARMCC::LT;
1158   case ISD::SETLE:  return ARMCC::LE;
1159   case ISD::SETUGT: return ARMCC::HI;
1160   case ISD::SETUGE: return ARMCC::HS;
1161   case ISD::SETULT: return ARMCC::LO;
1162   case ISD::SETULE: return ARMCC::LS;
1163   }
1164 }
1165
1166 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1167 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1168                         ARMCC::CondCodes &CondCode2) {
1169   CondCode2 = ARMCC::AL;
1170   switch (CC) {
1171   default: llvm_unreachable("Unknown FP condition!");
1172   case ISD::SETEQ:
1173   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1174   case ISD::SETGT:
1175   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1176   case ISD::SETGE:
1177   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1178   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1179   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1180   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1181   case ISD::SETO:   CondCode = ARMCC::VC; break;
1182   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1183   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1184   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1185   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1186   case ISD::SETLT:
1187   case ISD::SETULT: CondCode = ARMCC::LT; break;
1188   case ISD::SETLE:
1189   case ISD::SETULE: CondCode = ARMCC::LE; break;
1190   case ISD::SETNE:
1191   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1192   }
1193 }
1194
1195 //===----------------------------------------------------------------------===//
1196 //                      Calling Convention Implementation
1197 //===----------------------------------------------------------------------===//
1198
1199 #include "ARMGenCallingConv.inc"
1200
1201 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1202 /// account presence of floating point hardware and calling convention
1203 /// limitations, such as support for variadic functions.
1204 CallingConv::ID
1205 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1206                                            bool isVarArg) const {
1207   switch (CC) {
1208   default:
1209     llvm_unreachable("Unsupported calling convention");
1210   case CallingConv::ARM_AAPCS:
1211   case CallingConv::ARM_APCS:
1212   case CallingConv::GHC:
1213     return CC;
1214   case CallingConv::ARM_AAPCS_VFP:
1215     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1216   case CallingConv::C:
1217     if (!Subtarget->isAAPCS_ABI())
1218       return CallingConv::ARM_APCS;
1219     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1220              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1221              !isVarArg)
1222       return CallingConv::ARM_AAPCS_VFP;
1223     else
1224       return CallingConv::ARM_AAPCS;
1225   case CallingConv::Fast:
1226     if (!Subtarget->isAAPCS_ABI()) {
1227       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1228         return CallingConv::Fast;
1229       return CallingConv::ARM_APCS;
1230     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1231       return CallingConv::ARM_AAPCS_VFP;
1232     else
1233       return CallingConv::ARM_AAPCS;
1234   }
1235 }
1236
1237 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1238 /// CallingConvention.
1239 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1240                                                  bool Return,
1241                                                  bool isVarArg) const {
1242   switch (getEffectiveCallingConv(CC, isVarArg)) {
1243   default:
1244     llvm_unreachable("Unsupported calling convention");
1245   case CallingConv::ARM_APCS:
1246     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1247   case CallingConv::ARM_AAPCS:
1248     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1249   case CallingConv::ARM_AAPCS_VFP:
1250     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1251   case CallingConv::Fast:
1252     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1253   case CallingConv::GHC:
1254     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1255   }
1256 }
1257
1258 /// LowerCallResult - Lower the result values of a call into the
1259 /// appropriate copies out of appropriate physical registers.
1260 SDValue
1261 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1262                                    CallingConv::ID CallConv, bool isVarArg,
1263                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1264                                    SDLoc dl, SelectionDAG &DAG,
1265                                    SmallVectorImpl<SDValue> &InVals,
1266                                    bool isThisReturn, SDValue ThisVal) const {
1267
1268   // Assign locations to each value returned by this call.
1269   SmallVector<CCValAssign, 16> RVLocs;
1270   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1271                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1272   CCInfo.AnalyzeCallResult(Ins,
1273                            CCAssignFnForNode(CallConv, /* Return*/ true,
1274                                              isVarArg));
1275
1276   // Copy all of the result registers out of their specified physreg.
1277   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1278     CCValAssign VA = RVLocs[i];
1279
1280     // Pass 'this' value directly from the argument to return value, to avoid
1281     // reg unit interference
1282     if (i == 0 && isThisReturn) {
1283       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1284              "unexpected return calling convention register assignment");
1285       InVals.push_back(ThisVal);
1286       continue;
1287     }
1288
1289     SDValue Val;
1290     if (VA.needsCustom()) {
1291       // Handle f64 or half of a v2f64.
1292       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1293                                       InFlag);
1294       Chain = Lo.getValue(1);
1295       InFlag = Lo.getValue(2);
1296       VA = RVLocs[++i]; // skip ahead to next loc
1297       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1298                                       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
1305       if (VA.getLocVT() == MVT::v2f64) {
1306         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1307         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1308                           DAG.getConstant(0, MVT::i32));
1309
1310         VA = RVLocs[++i]; // skip ahead to next loc
1311         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1312         Chain = Lo.getValue(1);
1313         InFlag = Lo.getValue(2);
1314         VA = RVLocs[++i]; // skip ahead to next loc
1315         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1316         Chain = Hi.getValue(1);
1317         InFlag = Hi.getValue(2);
1318         if (!Subtarget->isLittle())
1319           std::swap (Lo, Hi);
1320         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1321         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1322                           DAG.getConstant(1, MVT::i32));
1323       }
1324     } else {
1325       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1326                                InFlag);
1327       Chain = Val.getValue(1);
1328       InFlag = Val.getValue(2);
1329     }
1330
1331     switch (VA.getLocInfo()) {
1332     default: llvm_unreachable("Unknown loc info!");
1333     case CCValAssign::Full: break;
1334     case CCValAssign::BCvt:
1335       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1336       break;
1337     }
1338
1339     InVals.push_back(Val);
1340   }
1341
1342   return Chain;
1343 }
1344
1345 /// LowerMemOpCallTo - Store the argument to the stack.
1346 SDValue
1347 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1348                                     SDValue StackPtr, SDValue Arg,
1349                                     SDLoc dl, SelectionDAG &DAG,
1350                                     const CCValAssign &VA,
1351                                     ISD::ArgFlagsTy Flags) const {
1352   unsigned LocMemOffset = VA.getLocMemOffset();
1353   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1354   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1355   return DAG.getStore(Chain, dl, Arg, PtrOff,
1356                       MachinePointerInfo::getStack(LocMemOffset),
1357                       false, false, 0);
1358 }
1359
1360 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1361                                          SDValue Chain, SDValue &Arg,
1362                                          RegsToPassVector &RegsToPass,
1363                                          CCValAssign &VA, CCValAssign &NextVA,
1364                                          SDValue &StackPtr,
1365                                          SmallVectorImpl<SDValue> &MemOpChains,
1366                                          ISD::ArgFlagsTy Flags) const {
1367
1368   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1369                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1370   unsigned id = Subtarget->isLittle() ? 0 : 1;
1371   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1372
1373   if (NextVA.isRegLoc())
1374     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1375   else {
1376     assert(NextVA.isMemLoc());
1377     if (!StackPtr.getNode())
1378       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1379
1380     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1381                                            dl, DAG, NextVA,
1382                                            Flags));
1383   }
1384 }
1385
1386 /// LowerCall - Lowering a call into a callseq_start <-
1387 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1388 /// nodes.
1389 SDValue
1390 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1391                              SmallVectorImpl<SDValue> &InVals) const {
1392   SelectionDAG &DAG                     = CLI.DAG;
1393   SDLoc &dl                          = CLI.DL;
1394   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1395   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1396   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1397   SDValue Chain                         = CLI.Chain;
1398   SDValue Callee                        = CLI.Callee;
1399   bool &isTailCall                      = CLI.IsTailCall;
1400   CallingConv::ID CallConv              = CLI.CallConv;
1401   bool doesNotRet                       = CLI.DoesNotReturn;
1402   bool isVarArg                         = CLI.IsVarArg;
1403
1404   MachineFunction &MF = DAG.getMachineFunction();
1405   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1406   bool isThisReturn   = false;
1407   bool isSibCall      = false;
1408
1409   // Disable tail calls if they're not supported.
1410   if (!Subtarget->supportsTailCall() || MF.getTarget().Options.DisableTailCalls)
1411     isTailCall = false;
1412
1413   if (isTailCall) {
1414     // Check if it's really possible to do a tail call.
1415     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1416                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1417                                                    Outs, OutVals, Ins, DAG);
1418     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1419       report_fatal_error("failed to perform tail call elimination on a call "
1420                          "site marked musttail");
1421     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1422     // detected sibcalls.
1423     if (isTailCall) {
1424       ++NumTailCalls;
1425       isSibCall = true;
1426     }
1427   }
1428
1429   // Analyze operands of the call, assigning locations to each operand.
1430   SmallVector<CCValAssign, 16> ArgLocs;
1431   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1432                  getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1433   CCInfo.AnalyzeCallOperands(Outs,
1434                              CCAssignFnForNode(CallConv, /* Return*/ false,
1435                                                isVarArg));
1436
1437   // Get a count of how many bytes are to be pushed on the stack.
1438   unsigned NumBytes = CCInfo.getNextStackOffset();
1439
1440   // For tail calls, memory operands are available in our caller's stack.
1441   if (isSibCall)
1442     NumBytes = 0;
1443
1444   // Adjust the stack pointer for the new arguments...
1445   // These operations are automatically eliminated by the prolog/epilog pass
1446   if (!isSibCall)
1447     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1448                                  dl);
1449
1450   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1451
1452   RegsToPassVector RegsToPass;
1453   SmallVector<SDValue, 8> MemOpChains;
1454
1455   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1456   // of tail call optimization, arguments are handled later.
1457   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1458        i != e;
1459        ++i, ++realArgIdx) {
1460     CCValAssign &VA = ArgLocs[i];
1461     SDValue Arg = OutVals[realArgIdx];
1462     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1463     bool isByVal = Flags.isByVal();
1464
1465     // Promote the value if needed.
1466     switch (VA.getLocInfo()) {
1467     default: llvm_unreachable("Unknown loc info!");
1468     case CCValAssign::Full: break;
1469     case CCValAssign::SExt:
1470       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1471       break;
1472     case CCValAssign::ZExt:
1473       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1474       break;
1475     case CCValAssign::AExt:
1476       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1477       break;
1478     case CCValAssign::BCvt:
1479       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1480       break;
1481     }
1482
1483     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1484     if (VA.needsCustom()) {
1485       if (VA.getLocVT() == MVT::v2f64) {
1486         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1487                                   DAG.getConstant(0, MVT::i32));
1488         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1489                                   DAG.getConstant(1, MVT::i32));
1490
1491         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1492                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1493
1494         VA = ArgLocs[++i]; // skip ahead to next loc
1495         if (VA.isRegLoc()) {
1496           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1497                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1498         } else {
1499           assert(VA.isMemLoc());
1500
1501           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1502                                                  dl, DAG, VA, Flags));
1503         }
1504       } else {
1505         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1506                          StackPtr, MemOpChains, Flags);
1507       }
1508     } else if (VA.isRegLoc()) {
1509       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1510         assert(VA.getLocVT() == MVT::i32 &&
1511                "unexpected calling convention register assignment");
1512         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1513                "unexpected use of 'returned'");
1514         isThisReturn = true;
1515       }
1516       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1517     } else if (isByVal) {
1518       assert(VA.isMemLoc());
1519       unsigned offset = 0;
1520
1521       // True if this byval aggregate will be split between registers
1522       // and memory.
1523       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1524       unsigned CurByValIdx = CCInfo.getInRegsParamsProceed();
1525
1526       if (CurByValIdx < ByValArgsCount) {
1527
1528         unsigned RegBegin, RegEnd;
1529         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1530
1531         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1532         unsigned int i, j;
1533         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1534           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1535           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1536           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1537                                      MachinePointerInfo(),
1538                                      false, false, false,
1539                                      DAG.InferPtrAlignment(AddArg));
1540           MemOpChains.push_back(Load.getValue(1));
1541           RegsToPass.push_back(std::make_pair(j, Load));
1542         }
1543
1544         // If parameter size outsides register area, "offset" value
1545         // helps us to calculate stack slot for remained part properly.
1546         offset = RegEnd - RegBegin;
1547
1548         CCInfo.nextInRegsParam();
1549       }
1550
1551       if (Flags.getByValSize() > 4*offset) {
1552         unsigned LocMemOffset = VA.getLocMemOffset();
1553         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1554         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1555                                   StkPtrOff);
1556         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1557         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1558         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1559                                            MVT::i32);
1560         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1561
1562         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1563         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1564         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1565                                           Ops));
1566       }
1567     } else if (!isSibCall) {
1568       assert(VA.isMemLoc());
1569
1570       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1571                                              dl, DAG, VA, Flags));
1572     }
1573   }
1574
1575   if (!MemOpChains.empty())
1576     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1577
1578   // Build a sequence of copy-to-reg nodes chained together with token chain
1579   // and flag operands which copy the outgoing args into the appropriate regs.
1580   SDValue InFlag;
1581   // Tail call byval lowering might overwrite argument registers so in case of
1582   // tail call optimization the copies to registers are lowered later.
1583   if (!isTailCall)
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
1590   // For tail calls lower the arguments to the 'real' stack slot.
1591   if (isTailCall) {
1592     // Force all the incoming stack arguments to be loaded from the stack
1593     // before any new outgoing arguments are stored to the stack, because the
1594     // outgoing stack slots may alias the incoming argument stack slots, and
1595     // the alias isn't otherwise explicit. This is slightly more conservative
1596     // than necessary, because it means that each store effectively depends
1597     // on every argument instead of just those arguments it would clobber.
1598
1599     // Do not flag preceding copytoreg stuff together with the following stuff.
1600     InFlag = SDValue();
1601     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1602       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1603                                RegsToPass[i].second, InFlag);
1604       InFlag = Chain.getValue(1);
1605     }
1606     InFlag = SDValue();
1607   }
1608
1609   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1610   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1611   // node so that legalize doesn't hack it.
1612   bool isDirect = false;
1613   bool isARMFunc = false;
1614   bool isLocalARMFunc = false;
1615   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1616
1617   if (EnableARMLongCalls) {
1618     assert((Subtarget->isTargetWindows() ||
1619             getTargetMachine().getRelocationModel() == Reloc::Static) &&
1620            "long-calls with non-static relocation model!");
1621     // Handle a global address or an external symbol. If it's not one of
1622     // those, the target's already in a register, so we don't need to do
1623     // anything extra.
1624     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1625       const GlobalValue *GV = G->getGlobal();
1626       // Create a constant pool entry for the callee address
1627       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1628       ARMConstantPoolValue *CPV =
1629         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1630
1631       // Get the address of the callee into a register
1632       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1633       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1634       Callee = DAG.getLoad(getPointerTy(), dl,
1635                            DAG.getEntryNode(), CPAddr,
1636                            MachinePointerInfo::getConstantPool(),
1637                            false, false, false, 0);
1638     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1639       const char *Sym = S->getSymbol();
1640
1641       // Create a constant pool entry for the callee address
1642       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1643       ARMConstantPoolValue *CPV =
1644         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1645                                       ARMPCLabelIndex, 0);
1646       // Get the address of the callee into a register
1647       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1648       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1649       Callee = DAG.getLoad(getPointerTy(), dl,
1650                            DAG.getEntryNode(), CPAddr,
1651                            MachinePointerInfo::getConstantPool(),
1652                            false, false, false, 0);
1653     }
1654   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1655     const GlobalValue *GV = G->getGlobal();
1656     isDirect = true;
1657     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1658     bool isStub = (isExt && Subtarget->isTargetMachO()) &&
1659                    getTargetMachine().getRelocationModel() != Reloc::Static;
1660     isARMFunc = !Subtarget->isThumb() || isStub;
1661     // ARM call to a local ARM function is predicable.
1662     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1663     // tBX takes a register source operand.
1664     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1665       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1666       Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1667                            DAG.getTargetGlobalAddress(GV, dl, getPointerTy()));
1668     } else if (Subtarget->isTargetCOFF()) {
1669       assert(Subtarget->isTargetWindows() &&
1670              "Windows is the only supported COFF target");
1671       unsigned TargetFlags = GV->hasDLLImportStorageClass()
1672                                  ? ARMII::MO_DLLIMPORT
1673                                  : ARMII::MO_NO_FLAG;
1674       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), /*Offset=*/0,
1675                                           TargetFlags);
1676       if (GV->hasDLLImportStorageClass())
1677         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
1678                              DAG.getNode(ARMISD::Wrapper, dl, getPointerTy(),
1679                                          Callee), MachinePointerInfo::getGOT(),
1680                              false, false, false, 0);
1681     } else {
1682       // On ELF targets for PIC code, direct calls should go through the PLT
1683       unsigned OpFlags = 0;
1684       if (Subtarget->isTargetELF() &&
1685           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1686         OpFlags = ARMII::MO_PLT;
1687       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1688     }
1689   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1690     isDirect = true;
1691     bool isStub = Subtarget->isTargetMachO() &&
1692                   getTargetMachine().getRelocationModel() != Reloc::Static;
1693     isARMFunc = !Subtarget->isThumb() || isStub;
1694     // tBX takes a register source operand.
1695     const char *Sym = S->getSymbol();
1696     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1697       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1698       ARMConstantPoolValue *CPV =
1699         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1700                                       ARMPCLabelIndex, 4);
1701       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1702       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1703       Callee = DAG.getLoad(getPointerTy(), dl,
1704                            DAG.getEntryNode(), CPAddr,
1705                            MachinePointerInfo::getConstantPool(),
1706                            false, false, false, 0);
1707       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1708       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1709                            getPointerTy(), Callee, PICLabel);
1710     } else {
1711       unsigned OpFlags = 0;
1712       // On ELF targets for PIC code, direct calls should go through the PLT
1713       if (Subtarget->isTargetELF() &&
1714                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1715         OpFlags = ARMII::MO_PLT;
1716       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1717     }
1718   }
1719
1720   // FIXME: handle tail calls differently.
1721   unsigned CallOpc;
1722   bool HasMinSizeAttr = MF.getFunction()->getAttributes().hasAttribute(
1723       AttributeSet::FunctionIndex, Attribute::MinSize);
1724   if (Subtarget->isThumb()) {
1725     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1726       CallOpc = ARMISD::CALL_NOLINK;
1727     else
1728       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1729   } else {
1730     if (!isDirect && !Subtarget->hasV5TOps())
1731       CallOpc = ARMISD::CALL_NOLINK;
1732     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1733                // Emit regular call when code size is the priority
1734                !HasMinSizeAttr)
1735       // "mov lr, pc; b _foo" to avoid confusing the RSP
1736       CallOpc = ARMISD::CALL_NOLINK;
1737     else
1738       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1739   }
1740
1741   std::vector<SDValue> Ops;
1742   Ops.push_back(Chain);
1743   Ops.push_back(Callee);
1744
1745   // Add argument registers to the end of the list so that they are known live
1746   // into the call.
1747   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1748     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1749                                   RegsToPass[i].second.getValueType()));
1750
1751   // Add a register mask operand representing the call-preserved registers.
1752   if (!isTailCall) {
1753     const uint32_t *Mask;
1754     const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1755     const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1756     if (isThisReturn) {
1757       // For 'this' returns, use the R0-preserving mask if applicable
1758       Mask = ARI->getThisReturnPreservedMask(CallConv);
1759       if (!Mask) {
1760         // Set isThisReturn to false if the calling convention is not one that
1761         // allows 'returned' to be modeled in this way, so LowerCallResult does
1762         // not try to pass 'this' straight through
1763         isThisReturn = false;
1764         Mask = ARI->getCallPreservedMask(CallConv);
1765       }
1766     } else
1767       Mask = ARI->getCallPreservedMask(CallConv);
1768
1769     assert(Mask && "Missing call preserved mask for calling convention");
1770     Ops.push_back(DAG.getRegisterMask(Mask));
1771   }
1772
1773   if (InFlag.getNode())
1774     Ops.push_back(InFlag);
1775
1776   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1777   if (isTailCall)
1778     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1779
1780   // Returns a chain and a flag for retval copy to use.
1781   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1782   InFlag = Chain.getValue(1);
1783
1784   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1785                              DAG.getIntPtrConstant(0, true), InFlag, dl);
1786   if (!Ins.empty())
1787     InFlag = Chain.getValue(1);
1788
1789   // Handle result values, copying them out of physregs into vregs that we
1790   // return.
1791   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1792                          InVals, isThisReturn,
1793                          isThisReturn ? OutVals[0] : SDValue());
1794 }
1795
1796 /// HandleByVal - Every parameter *after* a byval parameter is passed
1797 /// on the stack.  Remember the next parameter register to allocate,
1798 /// and then confiscate the rest of the parameter registers to insure
1799 /// this.
1800 void
1801 ARMTargetLowering::HandleByVal(
1802     CCState *State, unsigned &size, unsigned Align) const {
1803   unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1804   assert((State->getCallOrPrologue() == Prologue ||
1805           State->getCallOrPrologue() == Call) &&
1806          "unhandled ParmContext");
1807
1808   if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1809     if (Subtarget->isAAPCS_ABI() && Align > 4) {
1810       unsigned AlignInRegs = Align / 4;
1811       unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1812       for (unsigned i = 0; i < Waste; ++i)
1813         reg = State->AllocateReg(GPRArgRegs, 4);
1814     }
1815     if (reg != 0) {
1816       unsigned excess = 4 * (ARM::R4 - reg);
1817
1818       // Special case when NSAA != SP and parameter size greater than size of
1819       // all remained GPR regs. In that case we can't split parameter, we must
1820       // send it to stack. We also must set NCRN to R4, so waste all
1821       // remained registers.
1822       const unsigned NSAAOffset = State->getNextStackOffset();
1823       if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1824         while (State->AllocateReg(GPRArgRegs, 4))
1825           ;
1826         return;
1827       }
1828
1829       // First register for byval parameter is the first register that wasn't
1830       // allocated before this method call, so it would be "reg".
1831       // If parameter is small enough to be saved in range [reg, r4), then
1832       // the end (first after last) register would be reg + param-size-in-regs,
1833       // else parameter would be splitted between registers and stack,
1834       // end register would be r4 in this case.
1835       unsigned ByValRegBegin = reg;
1836       unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1837       State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1838       // Note, first register is allocated in the beginning of function already,
1839       // allocate remained amount of registers we need.
1840       for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1841         State->AllocateReg(GPRArgRegs, 4);
1842       // A byval parameter that is split between registers and memory needs its
1843       // size truncated here.
1844       // In the case where the entire structure fits in registers, we set the
1845       // size in memory to zero.
1846       if (size < excess)
1847         size = 0;
1848       else
1849         size -= excess;
1850     }
1851   }
1852 }
1853
1854 /// MatchingStackOffset - Return true if the given stack call argument is
1855 /// already available in the same position (relatively) of the caller's
1856 /// incoming argument stack.
1857 static
1858 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1859                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1860                          const TargetInstrInfo *TII) {
1861   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1862   int FI = INT_MAX;
1863   if (Arg.getOpcode() == ISD::CopyFromReg) {
1864     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1865     if (!TargetRegisterInfo::isVirtualRegister(VR))
1866       return false;
1867     MachineInstr *Def = MRI->getVRegDef(VR);
1868     if (!Def)
1869       return false;
1870     if (!Flags.isByVal()) {
1871       if (!TII->isLoadFromStackSlot(Def, FI))
1872         return false;
1873     } else {
1874       return false;
1875     }
1876   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1877     if (Flags.isByVal())
1878       // ByVal argument is passed in as a pointer but it's now being
1879       // dereferenced. e.g.
1880       // define @foo(%struct.X* %A) {
1881       //   tail call @bar(%struct.X* byval %A)
1882       // }
1883       return false;
1884     SDValue Ptr = Ld->getBasePtr();
1885     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1886     if (!FINode)
1887       return false;
1888     FI = FINode->getIndex();
1889   } else
1890     return false;
1891
1892   assert(FI != INT_MAX);
1893   if (!MFI->isFixedObjectIndex(FI))
1894     return false;
1895   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1896 }
1897
1898 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1899 /// for tail call optimization. Targets which want to do tail call
1900 /// optimization should implement this function.
1901 bool
1902 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1903                                                      CallingConv::ID CalleeCC,
1904                                                      bool isVarArg,
1905                                                      bool isCalleeStructRet,
1906                                                      bool isCallerStructRet,
1907                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1908                                     const SmallVectorImpl<SDValue> &OutVals,
1909                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1910                                                      SelectionDAG& DAG) const {
1911   const Function *CallerF = DAG.getMachineFunction().getFunction();
1912   CallingConv::ID CallerCC = CallerF->getCallingConv();
1913   bool CCMatch = CallerCC == CalleeCC;
1914
1915   // Look for obvious safe cases to perform tail call optimization that do not
1916   // require ABI changes. This is what gcc calls sibcall.
1917
1918   // Do not sibcall optimize vararg calls unless the call site is not passing
1919   // any arguments.
1920   if (isVarArg && !Outs.empty())
1921     return false;
1922
1923   // Exception-handling functions need a special set of instructions to indicate
1924   // a return to the hardware. Tail-calling another function would probably
1925   // break this.
1926   if (CallerF->hasFnAttribute("interrupt"))
1927     return false;
1928
1929   // Also avoid sibcall optimization if either caller or callee uses struct
1930   // return semantics.
1931   if (isCalleeStructRet || isCallerStructRet)
1932     return false;
1933
1934   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1935   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1936   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1937   // support in the assembler and linker to be used. This would need to be
1938   // fixed to fully support tail calls in Thumb1.
1939   //
1940   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1941   // LR.  This means if we need to reload LR, it takes an extra instructions,
1942   // which outweighs the value of the tail call; but here we don't know yet
1943   // whether LR is going to be used.  Probably the right approach is to
1944   // generate the tail call here and turn it back into CALL/RET in
1945   // emitEpilogue if LR is used.
1946
1947   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1948   // but we need to make sure there are enough registers; the only valid
1949   // registers are the 4 used for parameters.  We don't currently do this
1950   // case.
1951   if (Subtarget->isThumb1Only())
1952     return false;
1953
1954   // If the calling conventions do not match, then we'd better make sure the
1955   // results are returned in the same way as what the caller expects.
1956   if (!CCMatch) {
1957     SmallVector<CCValAssign, 16> RVLocs1;
1958     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1959                        getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1960     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1961
1962     SmallVector<CCValAssign, 16> RVLocs2;
1963     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1964                        getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1965     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1966
1967     if (RVLocs1.size() != RVLocs2.size())
1968       return false;
1969     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1970       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1971         return false;
1972       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1973         return false;
1974       if (RVLocs1[i].isRegLoc()) {
1975         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1976           return false;
1977       } else {
1978         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1979           return false;
1980       }
1981     }
1982   }
1983
1984   // If Caller's vararg or byval argument has been split between registers and
1985   // stack, do not perform tail call, since part of the argument is in caller's
1986   // local frame.
1987   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
1988                                       getInfo<ARMFunctionInfo>();
1989   if (AFI_Caller->getArgRegsSaveSize())
1990     return false;
1991
1992   // If the callee takes no arguments then go on to check the results of the
1993   // call.
1994   if (!Outs.empty()) {
1995     // Check if stack adjustment is needed. For now, do not do this if any
1996     // argument is passed on the stack.
1997     SmallVector<CCValAssign, 16> ArgLocs;
1998     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
1999                       getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
2000     CCInfo.AnalyzeCallOperands(Outs,
2001                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2002     if (CCInfo.getNextStackOffset()) {
2003       MachineFunction &MF = DAG.getMachineFunction();
2004
2005       // Check if the arguments are already laid out in the right way as
2006       // the caller's fixed stack objects.
2007       MachineFrameInfo *MFI = MF.getFrameInfo();
2008       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2009       const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
2010       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2011            i != e;
2012            ++i, ++realArgIdx) {
2013         CCValAssign &VA = ArgLocs[i];
2014         EVT RegVT = VA.getLocVT();
2015         SDValue Arg = OutVals[realArgIdx];
2016         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2017         if (VA.getLocInfo() == CCValAssign::Indirect)
2018           return false;
2019         if (VA.needsCustom()) {
2020           // f64 and vector types are split into multiple registers or
2021           // register/stack-slot combinations.  The types will not match
2022           // the registers; give up on memory f64 refs until we figure
2023           // out what to do about this.
2024           if (!VA.isRegLoc())
2025             return false;
2026           if (!ArgLocs[++i].isRegLoc())
2027             return false;
2028           if (RegVT == MVT::v2f64) {
2029             if (!ArgLocs[++i].isRegLoc())
2030               return false;
2031             if (!ArgLocs[++i].isRegLoc())
2032               return false;
2033           }
2034         } else if (!VA.isRegLoc()) {
2035           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2036                                    MFI, MRI, TII))
2037             return false;
2038         }
2039       }
2040     }
2041   }
2042
2043   return true;
2044 }
2045
2046 bool
2047 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2048                                   MachineFunction &MF, bool isVarArg,
2049                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2050                                   LLVMContext &Context) const {
2051   SmallVector<CCValAssign, 16> RVLocs;
2052   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
2053   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2054                                                     isVarArg));
2055 }
2056
2057 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2058                                     SDLoc DL, SelectionDAG &DAG) {
2059   const MachineFunction &MF = DAG.getMachineFunction();
2060   const Function *F = MF.getFunction();
2061
2062   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2063
2064   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2065   // version of the "preferred return address". These offsets affect the return
2066   // instruction if this is a return from PL1 without hypervisor extensions.
2067   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2068   //    SWI:     0      "subs pc, lr, #0"
2069   //    ABORT:   +4     "subs pc, lr, #4"
2070   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2071   // UNDEF varies depending on where the exception came from ARM or Thumb
2072   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2073
2074   int64_t LROffset;
2075   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2076       IntKind == "ABORT")
2077     LROffset = 4;
2078   else if (IntKind == "SWI" || IntKind == "UNDEF")
2079     LROffset = 0;
2080   else
2081     report_fatal_error("Unsupported interrupt attribute. If present, value "
2082                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2083
2084   RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2085
2086   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2087 }
2088
2089 SDValue
2090 ARMTargetLowering::LowerReturn(SDValue Chain,
2091                                CallingConv::ID CallConv, bool isVarArg,
2092                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2093                                const SmallVectorImpl<SDValue> &OutVals,
2094                                SDLoc dl, SelectionDAG &DAG) const {
2095
2096   // CCValAssign - represent the assignment of the return value to a location.
2097   SmallVector<CCValAssign, 16> RVLocs;
2098
2099   // CCState - Info about the registers and stack slots.
2100   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2101                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
2102
2103   // Analyze outgoing return values.
2104   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2105                                                isVarArg));
2106
2107   SDValue Flag;
2108   SmallVector<SDValue, 4> RetOps;
2109   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2110   bool isLittleEndian = Subtarget->isLittle();
2111
2112   // Copy the result values into the output registers.
2113   for (unsigned i = 0, realRVLocIdx = 0;
2114        i != RVLocs.size();
2115        ++i, ++realRVLocIdx) {
2116     CCValAssign &VA = RVLocs[i];
2117     assert(VA.isRegLoc() && "Can only return in registers!");
2118
2119     SDValue Arg = OutVals[realRVLocIdx];
2120
2121     switch (VA.getLocInfo()) {
2122     default: llvm_unreachable("Unknown loc info!");
2123     case CCValAssign::Full: break;
2124     case CCValAssign::BCvt:
2125       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2126       break;
2127     }
2128
2129     if (VA.needsCustom()) {
2130       if (VA.getLocVT() == MVT::v2f64) {
2131         // Extract the first half and return it in two registers.
2132         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2133                                    DAG.getConstant(0, MVT::i32));
2134         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2135                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2136
2137         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2138                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2139                                  Flag);
2140         Flag = Chain.getValue(1);
2141         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2142         VA = RVLocs[++i]; // skip ahead to next loc
2143         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2144                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2145                                  Flag);
2146         Flag = Chain.getValue(1);
2147         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2148         VA = RVLocs[++i]; // skip ahead to next loc
2149
2150         // Extract the 2nd half and fall through to handle it as an f64 value.
2151         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2152                           DAG.getConstant(1, MVT::i32));
2153       }
2154       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2155       // available.
2156       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2157                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2158       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2159                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2160                                Flag);
2161       Flag = Chain.getValue(1);
2162       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2163       VA = RVLocs[++i]; // skip ahead to next loc
2164       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2165                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2166                                Flag);
2167     } else
2168       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2169
2170     // Guarantee that all emitted copies are
2171     // stuck together, avoiding something bad.
2172     Flag = Chain.getValue(1);
2173     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2174   }
2175
2176   // Update chain and glue.
2177   RetOps[0] = Chain;
2178   if (Flag.getNode())
2179     RetOps.push_back(Flag);
2180
2181   // CPUs which aren't M-class use a special sequence to return from
2182   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2183   // though we use "subs pc, lr, #N").
2184   //
2185   // M-class CPUs actually use a normal return sequence with a special
2186   // (hardware-provided) value in LR, so the normal code path works.
2187   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2188       !Subtarget->isMClass()) {
2189     if (Subtarget->isThumb1Only())
2190       report_fatal_error("interrupt attribute is not supported in Thumb1");
2191     return LowerInterruptReturn(RetOps, dl, DAG);
2192   }
2193
2194   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2195 }
2196
2197 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2198   if (N->getNumValues() != 1)
2199     return false;
2200   if (!N->hasNUsesOfValue(1, 0))
2201     return false;
2202
2203   SDValue TCChain = Chain;
2204   SDNode *Copy = *N->use_begin();
2205   if (Copy->getOpcode() == ISD::CopyToReg) {
2206     // If the copy has a glue operand, we conservatively assume it isn't safe to
2207     // perform a tail call.
2208     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2209       return false;
2210     TCChain = Copy->getOperand(0);
2211   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2212     SDNode *VMov = Copy;
2213     // f64 returned in a pair of GPRs.
2214     SmallPtrSet<SDNode*, 2> Copies;
2215     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2216          UI != UE; ++UI) {
2217       if (UI->getOpcode() != ISD::CopyToReg)
2218         return false;
2219       Copies.insert(*UI);
2220     }
2221     if (Copies.size() > 2)
2222       return false;
2223
2224     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2225          UI != UE; ++UI) {
2226       SDValue UseChain = UI->getOperand(0);
2227       if (Copies.count(UseChain.getNode()))
2228         // Second CopyToReg
2229         Copy = *UI;
2230       else
2231         // First CopyToReg
2232         TCChain = UseChain;
2233     }
2234   } else if (Copy->getOpcode() == ISD::BITCAST) {
2235     // f32 returned in a single GPR.
2236     if (!Copy->hasOneUse())
2237       return false;
2238     Copy = *Copy->use_begin();
2239     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2240       return false;
2241     TCChain = Copy->getOperand(0);
2242   } else {
2243     return false;
2244   }
2245
2246   bool HasRet = false;
2247   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2248        UI != UE; ++UI) {
2249     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2250         UI->getOpcode() != ARMISD::INTRET_FLAG)
2251       return false;
2252     HasRet = true;
2253   }
2254
2255   if (!HasRet)
2256     return false;
2257
2258   Chain = TCChain;
2259   return true;
2260 }
2261
2262 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2263   if (!Subtarget->supportsTailCall())
2264     return false;
2265
2266   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2267     return false;
2268
2269   return !Subtarget->isThumb1Only();
2270 }
2271
2272 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2273 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2274 // one of the above mentioned nodes. It has to be wrapped because otherwise
2275 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2276 // be used to form addressing mode. These wrapped nodes will be selected
2277 // into MOVi.
2278 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2279   EVT PtrVT = Op.getValueType();
2280   // FIXME there is no actual debug info here
2281   SDLoc dl(Op);
2282   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2283   SDValue Res;
2284   if (CP->isMachineConstantPoolEntry())
2285     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2286                                     CP->getAlignment());
2287   else
2288     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2289                                     CP->getAlignment());
2290   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2291 }
2292
2293 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2294   return MachineJumpTableInfo::EK_Inline;
2295 }
2296
2297 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2298                                              SelectionDAG &DAG) const {
2299   MachineFunction &MF = DAG.getMachineFunction();
2300   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2301   unsigned ARMPCLabelIndex = 0;
2302   SDLoc DL(Op);
2303   EVT PtrVT = getPointerTy();
2304   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2305   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2306   SDValue CPAddr;
2307   if (RelocM == Reloc::Static) {
2308     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2309   } else {
2310     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2311     ARMPCLabelIndex = AFI->createPICLabelUId();
2312     ARMConstantPoolValue *CPV =
2313       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2314                                       ARMCP::CPBlockAddress, PCAdj);
2315     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2316   }
2317   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2318   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2319                                MachinePointerInfo::getConstantPool(),
2320                                false, false, false, 0);
2321   if (RelocM == Reloc::Static)
2322     return Result;
2323   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2324   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2325 }
2326
2327 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2328 SDValue
2329 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2330                                                  SelectionDAG &DAG) const {
2331   SDLoc dl(GA);
2332   EVT PtrVT = getPointerTy();
2333   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2334   MachineFunction &MF = DAG.getMachineFunction();
2335   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2336   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2337   ARMConstantPoolValue *CPV =
2338     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2339                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2340   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2341   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2342   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2343                          MachinePointerInfo::getConstantPool(),
2344                          false, false, false, 0);
2345   SDValue Chain = Argument.getValue(1);
2346
2347   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2348   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2349
2350   // call __tls_get_addr.
2351   ArgListTy Args;
2352   ArgListEntry Entry;
2353   Entry.Node = Argument;
2354   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2355   Args.push_back(Entry);
2356
2357   // FIXME: is there useful debug info available here?
2358   TargetLowering::CallLoweringInfo CLI(DAG);
2359   CLI.setDebugLoc(dl).setChain(Chain)
2360     .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2361                DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2362                0);
2363
2364   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2365   return CallResult.first;
2366 }
2367
2368 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2369 // "local exec" model.
2370 SDValue
2371 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2372                                         SelectionDAG &DAG,
2373                                         TLSModel::Model model) const {
2374   const GlobalValue *GV = GA->getGlobal();
2375   SDLoc dl(GA);
2376   SDValue Offset;
2377   SDValue Chain = DAG.getEntryNode();
2378   EVT PtrVT = getPointerTy();
2379   // Get the Thread Pointer
2380   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2381
2382   if (model == TLSModel::InitialExec) {
2383     MachineFunction &MF = DAG.getMachineFunction();
2384     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2385     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2386     // Initial exec model.
2387     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2388     ARMConstantPoolValue *CPV =
2389       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2390                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2391                                       true);
2392     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2393     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2394     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2395                          MachinePointerInfo::getConstantPool(),
2396                          false, false, false, 0);
2397     Chain = Offset.getValue(1);
2398
2399     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2400     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2401
2402     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2403                          MachinePointerInfo::getConstantPool(),
2404                          false, false, false, 0);
2405   } else {
2406     // local exec model
2407     assert(model == TLSModel::LocalExec);
2408     ARMConstantPoolValue *CPV =
2409       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2410     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2411     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2412     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2413                          MachinePointerInfo::getConstantPool(),
2414                          false, false, false, 0);
2415   }
2416
2417   // The address of the thread local variable is the add of the thread
2418   // pointer with the offset of the variable.
2419   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2420 }
2421
2422 SDValue
2423 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2424   // TODO: implement the "local dynamic" model
2425   assert(Subtarget->isTargetELF() &&
2426          "TLS not implemented for non-ELF targets");
2427   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2428
2429   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2430
2431   switch (model) {
2432     case TLSModel::GeneralDynamic:
2433     case TLSModel::LocalDynamic:
2434       return LowerToTLSGeneralDynamicModel(GA, DAG);
2435     case TLSModel::InitialExec:
2436     case TLSModel::LocalExec:
2437       return LowerToTLSExecModels(GA, DAG, model);
2438   }
2439   llvm_unreachable("bogus TLS model");
2440 }
2441
2442 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2443                                                  SelectionDAG &DAG) const {
2444   EVT PtrVT = getPointerTy();
2445   SDLoc dl(Op);
2446   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2447   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2448     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2449     ARMConstantPoolValue *CPV =
2450       ARMConstantPoolConstant::Create(GV,
2451                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2452     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2453     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2454     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2455                                  CPAddr,
2456                                  MachinePointerInfo::getConstantPool(),
2457                                  false, false, false, 0);
2458     SDValue Chain = Result.getValue(1);
2459     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2460     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2461     if (!UseGOTOFF)
2462       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2463                            MachinePointerInfo::getGOT(),
2464                            false, false, false, 0);
2465     return Result;
2466   }
2467
2468   // If we have T2 ops, we can materialize the address directly via movt/movw
2469   // pair. This is always cheaper.
2470   if (Subtarget->useMovt(DAG.getMachineFunction())) {
2471     ++NumMovwMovt;
2472     // FIXME: Once remat is capable of dealing with instructions with register
2473     // operands, expand this into two nodes.
2474     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2475                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2476   } else {
2477     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2478     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2479     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2480                        MachinePointerInfo::getConstantPool(),
2481                        false, false, false, 0);
2482   }
2483 }
2484
2485 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2486                                                     SelectionDAG &DAG) const {
2487   EVT PtrVT = getPointerTy();
2488   SDLoc dl(Op);
2489   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2490   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2491
2492   if (Subtarget->useMovt(DAG.getMachineFunction()))
2493     ++NumMovwMovt;
2494
2495   // FIXME: Once remat is capable of dealing with instructions with register
2496   // operands, expand this into multiple nodes
2497   unsigned Wrapper =
2498       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2499
2500   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2501   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2502
2503   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2504     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2505                          MachinePointerInfo::getGOT(), false, false, false, 0);
2506   return Result;
2507 }
2508
2509 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2510                                                      SelectionDAG &DAG) const {
2511   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2512   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2513          "Windows on ARM expects to use movw/movt");
2514
2515   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2516   const ARMII::TOF TargetFlags =
2517     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2518   EVT PtrVT = getPointerTy();
2519   SDValue Result;
2520   SDLoc DL(Op);
2521
2522   ++NumMovwMovt;
2523
2524   // FIXME: Once remat is capable of dealing with instructions with register
2525   // operands, expand this into two nodes.
2526   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2527                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2528                                                   TargetFlags));
2529   if (GV->hasDLLImportStorageClass())
2530     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2531                          MachinePointerInfo::getGOT(), false, false, false, 0);
2532   return Result;
2533 }
2534
2535 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2536                                                     SelectionDAG &DAG) const {
2537   assert(Subtarget->isTargetELF() &&
2538          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2539   MachineFunction &MF = DAG.getMachineFunction();
2540   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2541   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2542   EVT PtrVT = getPointerTy();
2543   SDLoc dl(Op);
2544   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2545   ARMConstantPoolValue *CPV =
2546     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2547                                   ARMPCLabelIndex, PCAdj);
2548   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2549   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2550   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2551                                MachinePointerInfo::getConstantPool(),
2552                                false, false, false, 0);
2553   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2554   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2555 }
2556
2557 SDValue
2558 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2559   SDLoc dl(Op);
2560   SDValue Val = DAG.getConstant(0, MVT::i32);
2561   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2562                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2563                      Op.getOperand(1), Val);
2564 }
2565
2566 SDValue
2567 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2568   SDLoc dl(Op);
2569   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2570                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2571 }
2572
2573 SDValue
2574 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2575                                           const ARMSubtarget *Subtarget) const {
2576   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2577   SDLoc dl(Op);
2578   switch (IntNo) {
2579   default: return SDValue();    // Don't custom lower most intrinsics.
2580   case Intrinsic::arm_rbit: {
2581     assert(Op.getOperand(0).getValueType() == MVT::i32 &&
2582            "RBIT intrinsic must have i32 type!");
2583     return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(0));
2584   }
2585   case Intrinsic::arm_thread_pointer: {
2586     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2587     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2588   }
2589   case Intrinsic::eh_sjlj_lsda: {
2590     MachineFunction &MF = DAG.getMachineFunction();
2591     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2592     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2593     EVT PtrVT = getPointerTy();
2594     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2595     SDValue CPAddr;
2596     unsigned PCAdj = (RelocM != Reloc::PIC_)
2597       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2598     ARMConstantPoolValue *CPV =
2599       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2600                                       ARMCP::CPLSDA, PCAdj);
2601     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2602     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2603     SDValue Result =
2604       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2605                   MachinePointerInfo::getConstantPool(),
2606                   false, false, false, 0);
2607
2608     if (RelocM == Reloc::PIC_) {
2609       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2610       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2611     }
2612     return Result;
2613   }
2614   case Intrinsic::arm_neon_vmulls:
2615   case Intrinsic::arm_neon_vmullu: {
2616     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2617       ? ARMISD::VMULLs : ARMISD::VMULLu;
2618     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2619                        Op.getOperand(1), Op.getOperand(2));
2620   }
2621   }
2622 }
2623
2624 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2625                                  const ARMSubtarget *Subtarget) {
2626   // FIXME: handle "fence singlethread" more efficiently.
2627   SDLoc dl(Op);
2628   if (!Subtarget->hasDataBarrier()) {
2629     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2630     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2631     // here.
2632     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2633            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2634     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2635                        DAG.getConstant(0, MVT::i32));
2636   }
2637
2638   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2639   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2640   unsigned Domain = ARM_MB::ISH;
2641   if (Subtarget->isMClass()) {
2642     // Only a full system barrier exists in the M-class architectures.
2643     Domain = ARM_MB::SY;
2644   } else if (Subtarget->isSwift() && Ord == Release) {
2645     // Swift happens to implement ISHST barriers in a way that's compatible with
2646     // Release semantics but weaker than ISH so we'd be fools not to use
2647     // it. Beware: other processors probably don't!
2648     Domain = ARM_MB::ISHST;
2649   }
2650
2651   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2652                      DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2653                      DAG.getConstant(Domain, MVT::i32));
2654 }
2655
2656 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2657                              const ARMSubtarget *Subtarget) {
2658   // ARM pre v5TE and Thumb1 does not have preload instructions.
2659   if (!(Subtarget->isThumb2() ||
2660         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2661     // Just preserve the chain.
2662     return Op.getOperand(0);
2663
2664   SDLoc dl(Op);
2665   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2666   if (!isRead &&
2667       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2668     // ARMv7 with MP extension has PLDW.
2669     return Op.getOperand(0);
2670
2671   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2672   if (Subtarget->isThumb()) {
2673     // Invert the bits.
2674     isRead = ~isRead & 1;
2675     isData = ~isData & 1;
2676   }
2677
2678   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2679                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2680                      DAG.getConstant(isData, MVT::i32));
2681 }
2682
2683 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2684   MachineFunction &MF = DAG.getMachineFunction();
2685   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2686
2687   // vastart just stores the address of the VarArgsFrameIndex slot into the
2688   // memory location argument.
2689   SDLoc dl(Op);
2690   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2691   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2692   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2693   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2694                       MachinePointerInfo(SV), false, false, 0);
2695 }
2696
2697 SDValue
2698 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2699                                         SDValue &Root, SelectionDAG &DAG,
2700                                         SDLoc dl) const {
2701   MachineFunction &MF = DAG.getMachineFunction();
2702   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2703
2704   const TargetRegisterClass *RC;
2705   if (AFI->isThumb1OnlyFunction())
2706     RC = &ARM::tGPRRegClass;
2707   else
2708     RC = &ARM::GPRRegClass;
2709
2710   // Transform the arguments stored in physical registers into virtual ones.
2711   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2712   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2713
2714   SDValue ArgValue2;
2715   if (NextVA.isMemLoc()) {
2716     MachineFrameInfo *MFI = MF.getFrameInfo();
2717     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2718
2719     // Create load node to retrieve arguments from the stack.
2720     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2721     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2722                             MachinePointerInfo::getFixedStack(FI),
2723                             false, false, false, 0);
2724   } else {
2725     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2726     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2727   }
2728   if (!Subtarget->isLittle())
2729     std::swap (ArgValue, ArgValue2);
2730   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2731 }
2732
2733 void
2734 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2735                                   unsigned InRegsParamRecordIdx,
2736                                   unsigned ArgSize,
2737                                   unsigned &ArgRegsSize,
2738                                   unsigned &ArgRegsSaveSize)
2739   const {
2740   unsigned NumGPRs;
2741   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2742     unsigned RBegin, REnd;
2743     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2744     NumGPRs = REnd - RBegin;
2745   } else {
2746     unsigned int firstUnalloced;
2747     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2748                                                 sizeof(GPRArgRegs) /
2749                                                 sizeof(GPRArgRegs[0]));
2750     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2751   }
2752
2753   unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2754   ArgRegsSize = NumGPRs * 4;
2755
2756   // If parameter is split between stack and GPRs...
2757   if (NumGPRs && Align > 4 &&
2758       (ArgRegsSize < ArgSize ||
2759         InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2760     // Add padding for part of param recovered from GPRs.  For example,
2761     // if Align == 8, its last byte must be at address K*8 - 1.
2762     // We need to do it, since remained (stack) part of parameter has
2763     // stack alignment, and we need to "attach" "GPRs head" without gaps
2764     // to it:
2765     // Stack:
2766     // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2767     // [ [padding] [GPRs head] ] [        Tail passed via stack       ....
2768     //
2769     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2770     unsigned Padding =
2771         OffsetToAlignment(ArgRegsSize + AFI->getArgRegsSaveSize(), Align);
2772     ArgRegsSaveSize = ArgRegsSize + Padding;
2773   } else
2774     // We don't need to extend regs save size for byval parameters if they
2775     // are passed via GPRs only.
2776     ArgRegsSaveSize = ArgRegsSize;
2777 }
2778
2779 // The remaining GPRs hold either the beginning of variable-argument
2780 // data, or the beginning of an aggregate passed by value (usually
2781 // byval).  Either way, we allocate stack slots adjacent to the data
2782 // provided by our caller, and store the unallocated registers there.
2783 // If this is a variadic function, the va_list pointer will begin with
2784 // these values; otherwise, this reassembles a (byval) structure that
2785 // was split between registers and memory.
2786 // Return: The frame index registers were stored into.
2787 int
2788 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2789                                   SDLoc dl, SDValue &Chain,
2790                                   const Value *OrigArg,
2791                                   unsigned InRegsParamRecordIdx,
2792                                   unsigned OffsetFromOrigArg,
2793                                   unsigned ArgOffset,
2794                                   unsigned ArgSize,
2795                                   bool ForceMutable,
2796                                   unsigned ByValStoreOffset,
2797                                   unsigned TotalArgRegsSaveSize) const {
2798
2799   // Currently, two use-cases possible:
2800   // Case #1. Non-var-args function, and we meet first byval parameter.
2801   //          Setup first unallocated register as first byval register;
2802   //          eat all remained registers
2803   //          (these two actions are performed by HandleByVal method).
2804   //          Then, here, we initialize stack frame with
2805   //          "store-reg" instructions.
2806   // Case #2. Var-args function, that doesn't contain byval parameters.
2807   //          The same: eat all remained unallocated registers,
2808   //          initialize stack frame.
2809
2810   MachineFunction &MF = DAG.getMachineFunction();
2811   MachineFrameInfo *MFI = MF.getFrameInfo();
2812   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2813   unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2814   unsigned RBegin, REnd;
2815   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2816     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2817     firstRegToSaveIndex = RBegin - ARM::R0;
2818     lastRegToSaveIndex = REnd - ARM::R0;
2819   } else {
2820     firstRegToSaveIndex = CCInfo.getFirstUnallocated
2821       (GPRArgRegs, array_lengthof(GPRArgRegs));
2822     lastRegToSaveIndex = 4;
2823   }
2824
2825   unsigned ArgRegsSize, ArgRegsSaveSize;
2826   computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2827                  ArgRegsSize, ArgRegsSaveSize);
2828
2829   // Store any by-val regs to their spots on the stack so that they may be
2830   // loaded by deferencing the result of formal parameter pointer or va_next.
2831   // Note: once stack area for byval/varargs registers
2832   // was initialized, it can't be initialized again.
2833   if (ArgRegsSaveSize) {
2834     unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2835
2836     if (Padding) {
2837       assert(AFI->getStoredByValParamsPadding() == 0 &&
2838              "The only parameter may be padded.");
2839       AFI->setStoredByValParamsPadding(Padding);
2840     }
2841
2842     int FrameIndex = MFI->CreateFixedObject(ArgRegsSaveSize,
2843                                             Padding +
2844                                               ByValStoreOffset -
2845                                               (int64_t)TotalArgRegsSaveSize,
2846                                             false);
2847     SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2848     if (Padding) {
2849        MFI->CreateFixedObject(Padding,
2850                               ArgOffset + ByValStoreOffset -
2851                                 (int64_t)ArgRegsSaveSize,
2852                               false);
2853     }
2854
2855     SmallVector<SDValue, 4> MemOps;
2856     for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2857          ++firstRegToSaveIndex, ++i) {
2858       const TargetRegisterClass *RC;
2859       if (AFI->isThumb1OnlyFunction())
2860         RC = &ARM::tGPRRegClass;
2861       else
2862         RC = &ARM::GPRRegClass;
2863
2864       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2865       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2866       SDValue Store =
2867         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2868                      MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2869                      false, false, 0);
2870       MemOps.push_back(Store);
2871       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2872                         DAG.getConstant(4, getPointerTy()));
2873     }
2874
2875     AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2876
2877     if (!MemOps.empty())
2878       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2879     return FrameIndex;
2880   } else {
2881     if (ArgSize == 0) {
2882       // We cannot allocate a zero-byte object for the first variadic argument,
2883       // so just make up a size.
2884       ArgSize = 4;
2885     }
2886     // This will point to the next argument passed via stack.
2887     return MFI->CreateFixedObject(
2888       ArgSize, ArgOffset, !ForceMutable);
2889   }
2890 }
2891
2892 // Setup stack frame, the va_list pointer will start from.
2893 void
2894 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2895                                         SDLoc dl, SDValue &Chain,
2896                                         unsigned ArgOffset,
2897                                         unsigned TotalArgRegsSaveSize,
2898                                         bool ForceMutable) const {
2899   MachineFunction &MF = DAG.getMachineFunction();
2900   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2901
2902   // Try to store any remaining integer argument regs
2903   // to their spots on the stack so that they may be loaded by deferencing
2904   // the result of va_next.
2905   // If there is no regs to be stored, just point address after last
2906   // argument passed via stack.
2907   int FrameIndex =
2908     StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
2909                    CCInfo.getInRegsParamsCount(), 0, ArgOffset, 0, ForceMutable,
2910                    0, TotalArgRegsSaveSize);
2911
2912   AFI->setVarArgsFrameIndex(FrameIndex);
2913 }
2914
2915 SDValue
2916 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2917                                         CallingConv::ID CallConv, bool isVarArg,
2918                                         const SmallVectorImpl<ISD::InputArg>
2919                                           &Ins,
2920                                         SDLoc dl, SelectionDAG &DAG,
2921                                         SmallVectorImpl<SDValue> &InVals)
2922                                           const {
2923   MachineFunction &MF = DAG.getMachineFunction();
2924   MachineFrameInfo *MFI = MF.getFrameInfo();
2925
2926   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2927
2928   // Assign locations to all of the incoming arguments.
2929   SmallVector<CCValAssign, 16> ArgLocs;
2930   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2931                     getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2932   CCInfo.AnalyzeFormalArguments(Ins,
2933                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2934                                                   isVarArg));
2935
2936   SmallVector<SDValue, 16> ArgValues;
2937   int lastInsIndex = -1;
2938   SDValue ArgValue;
2939   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2940   unsigned CurArgIdx = 0;
2941
2942   // Initially ArgRegsSaveSize is zero.
2943   // Then we increase this value each time we meet byval parameter.
2944   // We also increase this value in case of varargs function.
2945   AFI->setArgRegsSaveSize(0);
2946
2947   unsigned ByValStoreOffset = 0;
2948   unsigned TotalArgRegsSaveSize = 0;
2949   unsigned ArgRegsSaveSizeMaxAlign = 4;
2950
2951   // Calculate the amount of stack space that we need to allocate to store
2952   // byval and variadic arguments that are passed in registers.
2953   // We need to know this before we allocate the first byval or variadic
2954   // argument, as they will be allocated a stack slot below the CFA (Canonical
2955   // Frame Address, the stack pointer at entry to the function).
2956   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2957     CCValAssign &VA = ArgLocs[i];
2958     if (VA.isMemLoc()) {
2959       int index = VA.getValNo();
2960       if (index != lastInsIndex) {
2961         ISD::ArgFlagsTy Flags = Ins[index].Flags;
2962         if (Flags.isByVal()) {
2963           unsigned ExtraArgRegsSize;
2964           unsigned ExtraArgRegsSaveSize;
2965           computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsProceed(),
2966                          Flags.getByValSize(),
2967                          ExtraArgRegsSize, ExtraArgRegsSaveSize);
2968
2969           TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
2970           if (Flags.getByValAlign() > ArgRegsSaveSizeMaxAlign)
2971               ArgRegsSaveSizeMaxAlign = Flags.getByValAlign();
2972           CCInfo.nextInRegsParam();
2973         }
2974         lastInsIndex = index;
2975       }
2976     }
2977   }
2978   CCInfo.rewindByValRegsInfo();
2979   lastInsIndex = -1;
2980   if (isVarArg) {
2981     unsigned ExtraArgRegsSize;
2982     unsigned ExtraArgRegsSaveSize;
2983     computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsCount(), 0,
2984                    ExtraArgRegsSize, ExtraArgRegsSaveSize);
2985     TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
2986   }
2987   // If the arg regs save area contains N-byte aligned values, the
2988   // bottom of it must be at least N-byte aligned.
2989   TotalArgRegsSaveSize = RoundUpToAlignment(TotalArgRegsSaveSize, ArgRegsSaveSizeMaxAlign);
2990   TotalArgRegsSaveSize = std::min(TotalArgRegsSaveSize, 16U);
2991
2992   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2993     CCValAssign &VA = ArgLocs[i];
2994     std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
2995     CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
2996     // Arguments stored in registers.
2997     if (VA.isRegLoc()) {
2998       EVT RegVT = VA.getLocVT();
2999
3000       if (VA.needsCustom()) {
3001         // f64 and vector types are split up into multiple registers or
3002         // combinations of registers and stack slots.
3003         if (VA.getLocVT() == MVT::v2f64) {
3004           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3005                                                    Chain, DAG, dl);
3006           VA = ArgLocs[++i]; // skip ahead to next loc
3007           SDValue ArgValue2;
3008           if (VA.isMemLoc()) {
3009             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3010             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3011             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3012                                     MachinePointerInfo::getFixedStack(FI),
3013                                     false, false, false, 0);
3014           } else {
3015             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3016                                              Chain, DAG, dl);
3017           }
3018           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3019           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3020                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
3021           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3022                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
3023         } else
3024           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3025
3026       } else {
3027         const TargetRegisterClass *RC;
3028
3029         if (RegVT == MVT::f32)
3030           RC = &ARM::SPRRegClass;
3031         else if (RegVT == MVT::f64)
3032           RC = &ARM::DPRRegClass;
3033         else if (RegVT == MVT::v2f64)
3034           RC = &ARM::QPRRegClass;
3035         else if (RegVT == MVT::i32)
3036           RC = AFI->isThumb1OnlyFunction() ?
3037             (const TargetRegisterClass*)&ARM::tGPRRegClass :
3038             (const TargetRegisterClass*)&ARM::GPRRegClass;
3039         else
3040           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3041
3042         // Transform the arguments in physical registers into virtual ones.
3043         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3044         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3045       }
3046
3047       // If this is an 8 or 16-bit value, it is really passed promoted
3048       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3049       // truncate to the right size.
3050       switch (VA.getLocInfo()) {
3051       default: llvm_unreachable("Unknown loc info!");
3052       case CCValAssign::Full: break;
3053       case CCValAssign::BCvt:
3054         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3055         break;
3056       case CCValAssign::SExt:
3057         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3058                                DAG.getValueType(VA.getValVT()));
3059         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3060         break;
3061       case CCValAssign::ZExt:
3062         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3063                                DAG.getValueType(VA.getValVT()));
3064         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3065         break;
3066       }
3067
3068       InVals.push_back(ArgValue);
3069
3070     } else { // VA.isRegLoc()
3071
3072       // sanity check
3073       assert(VA.isMemLoc());
3074       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3075
3076       int index = ArgLocs[i].getValNo();
3077
3078       // Some Ins[] entries become multiple ArgLoc[] entries.
3079       // Process them only once.
3080       if (index != lastInsIndex)
3081         {
3082           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3083           // FIXME: For now, all byval parameter objects are marked mutable.
3084           // This can be changed with more analysis.
3085           // In case of tail call optimization mark all arguments mutable.
3086           // Since they could be overwritten by lowering of arguments in case of
3087           // a tail call.
3088           if (Flags.isByVal()) {
3089             unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
3090
3091             ByValStoreOffset = RoundUpToAlignment(ByValStoreOffset, Flags.getByValAlign());
3092             int FrameIndex = StoreByValRegs(
3093                 CCInfo, DAG, dl, Chain, CurOrigArg,
3094                 CurByValIndex,
3095                 Ins[VA.getValNo()].PartOffset,
3096                 VA.getLocMemOffset(),
3097                 Flags.getByValSize(),
3098                 true /*force mutable frames*/,
3099                 ByValStoreOffset,
3100                 TotalArgRegsSaveSize);
3101             ByValStoreOffset += Flags.getByValSize();
3102             ByValStoreOffset = std::min(ByValStoreOffset, 16U);
3103             InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3104             CCInfo.nextInRegsParam();
3105           } else {
3106             unsigned FIOffset = VA.getLocMemOffset();
3107             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3108                                             FIOffset, true);
3109
3110             // Create load nodes to retrieve arguments from the stack.
3111             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3112             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3113                                          MachinePointerInfo::getFixedStack(FI),
3114                                          false, false, false, 0));
3115           }
3116           lastInsIndex = index;
3117         }
3118     }
3119   }
3120
3121   // varargs
3122   if (isVarArg)
3123     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3124                          CCInfo.getNextStackOffset(),
3125                          TotalArgRegsSaveSize);
3126
3127   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3128
3129   return Chain;
3130 }
3131
3132 /// isFloatingPointZero - Return true if this is +0.0.
3133 static bool isFloatingPointZero(SDValue Op) {
3134   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3135     return CFP->getValueAPF().isPosZero();
3136   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3137     // Maybe this has already been legalized into the constant pool?
3138     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3139       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3140       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3141         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3142           return CFP->getValueAPF().isPosZero();
3143     }
3144   }
3145   return false;
3146 }
3147
3148 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3149 /// the given operands.
3150 SDValue
3151 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3152                              SDValue &ARMcc, SelectionDAG &DAG,
3153                              SDLoc dl) const {
3154   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3155     unsigned C = RHSC->getZExtValue();
3156     if (!isLegalICmpImmediate(C)) {
3157       // Constant does not fit, try adjusting it by one?
3158       switch (CC) {
3159       default: break;
3160       case ISD::SETLT:
3161       case ISD::SETGE:
3162         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3163           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3164           RHS = DAG.getConstant(C-1, MVT::i32);
3165         }
3166         break;
3167       case ISD::SETULT:
3168       case ISD::SETUGE:
3169         if (C != 0 && isLegalICmpImmediate(C-1)) {
3170           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3171           RHS = DAG.getConstant(C-1, MVT::i32);
3172         }
3173         break;
3174       case ISD::SETLE:
3175       case ISD::SETGT:
3176         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3177           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3178           RHS = DAG.getConstant(C+1, MVT::i32);
3179         }
3180         break;
3181       case ISD::SETULE:
3182       case ISD::SETUGT:
3183         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3184           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3185           RHS = DAG.getConstant(C+1, MVT::i32);
3186         }
3187         break;
3188       }
3189     }
3190   }
3191
3192   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3193   ARMISD::NodeType CompareType;
3194   switch (CondCode) {
3195   default:
3196     CompareType = ARMISD::CMP;
3197     break;
3198   case ARMCC::EQ:
3199   case ARMCC::NE:
3200     // Uses only Z Flag
3201     CompareType = ARMISD::CMPZ;
3202     break;
3203   }
3204   ARMcc = DAG.getConstant(CondCode, MVT::i32);
3205   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3206 }
3207
3208 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3209 SDValue
3210 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3211                              SDLoc dl) const {
3212   SDValue Cmp;
3213   if (!isFloatingPointZero(RHS))
3214     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3215   else
3216     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3217   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3218 }
3219
3220 /// duplicateCmp - Glue values can have only one use, so this function
3221 /// duplicates a comparison node.
3222 SDValue
3223 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3224   unsigned Opc = Cmp.getOpcode();
3225   SDLoc DL(Cmp);
3226   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3227     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3228
3229   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3230   Cmp = Cmp.getOperand(0);
3231   Opc = Cmp.getOpcode();
3232   if (Opc == ARMISD::CMPFP)
3233     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3234   else {
3235     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3236     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3237   }
3238   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3239 }
3240
3241 std::pair<SDValue, SDValue>
3242 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3243                                  SDValue &ARMcc) const {
3244   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3245
3246   SDValue Value, OverflowCmp;
3247   SDValue LHS = Op.getOperand(0);
3248   SDValue RHS = Op.getOperand(1);
3249
3250
3251   // FIXME: We are currently always generating CMPs because we don't support
3252   // generating CMN through the backend. This is not as good as the natural
3253   // CMP case because it causes a register dependency and cannot be folded
3254   // later.
3255
3256   switch (Op.getOpcode()) {
3257   default:
3258     llvm_unreachable("Unknown overflow instruction!");
3259   case ISD::SADDO:
3260     ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3261     Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3262     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3263     break;
3264   case ISD::UADDO:
3265     ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3266     Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3267     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3268     break;
3269   case ISD::SSUBO:
3270     ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3271     Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3272     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3273     break;
3274   case ISD::USUBO:
3275     ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3276     Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3277     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3278     break;
3279   } // switch (...)
3280
3281   return std::make_pair(Value, OverflowCmp);
3282 }
3283
3284
3285 SDValue
3286 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3287   // Let legalize expand this if it isn't a legal type yet.
3288   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3289     return SDValue();
3290
3291   SDValue Value, OverflowCmp;
3292   SDValue ARMcc;
3293   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3294   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3295   // We use 0 and 1 as false and true values.
3296   SDValue TVal = DAG.getConstant(1, MVT::i32);
3297   SDValue FVal = DAG.getConstant(0, MVT::i32);
3298   EVT VT = Op.getValueType();
3299
3300   SDValue Overflow = DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, TVal, FVal,
3301                                  ARMcc, CCR, OverflowCmp);
3302
3303   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3304   return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), VTs, Value, Overflow);
3305 }
3306
3307
3308 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3309   SDValue Cond = Op.getOperand(0);
3310   SDValue SelectTrue = Op.getOperand(1);
3311   SDValue SelectFalse = Op.getOperand(2);
3312   SDLoc dl(Op);
3313   unsigned Opc = Cond.getOpcode();
3314
3315   if (Cond.getResNo() == 1 &&
3316       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3317        Opc == ISD::USUBO)) {
3318     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3319       return SDValue();
3320
3321     SDValue Value, OverflowCmp;
3322     SDValue ARMcc;
3323     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3324     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3325     EVT VT = Op.getValueType();
3326
3327     return DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, SelectTrue, SelectFalse,
3328                        ARMcc, CCR, OverflowCmp);
3329
3330   }
3331
3332   // Convert:
3333   //
3334   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3335   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3336   //
3337   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3338     const ConstantSDNode *CMOVTrue =
3339       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3340     const ConstantSDNode *CMOVFalse =
3341       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3342
3343     if (CMOVTrue && CMOVFalse) {
3344       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3345       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3346
3347       SDValue True;
3348       SDValue False;
3349       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3350         True = SelectTrue;
3351         False = SelectFalse;
3352       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3353         True = SelectFalse;
3354         False = SelectTrue;
3355       }
3356
3357       if (True.getNode() && False.getNode()) {
3358         EVT VT = Op.getValueType();
3359         SDValue ARMcc = Cond.getOperand(2);
3360         SDValue CCR = Cond.getOperand(3);
3361         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3362         assert(True.getValueType() == VT);
3363         return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
3364       }
3365     }
3366   }
3367
3368   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3369   // undefined bits before doing a full-word comparison with zero.
3370   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3371                      DAG.getConstant(1, Cond.getValueType()));
3372
3373   return DAG.getSelectCC(dl, Cond,
3374                          DAG.getConstant(0, Cond.getValueType()),
3375                          SelectTrue, SelectFalse, ISD::SETNE);
3376 }
3377
3378 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3379   if (CC == ISD::SETNE)
3380     return ISD::SETEQ;
3381   return ISD::getSetCCInverse(CC, true);
3382 }
3383
3384 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3385                                  bool &swpCmpOps, bool &swpVselOps) {
3386   // Start by selecting the GE condition code for opcodes that return true for
3387   // 'equality'
3388   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3389       CC == ISD::SETULE)
3390     CondCode = ARMCC::GE;
3391
3392   // and GT for opcodes that return false for 'equality'.
3393   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3394            CC == ISD::SETULT)
3395     CondCode = ARMCC::GT;
3396
3397   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3398   // to swap the compare operands.
3399   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3400       CC == ISD::SETULT)
3401     swpCmpOps = true;
3402
3403   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3404   // If we have an unordered opcode, we need to swap the operands to the VSEL
3405   // instruction (effectively negating the condition).
3406   //
3407   // This also has the effect of swapping which one of 'less' or 'greater'
3408   // returns true, so we also swap the compare operands. It also switches
3409   // whether we return true for 'equality', so we compensate by picking the
3410   // opposite condition code to our original choice.
3411   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3412       CC == ISD::SETUGT) {
3413     swpCmpOps = !swpCmpOps;
3414     swpVselOps = !swpVselOps;
3415     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3416   }
3417
3418   // 'ordered' is 'anything but unordered', so use the VS condition code and
3419   // swap the VSEL operands.
3420   if (CC == ISD::SETO) {
3421     CondCode = ARMCC::VS;
3422     swpVselOps = true;
3423   }
3424
3425   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3426   // code and swap the VSEL operands.
3427   if (CC == ISD::SETUNE) {
3428     CondCode = ARMCC::EQ;
3429     swpVselOps = true;
3430   }
3431 }
3432
3433 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3434   EVT VT = Op.getValueType();
3435   SDValue LHS = Op.getOperand(0);
3436   SDValue RHS = Op.getOperand(1);
3437   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3438   SDValue TrueVal = Op.getOperand(2);
3439   SDValue FalseVal = Op.getOperand(3);
3440   SDLoc dl(Op);
3441
3442   if (LHS.getValueType() == MVT::i32) {
3443     // Try to generate VSEL on ARMv8.
3444     // The VSEL instruction can't use all the usual ARM condition
3445     // codes: it only has two bits to select the condition code, so it's
3446     // constrained to use only GE, GT, VS and EQ.
3447     //
3448     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3449     // swap the operands of the previous compare instruction (effectively
3450     // inverting the compare condition, swapping 'less' and 'greater') and
3451     // sometimes need to swap the operands to the VSEL (which inverts the
3452     // condition in the sense of firing whenever the previous condition didn't)
3453     if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3454                                       TrueVal.getValueType() == MVT::f64)) {
3455       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3456       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3457           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3458         CC = getInverseCCForVSEL(CC);
3459         std::swap(TrueVal, FalseVal);
3460       }
3461     }
3462
3463     SDValue ARMcc;
3464     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3465     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3466     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3467                        Cmp);
3468   }
3469
3470   ARMCC::CondCodes CondCode, CondCode2;
3471   FPCCToARMCC(CC, CondCode, CondCode2);
3472
3473   // Try to generate VSEL on ARMv8.
3474   if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3475                                     TrueVal.getValueType() == MVT::f64)) {
3476     // We can select VMAXNM/VMINNM from a compare followed by a select with the
3477     // same operands, as follows:
3478     //   c = fcmp [ogt, olt, ugt, ult] a, b
3479     //   select c, a, b
3480     // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3481     // handled differently than the original code sequence.
3482     if (getTargetMachine().Options.UnsafeFPMath && LHS == TrueVal &&
3483         RHS == FalseVal) {
3484       if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3485         return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3486       if (CC == ISD::SETOLT || CC == ISD::SETULT)
3487         return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3488     }
3489
3490     bool swpCmpOps = false;
3491     bool swpVselOps = false;
3492     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3493
3494     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3495         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3496       if (swpCmpOps)
3497         std::swap(LHS, RHS);
3498       if (swpVselOps)
3499         std::swap(TrueVal, FalseVal);
3500     }
3501   }
3502
3503   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3504   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3505   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3506   SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
3507                                ARMcc, CCR, Cmp);
3508   if (CondCode2 != ARMCC::AL) {
3509     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3510     // FIXME: Needs another CMP because flag can have but one use.
3511     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3512     Result = DAG.getNode(ARMISD::CMOV, dl, VT,
3513                          Result, TrueVal, ARMcc2, CCR, Cmp2);
3514   }
3515   return Result;
3516 }
3517
3518 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3519 /// to morph to an integer compare sequence.
3520 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3521                            const ARMSubtarget *Subtarget) {
3522   SDNode *N = Op.getNode();
3523   if (!N->hasOneUse())
3524     // Otherwise it requires moving the value from fp to integer registers.
3525     return false;
3526   if (!N->getNumValues())
3527     return false;
3528   EVT VT = Op.getValueType();
3529   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3530     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3531     // vmrs are very slow, e.g. cortex-a8.
3532     return false;
3533
3534   if (isFloatingPointZero(Op)) {
3535     SeenZero = true;
3536     return true;
3537   }
3538   return ISD::isNormalLoad(N);
3539 }
3540
3541 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3542   if (isFloatingPointZero(Op))
3543     return DAG.getConstant(0, MVT::i32);
3544
3545   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3546     return DAG.getLoad(MVT::i32, SDLoc(Op),
3547                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3548                        Ld->isVolatile(), Ld->isNonTemporal(),
3549                        Ld->isInvariant(), Ld->getAlignment());
3550
3551   llvm_unreachable("Unknown VFP cmp argument!");
3552 }
3553
3554 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3555                            SDValue &RetVal1, SDValue &RetVal2) {
3556   if (isFloatingPointZero(Op)) {
3557     RetVal1 = DAG.getConstant(0, MVT::i32);
3558     RetVal2 = DAG.getConstant(0, MVT::i32);
3559     return;
3560   }
3561
3562   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3563     SDValue Ptr = Ld->getBasePtr();
3564     RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3565                           Ld->getChain(), Ptr,
3566                           Ld->getPointerInfo(),
3567                           Ld->isVolatile(), Ld->isNonTemporal(),
3568                           Ld->isInvariant(), Ld->getAlignment());
3569
3570     EVT PtrType = Ptr.getValueType();
3571     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3572     SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3573                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
3574     RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3575                           Ld->getChain(), NewPtr,
3576                           Ld->getPointerInfo().getWithOffset(4),
3577                           Ld->isVolatile(), Ld->isNonTemporal(),
3578                           Ld->isInvariant(), NewAlign);
3579     return;
3580   }
3581
3582   llvm_unreachable("Unknown VFP cmp argument!");
3583 }
3584
3585 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3586 /// f32 and even f64 comparisons to integer ones.
3587 SDValue
3588 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3589   SDValue Chain = Op.getOperand(0);
3590   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3591   SDValue LHS = Op.getOperand(2);
3592   SDValue RHS = Op.getOperand(3);
3593   SDValue Dest = Op.getOperand(4);
3594   SDLoc dl(Op);
3595
3596   bool LHSSeenZero = false;
3597   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3598   bool RHSSeenZero = false;
3599   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3600   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3601     // If unsafe fp math optimization is enabled and there are no other uses of
3602     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3603     // to an integer comparison.
3604     if (CC == ISD::SETOEQ)
3605       CC = ISD::SETEQ;
3606     else if (CC == ISD::SETUNE)
3607       CC = ISD::SETNE;
3608
3609     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3610     SDValue ARMcc;
3611     if (LHS.getValueType() == MVT::f32) {
3612       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3613                         bitcastf32Toi32(LHS, DAG), Mask);
3614       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3615                         bitcastf32Toi32(RHS, DAG), Mask);
3616       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3617       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3618       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3619                          Chain, Dest, ARMcc, CCR, Cmp);
3620     }
3621
3622     SDValue LHS1, LHS2;
3623     SDValue RHS1, RHS2;
3624     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3625     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3626     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3627     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3628     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3629     ARMcc = DAG.getConstant(CondCode, MVT::i32);
3630     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3631     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3632     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3633   }
3634
3635   return SDValue();
3636 }
3637
3638 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3639   SDValue Chain = Op.getOperand(0);
3640   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3641   SDValue LHS = Op.getOperand(2);
3642   SDValue RHS = Op.getOperand(3);
3643   SDValue Dest = Op.getOperand(4);
3644   SDLoc dl(Op);
3645
3646   if (LHS.getValueType() == MVT::i32) {
3647     SDValue ARMcc;
3648     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3649     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3650     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3651                        Chain, Dest, ARMcc, CCR, Cmp);
3652   }
3653
3654   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3655
3656   if (getTargetMachine().Options.UnsafeFPMath &&
3657       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3658        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3659     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3660     if (Result.getNode())
3661       return Result;
3662   }
3663
3664   ARMCC::CondCodes CondCode, CondCode2;
3665   FPCCToARMCC(CC, CondCode, CondCode2);
3666
3667   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3668   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3669   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3670   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3671   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3672   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3673   if (CondCode2 != ARMCC::AL) {
3674     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3675     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3676     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3677   }
3678   return Res;
3679 }
3680
3681 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3682   SDValue Chain = Op.getOperand(0);
3683   SDValue Table = Op.getOperand(1);
3684   SDValue Index = Op.getOperand(2);
3685   SDLoc dl(Op);
3686
3687   EVT PTy = getPointerTy();
3688   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3689   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3690   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3691   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3692   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3693   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3694   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3695   if (Subtarget->isThumb2()) {
3696     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3697     // which does another jump to the destination. This also makes it easier
3698     // to translate it to TBB / TBH later.
3699     // FIXME: This might not work if the function is extremely large.
3700     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3701                        Addr, Op.getOperand(2), JTI, UId);
3702   }
3703   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3704     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3705                        MachinePointerInfo::getJumpTable(),
3706                        false, false, false, 0);
3707     Chain = Addr.getValue(1);
3708     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3709     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3710   } else {
3711     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3712                        MachinePointerInfo::getJumpTable(),
3713                        false, false, false, 0);
3714     Chain = Addr.getValue(1);
3715     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3716   }
3717 }
3718
3719 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3720   EVT VT = Op.getValueType();
3721   SDLoc dl(Op);
3722
3723   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3724     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3725       return Op;
3726     return DAG.UnrollVectorOp(Op.getNode());
3727   }
3728
3729   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3730          "Invalid type for custom lowering!");
3731   if (VT != MVT::v4i16)
3732     return DAG.UnrollVectorOp(Op.getNode());
3733
3734   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3735   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3736 }
3737
3738 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3739   EVT VT = Op.getValueType();
3740   if (VT.isVector())
3741     return LowerVectorFP_TO_INT(Op, DAG);
3742
3743   SDLoc dl(Op);
3744   unsigned Opc;
3745
3746   switch (Op.getOpcode()) {
3747   default: llvm_unreachable("Invalid opcode!");
3748   case ISD::FP_TO_SINT:
3749     Opc = ARMISD::FTOSI;
3750     break;
3751   case ISD::FP_TO_UINT:
3752     Opc = ARMISD::FTOUI;
3753     break;
3754   }
3755   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3756   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3757 }
3758
3759 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3760   EVT VT = Op.getValueType();
3761   SDLoc dl(Op);
3762
3763   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3764     if (VT.getVectorElementType() == MVT::f32)
3765       return Op;
3766     return DAG.UnrollVectorOp(Op.getNode());
3767   }
3768
3769   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3770          "Invalid type for custom lowering!");
3771   if (VT != MVT::v4f32)
3772     return DAG.UnrollVectorOp(Op.getNode());
3773
3774   unsigned CastOpc;
3775   unsigned Opc;
3776   switch (Op.getOpcode()) {
3777   default: llvm_unreachable("Invalid opcode!");
3778   case ISD::SINT_TO_FP:
3779     CastOpc = ISD::SIGN_EXTEND;
3780     Opc = ISD::SINT_TO_FP;
3781     break;
3782   case ISD::UINT_TO_FP:
3783     CastOpc = ISD::ZERO_EXTEND;
3784     Opc = ISD::UINT_TO_FP;
3785     break;
3786   }
3787
3788   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3789   return DAG.getNode(Opc, dl, VT, Op);
3790 }
3791
3792 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3793   EVT VT = Op.getValueType();
3794   if (VT.isVector())
3795     return LowerVectorINT_TO_FP(Op, DAG);
3796
3797   SDLoc dl(Op);
3798   unsigned Opc;
3799
3800   switch (Op.getOpcode()) {
3801   default: llvm_unreachable("Invalid opcode!");
3802   case ISD::SINT_TO_FP:
3803     Opc = ARMISD::SITOF;
3804     break;
3805   case ISD::UINT_TO_FP:
3806     Opc = ARMISD::UITOF;
3807     break;
3808   }
3809
3810   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3811   return DAG.getNode(Opc, dl, VT, Op);
3812 }
3813
3814 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3815   // Implement fcopysign with a fabs and a conditional fneg.
3816   SDValue Tmp0 = Op.getOperand(0);
3817   SDValue Tmp1 = Op.getOperand(1);
3818   SDLoc dl(Op);
3819   EVT VT = Op.getValueType();
3820   EVT SrcVT = Tmp1.getValueType();
3821   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3822     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3823   bool UseNEON = !InGPR && Subtarget->hasNEON();
3824
3825   if (UseNEON) {
3826     // Use VBSL to copy the sign bit.
3827     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3828     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3829                                DAG.getTargetConstant(EncodedVal, MVT::i32));
3830     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3831     if (VT == MVT::f64)
3832       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3833                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3834                          DAG.getConstant(32, MVT::i32));
3835     else /*if (VT == MVT::f32)*/
3836       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3837     if (SrcVT == MVT::f32) {
3838       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3839       if (VT == MVT::f64)
3840         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3841                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3842                            DAG.getConstant(32, MVT::i32));
3843     } else if (VT == MVT::f32)
3844       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3845                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3846                          DAG.getConstant(32, MVT::i32));
3847     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3848     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3849
3850     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3851                                             MVT::i32);
3852     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3853     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3854                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3855
3856     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3857                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3858                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3859     if (VT == MVT::f32) {
3860       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3861       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3862                         DAG.getConstant(0, MVT::i32));
3863     } else {
3864       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3865     }
3866
3867     return Res;
3868   }
3869
3870   // Bitcast operand 1 to i32.
3871   if (SrcVT == MVT::f64)
3872     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3873                        Tmp1).getValue(1);
3874   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3875
3876   // Or in the signbit with integer operations.
3877   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3878   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3879   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3880   if (VT == MVT::f32) {
3881     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3882                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3883     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3884                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3885   }
3886
3887   // f64: Or the high part with signbit and then combine two parts.
3888   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3889                      Tmp0);
3890   SDValue Lo = Tmp0.getValue(0);
3891   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3892   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3893   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3894 }
3895
3896 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3897   MachineFunction &MF = DAG.getMachineFunction();
3898   MachineFrameInfo *MFI = MF.getFrameInfo();
3899   MFI->setReturnAddressIsTaken(true);
3900
3901   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3902     return SDValue();
3903
3904   EVT VT = Op.getValueType();
3905   SDLoc dl(Op);
3906   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3907   if (Depth) {
3908     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3909     SDValue Offset = DAG.getConstant(4, MVT::i32);
3910     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3911                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3912                        MachinePointerInfo(), false, false, false, 0);
3913   }
3914
3915   // Return LR, which contains the return address. Mark it an implicit live-in.
3916   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3917   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3918 }
3919
3920 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3921   const ARMBaseRegisterInfo &ARI =
3922     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
3923   MachineFunction &MF = DAG.getMachineFunction();
3924   MachineFrameInfo *MFI = MF.getFrameInfo();
3925   MFI->setFrameAddressIsTaken(true);
3926
3927   EVT VT = Op.getValueType();
3928   SDLoc dl(Op);  // FIXME probably not meaningful
3929   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3930   unsigned FrameReg = ARI.getFrameRegister(MF);
3931   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3932   while (Depth--)
3933     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3934                             MachinePointerInfo(),
3935                             false, false, false, 0);
3936   return FrameAddr;
3937 }
3938
3939 // FIXME? Maybe this could be a TableGen attribute on some registers and
3940 // this table could be generated automatically from RegInfo.
3941 unsigned ARMTargetLowering::getRegisterByName(const char* RegName,
3942                                               EVT VT) const {
3943   unsigned Reg = StringSwitch<unsigned>(RegName)
3944                        .Case("sp", ARM::SP)
3945                        .Default(0);
3946   if (Reg)
3947     return Reg;
3948   report_fatal_error("Invalid register name global variable");
3949 }
3950
3951 /// ExpandBITCAST - If the target supports VFP, this function is called to
3952 /// expand a bit convert where either the source or destination type is i64 to
3953 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
3954 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3955 /// vectors), since the legalizer won't know what to do with that.
3956 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3957   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3958   SDLoc dl(N);
3959   SDValue Op = N->getOperand(0);
3960
3961   // This function is only supposed to be called for i64 types, either as the
3962   // source or destination of the bit convert.
3963   EVT SrcVT = Op.getValueType();
3964   EVT DstVT = N->getValueType(0);
3965   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3966          "ExpandBITCAST called for non-i64 type");
3967
3968   // Turn i64->f64 into VMOVDRR.
3969   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3970     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3971                              DAG.getConstant(0, MVT::i32));
3972     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3973                              DAG.getConstant(1, MVT::i32));
3974     return DAG.getNode(ISD::BITCAST, dl, DstVT,
3975                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3976   }
3977
3978   // Turn f64->i64 into VMOVRRD.
3979   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3980     SDValue Cvt;
3981     if (TLI.isBigEndian() && SrcVT.isVector() &&
3982         SrcVT.getVectorNumElements() > 1)
3983       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3984                         DAG.getVTList(MVT::i32, MVT::i32),
3985                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
3986     else
3987       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3988                         DAG.getVTList(MVT::i32, MVT::i32), Op);
3989     // Merge the pieces into a single i64 value.
3990     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3991   }
3992
3993   return SDValue();
3994 }
3995
3996 /// getZeroVector - Returns a vector of specified type with all zero elements.
3997 /// Zero vectors are used to represent vector negation and in those cases
3998 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
3999 /// not support i64 elements, so sometimes the zero vectors will need to be
4000 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
4001 /// zero vector.
4002 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4003   assert(VT.isVector() && "Expected a vector type");
4004   // The canonical modified immediate encoding of a zero vector is....0!
4005   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
4006   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4007   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4008   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4009 }
4010
4011 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4012 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4013 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4014                                                 SelectionDAG &DAG) const {
4015   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4016   EVT VT = Op.getValueType();
4017   unsigned VTBits = VT.getSizeInBits();
4018   SDLoc dl(Op);
4019   SDValue ShOpLo = Op.getOperand(0);
4020   SDValue ShOpHi = Op.getOperand(1);
4021   SDValue ShAmt  = Op.getOperand(2);
4022   SDValue ARMcc;
4023   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4024
4025   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4026
4027   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4028                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
4029   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4030   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4031                                    DAG.getConstant(VTBits, MVT::i32));
4032   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4033   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4034   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4035
4036   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4037   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4038                           ARMcc, DAG, dl);
4039   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4040   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4041                            CCR, Cmp);
4042
4043   SDValue Ops[2] = { Lo, Hi };
4044   return DAG.getMergeValues(Ops, dl);
4045 }
4046
4047 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4048 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4049 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4050                                                SelectionDAG &DAG) const {
4051   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4052   EVT VT = Op.getValueType();
4053   unsigned VTBits = VT.getSizeInBits();
4054   SDLoc dl(Op);
4055   SDValue ShOpLo = Op.getOperand(0);
4056   SDValue ShOpHi = Op.getOperand(1);
4057   SDValue ShAmt  = Op.getOperand(2);
4058   SDValue ARMcc;
4059
4060   assert(Op.getOpcode() == ISD::SHL_PARTS);
4061   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4062                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
4063   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4064   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4065                                    DAG.getConstant(VTBits, MVT::i32));
4066   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4067   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4068
4069   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4070   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4071   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4072                           ARMcc, DAG, dl);
4073   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4074   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4075                            CCR, Cmp);
4076
4077   SDValue Ops[2] = { Lo, Hi };
4078   return DAG.getMergeValues(Ops, dl);
4079 }
4080
4081 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4082                                             SelectionDAG &DAG) const {
4083   // The rounding mode is in bits 23:22 of the FPSCR.
4084   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4085   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4086   // so that the shift + and get folded into a bitfield extract.
4087   SDLoc dl(Op);
4088   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4089                               DAG.getConstant(Intrinsic::arm_get_fpscr,
4090                                               MVT::i32));
4091   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4092                                   DAG.getConstant(1U << 22, MVT::i32));
4093   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4094                               DAG.getConstant(22, MVT::i32));
4095   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4096                      DAG.getConstant(3, MVT::i32));
4097 }
4098
4099 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4100                          const ARMSubtarget *ST) {
4101   EVT VT = N->getValueType(0);
4102   SDLoc dl(N);
4103
4104   if (!ST->hasV6T2Ops())
4105     return SDValue();
4106
4107   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4108   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4109 }
4110
4111 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4112 /// for each 16-bit element from operand, repeated.  The basic idea is to
4113 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4114 ///
4115 /// Trace for v4i16:
4116 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
4117 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4118 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4119 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4120 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
4121 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
4122 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4123 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
4124 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4125   EVT VT = N->getValueType(0);
4126   SDLoc DL(N);
4127
4128   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4129   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4130   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4131   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4132   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4133   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4134 }
4135
4136 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4137 /// bit-count for each 16-bit element from the operand.  We need slightly
4138 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4139 /// 64/128-bit registers.
4140 ///
4141 /// Trace for v4i16:
4142 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
4143 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4144 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
4145 /// v4i16:Extracted = [k0    k1    k2    k3    ]
4146 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4147   EVT VT = N->getValueType(0);
4148   SDLoc DL(N);
4149
4150   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4151   if (VT.is64BitVector()) {
4152     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4153     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4154                        DAG.getIntPtrConstant(0));
4155   } else {
4156     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4157                                     BitCounts, DAG.getIntPtrConstant(0));
4158     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4159   }
4160 }
4161
4162 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4163 /// bit-count for each 32-bit element from the operand.  The idea here is
4164 /// to split the vector into 16-bit elements, leverage the 16-bit count
4165 /// routine, and then combine the results.
4166 ///
4167 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4168 /// input    = [v0    v1    ] (vi: 32-bit elements)
4169 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4170 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4171 /// vrev: N0 = [k1 k0 k3 k2 ]
4172 ///            [k0 k1 k2 k3 ]
4173 ///       N1 =+[k1 k0 k3 k2 ]
4174 ///            [k0 k2 k1 k3 ]
4175 ///       N2 =+[k1 k3 k0 k2 ]
4176 ///            [k0    k2    k1    k3    ]
4177 /// Extended =+[k1    k3    k0    k2    ]
4178 ///            [k0    k2    ]
4179 /// Extracted=+[k1    k3    ]
4180 ///
4181 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4182   EVT VT = N->getValueType(0);
4183   SDLoc DL(N);
4184
4185   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4186
4187   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4188   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4189   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4190   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4191   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4192
4193   if (VT.is64BitVector()) {
4194     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4195     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4196                        DAG.getIntPtrConstant(0));
4197   } else {
4198     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4199                                     DAG.getIntPtrConstant(0));
4200     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4201   }
4202 }
4203
4204 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4205                           const ARMSubtarget *ST) {
4206   EVT VT = N->getValueType(0);
4207
4208   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4209   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4210           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4211          "Unexpected type for custom ctpop lowering");
4212
4213   if (VT.getVectorElementType() == MVT::i32)
4214     return lowerCTPOP32BitElements(N, DAG);
4215   else
4216     return lowerCTPOP16BitElements(N, DAG);
4217 }
4218
4219 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4220                           const ARMSubtarget *ST) {
4221   EVT VT = N->getValueType(0);
4222   SDLoc dl(N);
4223
4224   if (!VT.isVector())
4225     return SDValue();
4226
4227   // Lower vector shifts on NEON to use VSHL.
4228   assert(ST->hasNEON() && "unexpected vector shift");
4229
4230   // Left shifts translate directly to the vshiftu intrinsic.
4231   if (N->getOpcode() == ISD::SHL)
4232     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4233                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4234                        N->getOperand(0), N->getOperand(1));
4235
4236   assert((N->getOpcode() == ISD::SRA ||
4237           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4238
4239   // NEON uses the same intrinsics for both left and right shifts.  For
4240   // right shifts, the shift amounts are negative, so negate the vector of
4241   // shift amounts.
4242   EVT ShiftVT = N->getOperand(1).getValueType();
4243   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4244                                      getZeroVector(ShiftVT, DAG, dl),
4245                                      N->getOperand(1));
4246   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4247                              Intrinsic::arm_neon_vshifts :
4248                              Intrinsic::arm_neon_vshiftu);
4249   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4250                      DAG.getConstant(vshiftInt, MVT::i32),
4251                      N->getOperand(0), NegatedCount);
4252 }
4253
4254 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4255                                 const ARMSubtarget *ST) {
4256   EVT VT = N->getValueType(0);
4257   SDLoc dl(N);
4258
4259   // We can get here for a node like i32 = ISD::SHL i32, i64
4260   if (VT != MVT::i64)
4261     return SDValue();
4262
4263   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4264          "Unknown shift to lower!");
4265
4266   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4267   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4268       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4269     return SDValue();
4270
4271   // If we are in thumb mode, we don't have RRX.
4272   if (ST->isThumb1Only()) return SDValue();
4273
4274   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4275   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4276                            DAG.getConstant(0, MVT::i32));
4277   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4278                            DAG.getConstant(1, MVT::i32));
4279
4280   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4281   // captures the result into a carry flag.
4282   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4283   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4284
4285   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4286   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4287
4288   // Merge the pieces into a single i64 value.
4289  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4290 }
4291
4292 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4293   SDValue TmpOp0, TmpOp1;
4294   bool Invert = false;
4295   bool Swap = false;
4296   unsigned Opc = 0;
4297
4298   SDValue Op0 = Op.getOperand(0);
4299   SDValue Op1 = Op.getOperand(1);
4300   SDValue CC = Op.getOperand(2);
4301   EVT VT = Op.getValueType();
4302   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4303   SDLoc dl(Op);
4304
4305   if (Op.getOperand(1).getValueType().isFloatingPoint()) {
4306     switch (SetCCOpcode) {
4307     default: llvm_unreachable("Illegal FP comparison");
4308     case ISD::SETUNE:
4309     case ISD::SETNE:  Invert = true; // Fallthrough
4310     case ISD::SETOEQ:
4311     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4312     case ISD::SETOLT:
4313     case ISD::SETLT: Swap = true; // Fallthrough
4314     case ISD::SETOGT:
4315     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4316     case ISD::SETOLE:
4317     case ISD::SETLE:  Swap = true; // Fallthrough
4318     case ISD::SETOGE:
4319     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4320     case ISD::SETUGE: Swap = true; // Fallthrough
4321     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4322     case ISD::SETUGT: Swap = true; // Fallthrough
4323     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4324     case ISD::SETUEQ: Invert = true; // Fallthrough
4325     case ISD::SETONE:
4326       // Expand this to (OLT | OGT).
4327       TmpOp0 = Op0;
4328       TmpOp1 = Op1;
4329       Opc = ISD::OR;
4330       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4331       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
4332       break;
4333     case ISD::SETUO: Invert = true; // Fallthrough
4334     case ISD::SETO:
4335       // Expand this to (OLT | OGE).
4336       TmpOp0 = Op0;
4337       TmpOp1 = Op1;
4338       Opc = ISD::OR;
4339       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4340       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
4341       break;
4342     }
4343   } else {
4344     // Integer comparisons.
4345     switch (SetCCOpcode) {
4346     default: llvm_unreachable("Illegal integer comparison");
4347     case ISD::SETNE:  Invert = true;
4348     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4349     case ISD::SETLT:  Swap = true;
4350     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4351     case ISD::SETLE:  Swap = true;
4352     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4353     case ISD::SETULT: Swap = true;
4354     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4355     case ISD::SETULE: Swap = true;
4356     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4357     }
4358
4359     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4360     if (Opc == ARMISD::VCEQ) {
4361
4362       SDValue AndOp;
4363       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4364         AndOp = Op0;
4365       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4366         AndOp = Op1;
4367
4368       // Ignore bitconvert.
4369       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4370         AndOp = AndOp.getOperand(0);
4371
4372       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4373         Opc = ARMISD::VTST;
4374         Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
4375         Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4376         Invert = !Invert;
4377       }
4378     }
4379   }
4380
4381   if (Swap)
4382     std::swap(Op0, Op1);
4383
4384   // If one of the operands is a constant vector zero, attempt to fold the
4385   // comparison to a specialized compare-against-zero form.
4386   SDValue SingleOp;
4387   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4388     SingleOp = Op0;
4389   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4390     if (Opc == ARMISD::VCGE)
4391       Opc = ARMISD::VCLEZ;
4392     else if (Opc == ARMISD::VCGT)
4393       Opc = ARMISD::VCLTZ;
4394     SingleOp = Op1;
4395   }
4396
4397   SDValue Result;
4398   if (SingleOp.getNode()) {
4399     switch (Opc) {
4400     case ARMISD::VCEQ:
4401       Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4402     case ARMISD::VCGE:
4403       Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4404     case ARMISD::VCLEZ:
4405       Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4406     case ARMISD::VCGT:
4407       Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4408     case ARMISD::VCLTZ:
4409       Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4410     default:
4411       Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4412     }
4413   } else {
4414      Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4415   }
4416
4417   if (Invert)
4418     Result = DAG.getNOT(dl, Result, VT);
4419
4420   return Result;
4421 }
4422
4423 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4424 /// valid vector constant for a NEON instruction with a "modified immediate"
4425 /// operand (e.g., VMOV).  If so, return the encoded value.
4426 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4427                                  unsigned SplatBitSize, SelectionDAG &DAG,
4428                                  EVT &VT, bool is128Bits, NEONModImmType type) {
4429   unsigned OpCmode, Imm;
4430
4431   // SplatBitSize is set to the smallest size that splats the vector, so a
4432   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4433   // immediate instructions others than VMOV do not support the 8-bit encoding
4434   // of a zero vector, and the default encoding of zero is supposed to be the
4435   // 32-bit version.
4436   if (SplatBits == 0)
4437     SplatBitSize = 32;
4438
4439   switch (SplatBitSize) {
4440   case 8:
4441     if (type != VMOVModImm)
4442       return SDValue();
4443     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4444     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4445     OpCmode = 0xe;
4446     Imm = SplatBits;
4447     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4448     break;
4449
4450   case 16:
4451     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4452     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4453     if ((SplatBits & ~0xff) == 0) {
4454       // Value = 0x00nn: Op=x, Cmode=100x.
4455       OpCmode = 0x8;
4456       Imm = SplatBits;
4457       break;
4458     }
4459     if ((SplatBits & ~0xff00) == 0) {
4460       // Value = 0xnn00: Op=x, Cmode=101x.
4461       OpCmode = 0xa;
4462       Imm = SplatBits >> 8;
4463       break;
4464     }
4465     return SDValue();
4466
4467   case 32:
4468     // NEON's 32-bit VMOV supports splat values where:
4469     // * only one byte is nonzero, or
4470     // * the least significant byte is 0xff and the second byte is nonzero, or
4471     // * the least significant 2 bytes are 0xff and the third is nonzero.
4472     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4473     if ((SplatBits & ~0xff) == 0) {
4474       // Value = 0x000000nn: Op=x, Cmode=000x.
4475       OpCmode = 0;
4476       Imm = SplatBits;
4477       break;
4478     }
4479     if ((SplatBits & ~0xff00) == 0) {
4480       // Value = 0x0000nn00: Op=x, Cmode=001x.
4481       OpCmode = 0x2;
4482       Imm = SplatBits >> 8;
4483       break;
4484     }
4485     if ((SplatBits & ~0xff0000) == 0) {
4486       // Value = 0x00nn0000: Op=x, Cmode=010x.
4487       OpCmode = 0x4;
4488       Imm = SplatBits >> 16;
4489       break;
4490     }
4491     if ((SplatBits & ~0xff000000) == 0) {
4492       // Value = 0xnn000000: Op=x, Cmode=011x.
4493       OpCmode = 0x6;
4494       Imm = SplatBits >> 24;
4495       break;
4496     }
4497
4498     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4499     if (type == OtherModImm) return SDValue();
4500
4501     if ((SplatBits & ~0xffff) == 0 &&
4502         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4503       // Value = 0x0000nnff: Op=x, Cmode=1100.
4504       OpCmode = 0xc;
4505       Imm = SplatBits >> 8;
4506       break;
4507     }
4508
4509     if ((SplatBits & ~0xffffff) == 0 &&
4510         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4511       // Value = 0x00nnffff: Op=x, Cmode=1101.
4512       OpCmode = 0xd;
4513       Imm = SplatBits >> 16;
4514       break;
4515     }
4516
4517     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4518     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4519     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4520     // and fall through here to test for a valid 64-bit splat.  But, then the
4521     // caller would also need to check and handle the change in size.
4522     return SDValue();
4523
4524   case 64: {
4525     if (type != VMOVModImm)
4526       return SDValue();
4527     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4528     uint64_t BitMask = 0xff;
4529     uint64_t Val = 0;
4530     unsigned ImmMask = 1;
4531     Imm = 0;
4532     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4533       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4534         Val |= BitMask;
4535         Imm |= ImmMask;
4536       } else if ((SplatBits & BitMask) != 0) {
4537         return SDValue();
4538       }
4539       BitMask <<= 8;
4540       ImmMask <<= 1;
4541     }
4542
4543     if (DAG.getTargetLoweringInfo().isBigEndian())
4544       // swap higher and lower 32 bit word
4545       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4546
4547     // Op=1, Cmode=1110.
4548     OpCmode = 0x1e;
4549     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4550     break;
4551   }
4552
4553   default:
4554     llvm_unreachable("unexpected size for isNEONModifiedImm");
4555   }
4556
4557   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4558   return DAG.getTargetConstant(EncodedVal, MVT::i32);
4559 }
4560
4561 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4562                                            const ARMSubtarget *ST) const {
4563   if (!ST->hasVFP3())
4564     return SDValue();
4565
4566   bool IsDouble = Op.getValueType() == MVT::f64;
4567   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4568
4569   // Try splatting with a VMOV.f32...
4570   APFloat FPVal = CFP->getValueAPF();
4571   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4572
4573   if (ImmVal != -1) {
4574     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4575       // We have code in place to select a valid ConstantFP already, no need to
4576       // do any mangling.
4577       return Op;
4578     }
4579
4580     // It's a float and we are trying to use NEON operations where
4581     // possible. Lower it to a splat followed by an extract.
4582     SDLoc DL(Op);
4583     SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4584     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4585                                       NewVal);
4586     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4587                        DAG.getConstant(0, MVT::i32));
4588   }
4589
4590   // The rest of our options are NEON only, make sure that's allowed before
4591   // proceeding..
4592   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4593     return SDValue();
4594
4595   EVT VMovVT;
4596   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4597
4598   // It wouldn't really be worth bothering for doubles except for one very
4599   // important value, which does happen to match: 0.0. So make sure we don't do
4600   // anything stupid.
4601   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4602     return SDValue();
4603
4604   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4605   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4606                                      false, VMOVModImm);
4607   if (NewVal != SDValue()) {
4608     SDLoc DL(Op);
4609     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4610                                       NewVal);
4611     if (IsDouble)
4612       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4613
4614     // It's a float: cast and extract a vector element.
4615     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4616                                        VecConstant);
4617     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4618                        DAG.getConstant(0, MVT::i32));
4619   }
4620
4621   // Finally, try a VMVN.i32
4622   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4623                              false, VMVNModImm);
4624   if (NewVal != SDValue()) {
4625     SDLoc DL(Op);
4626     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4627
4628     if (IsDouble)
4629       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4630
4631     // It's a float: cast and extract a vector element.
4632     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4633                                        VecConstant);
4634     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4635                        DAG.getConstant(0, MVT::i32));
4636   }
4637
4638   return SDValue();
4639 }
4640
4641 // check if an VEXT instruction can handle the shuffle mask when the
4642 // vector sources of the shuffle are the same.
4643 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4644   unsigned NumElts = VT.getVectorNumElements();
4645
4646   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4647   if (M[0] < 0)
4648     return false;
4649
4650   Imm = M[0];
4651
4652   // If this is a VEXT shuffle, the immediate value is the index of the first
4653   // element.  The other shuffle indices must be the successive elements after
4654   // the first one.
4655   unsigned ExpectedElt = Imm;
4656   for (unsigned i = 1; i < NumElts; ++i) {
4657     // Increment the expected index.  If it wraps around, just follow it
4658     // back to index zero and keep going.
4659     ++ExpectedElt;
4660     if (ExpectedElt == NumElts)
4661       ExpectedElt = 0;
4662
4663     if (M[i] < 0) continue; // ignore UNDEF indices
4664     if (ExpectedElt != static_cast<unsigned>(M[i]))
4665       return false;
4666   }
4667
4668   return true;
4669 }
4670
4671
4672 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4673                        bool &ReverseVEXT, unsigned &Imm) {
4674   unsigned NumElts = VT.getVectorNumElements();
4675   ReverseVEXT = false;
4676
4677   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4678   if (M[0] < 0)
4679     return false;
4680
4681   Imm = M[0];
4682
4683   // If this is a VEXT shuffle, the immediate value is the index of the first
4684   // element.  The other shuffle indices must be the successive elements after
4685   // the first one.
4686   unsigned ExpectedElt = Imm;
4687   for (unsigned i = 1; i < NumElts; ++i) {
4688     // Increment the expected index.  If it wraps around, it may still be
4689     // a VEXT but the source vectors must be swapped.
4690     ExpectedElt += 1;
4691     if (ExpectedElt == NumElts * 2) {
4692       ExpectedElt = 0;
4693       ReverseVEXT = true;
4694     }
4695
4696     if (M[i] < 0) continue; // ignore UNDEF indices
4697     if (ExpectedElt != static_cast<unsigned>(M[i]))
4698       return false;
4699   }
4700
4701   // Adjust the index value if the source operands will be swapped.
4702   if (ReverseVEXT)
4703     Imm -= NumElts;
4704
4705   return true;
4706 }
4707
4708 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4709 /// instruction with the specified blocksize.  (The order of the elements
4710 /// within each block of the vector is reversed.)
4711 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4712   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4713          "Only possible block sizes for VREV are: 16, 32, 64");
4714
4715   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4716   if (EltSz == 64)
4717     return false;
4718
4719   unsigned NumElts = VT.getVectorNumElements();
4720   unsigned BlockElts = M[0] + 1;
4721   // If the first shuffle index is UNDEF, be optimistic.
4722   if (M[0] < 0)
4723     BlockElts = BlockSize / EltSz;
4724
4725   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4726     return false;
4727
4728   for (unsigned i = 0; i < NumElts; ++i) {
4729     if (M[i] < 0) continue; // ignore UNDEF indices
4730     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4731       return false;
4732   }
4733
4734   return true;
4735 }
4736
4737 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4738   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4739   // range, then 0 is placed into the resulting vector. So pretty much any mask
4740   // of 8 elements can work here.
4741   return VT == MVT::v8i8 && M.size() == 8;
4742 }
4743
4744 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4745   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4746   if (EltSz == 64)
4747     return false;
4748
4749   unsigned NumElts = VT.getVectorNumElements();
4750   WhichResult = (M[0] == 0 ? 0 : 1);
4751   for (unsigned i = 0; i < NumElts; i += 2) {
4752     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4753         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4754       return false;
4755   }
4756   return true;
4757 }
4758
4759 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4760 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4761 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4762 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4763   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4764   if (EltSz == 64)
4765     return false;
4766
4767   unsigned NumElts = VT.getVectorNumElements();
4768   WhichResult = (M[0] == 0 ? 0 : 1);
4769   for (unsigned i = 0; i < NumElts; i += 2) {
4770     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4771         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4772       return false;
4773   }
4774   return true;
4775 }
4776
4777 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4778   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4779   if (EltSz == 64)
4780     return false;
4781
4782   unsigned NumElts = VT.getVectorNumElements();
4783   WhichResult = (M[0] == 0 ? 0 : 1);
4784   for (unsigned i = 0; i != NumElts; ++i) {
4785     if (M[i] < 0) continue; // ignore UNDEF indices
4786     if ((unsigned) M[i] != 2 * i + WhichResult)
4787       return false;
4788   }
4789
4790   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4791   if (VT.is64BitVector() && EltSz == 32)
4792     return false;
4793
4794   return true;
4795 }
4796
4797 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4798 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4799 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4800 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4801   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4802   if (EltSz == 64)
4803     return false;
4804
4805   unsigned Half = VT.getVectorNumElements() / 2;
4806   WhichResult = (M[0] == 0 ? 0 : 1);
4807   for (unsigned j = 0; j != 2; ++j) {
4808     unsigned Idx = WhichResult;
4809     for (unsigned i = 0; i != Half; ++i) {
4810       int MIdx = M[i + j * Half];
4811       if (MIdx >= 0 && (unsigned) MIdx != Idx)
4812         return false;
4813       Idx += 2;
4814     }
4815   }
4816
4817   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4818   if (VT.is64BitVector() && EltSz == 32)
4819     return false;
4820
4821   return true;
4822 }
4823
4824 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4825   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4826   if (EltSz == 64)
4827     return false;
4828
4829   unsigned NumElts = VT.getVectorNumElements();
4830   WhichResult = (M[0] == 0 ? 0 : 1);
4831   unsigned Idx = WhichResult * NumElts / 2;
4832   for (unsigned i = 0; i != NumElts; i += 2) {
4833     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4834         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4835       return false;
4836     Idx += 1;
4837   }
4838
4839   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4840   if (VT.is64BitVector() && EltSz == 32)
4841     return false;
4842
4843   return true;
4844 }
4845
4846 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4847 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4848 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4849 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4850   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4851   if (EltSz == 64)
4852     return false;
4853
4854   unsigned NumElts = VT.getVectorNumElements();
4855   WhichResult = (M[0] == 0 ? 0 : 1);
4856   unsigned Idx = WhichResult * NumElts / 2;
4857   for (unsigned i = 0; i != NumElts; i += 2) {
4858     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4859         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4860       return false;
4861     Idx += 1;
4862   }
4863
4864   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4865   if (VT.is64BitVector() && EltSz == 32)
4866     return false;
4867
4868   return true;
4869 }
4870
4871 /// \return true if this is a reverse operation on an vector.
4872 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4873   unsigned NumElts = VT.getVectorNumElements();
4874   // Make sure the mask has the right size.
4875   if (NumElts != M.size())
4876       return false;
4877
4878   // Look for <15, ..., 3, -1, 1, 0>.
4879   for (unsigned i = 0; i != NumElts; ++i)
4880     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4881       return false;
4882
4883   return true;
4884 }
4885
4886 // If N is an integer constant that can be moved into a register in one
4887 // instruction, return an SDValue of such a constant (will become a MOV
4888 // instruction).  Otherwise return null.
4889 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4890                                      const ARMSubtarget *ST, SDLoc dl) {
4891   uint64_t Val;
4892   if (!isa<ConstantSDNode>(N))
4893     return SDValue();
4894   Val = cast<ConstantSDNode>(N)->getZExtValue();
4895
4896   if (ST->isThumb1Only()) {
4897     if (Val <= 255 || ~Val <= 255)
4898       return DAG.getConstant(Val, MVT::i32);
4899   } else {
4900     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4901       return DAG.getConstant(Val, MVT::i32);
4902   }
4903   return SDValue();
4904 }
4905
4906 // If this is a case we can't handle, return null and let the default
4907 // expansion code take care of it.
4908 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4909                                              const ARMSubtarget *ST) const {
4910   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4911   SDLoc dl(Op);
4912   EVT VT = Op.getValueType();
4913
4914   APInt SplatBits, SplatUndef;
4915   unsigned SplatBitSize;
4916   bool HasAnyUndefs;
4917   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4918     if (SplatBitSize <= 64) {
4919       // Check if an immediate VMOV works.
4920       EVT VmovVT;
4921       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4922                                       SplatUndef.getZExtValue(), SplatBitSize,
4923                                       DAG, VmovVT, VT.is128BitVector(),
4924                                       VMOVModImm);
4925       if (Val.getNode()) {
4926         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4927         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4928       }
4929
4930       // Try an immediate VMVN.
4931       uint64_t NegatedImm = (~SplatBits).getZExtValue();
4932       Val = isNEONModifiedImm(NegatedImm,
4933                                       SplatUndef.getZExtValue(), SplatBitSize,
4934                                       DAG, VmovVT, VT.is128BitVector(),
4935                                       VMVNModImm);
4936       if (Val.getNode()) {
4937         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4938         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4939       }
4940
4941       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4942       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4943         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4944         if (ImmVal != -1) {
4945           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4946           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4947         }
4948       }
4949     }
4950   }
4951
4952   // Scan through the operands to see if only one value is used.
4953   //
4954   // As an optimisation, even if more than one value is used it may be more
4955   // profitable to splat with one value then change some lanes.
4956   //
4957   // Heuristically we decide to do this if the vector has a "dominant" value,
4958   // defined as splatted to more than half of the lanes.
4959   unsigned NumElts = VT.getVectorNumElements();
4960   bool isOnlyLowElement = true;
4961   bool usesOnlyOneValue = true;
4962   bool hasDominantValue = false;
4963   bool isConstant = true;
4964
4965   // Map of the number of times a particular SDValue appears in the
4966   // element list.
4967   DenseMap<SDValue, unsigned> ValueCounts;
4968   SDValue Value;
4969   for (unsigned i = 0; i < NumElts; ++i) {
4970     SDValue V = Op.getOperand(i);
4971     if (V.getOpcode() == ISD::UNDEF)
4972       continue;
4973     if (i > 0)
4974       isOnlyLowElement = false;
4975     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4976       isConstant = false;
4977
4978     ValueCounts.insert(std::make_pair(V, 0));
4979     unsigned &Count = ValueCounts[V];
4980
4981     // Is this value dominant? (takes up more than half of the lanes)
4982     if (++Count > (NumElts / 2)) {
4983       hasDominantValue = true;
4984       Value = V;
4985     }
4986   }
4987   if (ValueCounts.size() != 1)
4988     usesOnlyOneValue = false;
4989   if (!Value.getNode() && ValueCounts.size() > 0)
4990     Value = ValueCounts.begin()->first;
4991
4992   if (ValueCounts.size() == 0)
4993     return DAG.getUNDEF(VT);
4994
4995   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
4996   // Keep going if we are hitting this case.
4997   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
4998     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4999
5000   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5001
5002   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
5003   // i32 and try again.
5004   if (hasDominantValue && EltSize <= 32) {
5005     if (!isConstant) {
5006       SDValue N;
5007
5008       // If we are VDUPing a value that comes directly from a vector, that will
5009       // cause an unnecessary move to and from a GPR, where instead we could
5010       // just use VDUPLANE. We can only do this if the lane being extracted
5011       // is at a constant index, as the VDUP from lane instructions only have
5012       // constant-index forms.
5013       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5014           isa<ConstantSDNode>(Value->getOperand(1))) {
5015         // We need to create a new undef vector to use for the VDUPLANE if the
5016         // size of the vector from which we get the value is different than the
5017         // size of the vector that we need to create. We will insert the element
5018         // such that the register coalescer will remove unnecessary copies.
5019         if (VT != Value->getOperand(0).getValueType()) {
5020           ConstantSDNode *constIndex;
5021           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5022           assert(constIndex && "The index is not a constant!");
5023           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5024                              VT.getVectorNumElements();
5025           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5026                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5027                         Value, DAG.getConstant(index, MVT::i32)),
5028                            DAG.getConstant(index, MVT::i32));
5029         } else
5030           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5031                         Value->getOperand(0), Value->getOperand(1));
5032       } else
5033         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5034
5035       if (!usesOnlyOneValue) {
5036         // The dominant value was splatted as 'N', but we now have to insert
5037         // all differing elements.
5038         for (unsigned I = 0; I < NumElts; ++I) {
5039           if (Op.getOperand(I) == Value)
5040             continue;
5041           SmallVector<SDValue, 3> Ops;
5042           Ops.push_back(N);
5043           Ops.push_back(Op.getOperand(I));
5044           Ops.push_back(DAG.getConstant(I, MVT::i32));
5045           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5046         }
5047       }
5048       return N;
5049     }
5050     if (VT.getVectorElementType().isFloatingPoint()) {
5051       SmallVector<SDValue, 8> Ops;
5052       for (unsigned i = 0; i < NumElts; ++i)
5053         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5054                                   Op.getOperand(i)));
5055       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5056       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5057       Val = LowerBUILD_VECTOR(Val, DAG, ST);
5058       if (Val.getNode())
5059         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5060     }
5061     if (usesOnlyOneValue) {
5062       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5063       if (isConstant && Val.getNode())
5064         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5065     }
5066   }
5067
5068   // If all elements are constants and the case above didn't get hit, fall back
5069   // to the default expansion, which will generate a load from the constant
5070   // pool.
5071   if (isConstant)
5072     return SDValue();
5073
5074   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5075   if (NumElts >= 4) {
5076     SDValue shuffle = ReconstructShuffle(Op, DAG);
5077     if (shuffle != SDValue())
5078       return shuffle;
5079   }
5080
5081   // Vectors with 32- or 64-bit elements can be built by directly assigning
5082   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
5083   // will be legalized.
5084   if (EltSize >= 32) {
5085     // Do the expansion with floating-point types, since that is what the VFP
5086     // registers are defined to use, and since i64 is not legal.
5087     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5088     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5089     SmallVector<SDValue, 8> Ops;
5090     for (unsigned i = 0; i < NumElts; ++i)
5091       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5092     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5093     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5094   }
5095
5096   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5097   // know the default expansion would otherwise fall back on something even
5098   // worse. For a vector with one or two non-undef values, that's
5099   // scalar_to_vector for the elements followed by a shuffle (provided the
5100   // shuffle is valid for the target) and materialization element by element
5101   // on the stack followed by a load for everything else.
5102   if (!isConstant && !usesOnlyOneValue) {
5103     SDValue Vec = DAG.getUNDEF(VT);
5104     for (unsigned i = 0 ; i < NumElts; ++i) {
5105       SDValue V = Op.getOperand(i);
5106       if (V.getOpcode() == ISD::UNDEF)
5107         continue;
5108       SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
5109       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5110     }
5111     return Vec;
5112   }
5113
5114   return SDValue();
5115 }
5116
5117 // Gather data to see if the operation can be modelled as a
5118 // shuffle in combination with VEXTs.
5119 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5120                                               SelectionDAG &DAG) const {
5121   SDLoc dl(Op);
5122   EVT VT = Op.getValueType();
5123   unsigned NumElts = VT.getVectorNumElements();
5124
5125   SmallVector<SDValue, 2> SourceVecs;
5126   SmallVector<unsigned, 2> MinElts;
5127   SmallVector<unsigned, 2> MaxElts;
5128
5129   for (unsigned i = 0; i < NumElts; ++i) {
5130     SDValue V = Op.getOperand(i);
5131     if (V.getOpcode() == ISD::UNDEF)
5132       continue;
5133     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5134       // A shuffle can only come from building a vector from various
5135       // elements of other vectors.
5136       return SDValue();
5137     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5138                VT.getVectorElementType()) {
5139       // This code doesn't know how to handle shuffles where the vector
5140       // element types do not match (this happens because type legalization
5141       // promotes the return type of EXTRACT_VECTOR_ELT).
5142       // FIXME: It might be appropriate to extend this code to handle
5143       // mismatched types.
5144       return SDValue();
5145     }
5146
5147     // Record this extraction against the appropriate vector if possible...
5148     SDValue SourceVec = V.getOperand(0);
5149     // If the element number isn't a constant, we can't effectively
5150     // analyze what's going on.
5151     if (!isa<ConstantSDNode>(V.getOperand(1)))
5152       return SDValue();
5153     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5154     bool FoundSource = false;
5155     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5156       if (SourceVecs[j] == SourceVec) {
5157         if (MinElts[j] > EltNo)
5158           MinElts[j] = EltNo;
5159         if (MaxElts[j] < EltNo)
5160           MaxElts[j] = EltNo;
5161         FoundSource = true;
5162         break;
5163       }
5164     }
5165
5166     // Or record a new source if not...
5167     if (!FoundSource) {
5168       SourceVecs.push_back(SourceVec);
5169       MinElts.push_back(EltNo);
5170       MaxElts.push_back(EltNo);
5171     }
5172   }
5173
5174   // Currently only do something sane when at most two source vectors
5175   // involved.
5176   if (SourceVecs.size() > 2)
5177     return SDValue();
5178
5179   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5180   int VEXTOffsets[2] = {0, 0};
5181
5182   // This loop extracts the usage patterns of the source vectors
5183   // and prepares appropriate SDValues for a shuffle if possible.
5184   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5185     if (SourceVecs[i].getValueType() == VT) {
5186       // No VEXT necessary
5187       ShuffleSrcs[i] = SourceVecs[i];
5188       VEXTOffsets[i] = 0;
5189       continue;
5190     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5191       // It probably isn't worth padding out a smaller vector just to
5192       // break it down again in a shuffle.
5193       return SDValue();
5194     }
5195
5196     // Since only 64-bit and 128-bit vectors are legal on ARM and
5197     // we've eliminated the other cases...
5198     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5199            "unexpected vector sizes in ReconstructShuffle");
5200
5201     if (MaxElts[i] - MinElts[i] >= NumElts) {
5202       // Span too large for a VEXT to cope
5203       return SDValue();
5204     }
5205
5206     if (MinElts[i] >= NumElts) {
5207       // The extraction can just take the second half
5208       VEXTOffsets[i] = NumElts;
5209       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5210                                    SourceVecs[i],
5211                                    DAG.getIntPtrConstant(NumElts));
5212     } else if (MaxElts[i] < NumElts) {
5213       // The extraction can just take the first half
5214       VEXTOffsets[i] = 0;
5215       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5216                                    SourceVecs[i],
5217                                    DAG.getIntPtrConstant(0));
5218     } else {
5219       // An actual VEXT is needed
5220       VEXTOffsets[i] = MinElts[i];
5221       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5222                                      SourceVecs[i],
5223                                      DAG.getIntPtrConstant(0));
5224       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5225                                      SourceVecs[i],
5226                                      DAG.getIntPtrConstant(NumElts));
5227       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5228                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
5229     }
5230   }
5231
5232   SmallVector<int, 8> Mask;
5233
5234   for (unsigned i = 0; i < NumElts; ++i) {
5235     SDValue Entry = Op.getOperand(i);
5236     if (Entry.getOpcode() == ISD::UNDEF) {
5237       Mask.push_back(-1);
5238       continue;
5239     }
5240
5241     SDValue ExtractVec = Entry.getOperand(0);
5242     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5243                                           .getOperand(1))->getSExtValue();
5244     if (ExtractVec == SourceVecs[0]) {
5245       Mask.push_back(ExtractElt - VEXTOffsets[0]);
5246     } else {
5247       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5248     }
5249   }
5250
5251   // Final check before we try to produce nonsense...
5252   if (isShuffleMaskLegal(Mask, VT))
5253     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5254                                 &Mask[0]);
5255
5256   return SDValue();
5257 }
5258
5259 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5260 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5261 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5262 /// are assumed to be legal.
5263 bool
5264 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5265                                       EVT VT) const {
5266   if (VT.getVectorNumElements() == 4 &&
5267       (VT.is128BitVector() || VT.is64BitVector())) {
5268     unsigned PFIndexes[4];
5269     for (unsigned i = 0; i != 4; ++i) {
5270       if (M[i] < 0)
5271         PFIndexes[i] = 8;
5272       else
5273         PFIndexes[i] = M[i];
5274     }
5275
5276     // Compute the index in the perfect shuffle table.
5277     unsigned PFTableIndex =
5278       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5279     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5280     unsigned Cost = (PFEntry >> 30);
5281
5282     if (Cost <= 4)
5283       return true;
5284   }
5285
5286   bool ReverseVEXT;
5287   unsigned Imm, WhichResult;
5288
5289   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5290   return (EltSize >= 32 ||
5291           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5292           isVREVMask(M, VT, 64) ||
5293           isVREVMask(M, VT, 32) ||
5294           isVREVMask(M, VT, 16) ||
5295           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5296           isVTBLMask(M, VT) ||
5297           isVTRNMask(M, VT, WhichResult) ||
5298           isVUZPMask(M, VT, WhichResult) ||
5299           isVZIPMask(M, VT, WhichResult) ||
5300           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5301           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5302           isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5303           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5304 }
5305
5306 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5307 /// the specified operations to build the shuffle.
5308 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5309                                       SDValue RHS, SelectionDAG &DAG,
5310                                       SDLoc dl) {
5311   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5312   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5313   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5314
5315   enum {
5316     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5317     OP_VREV,
5318     OP_VDUP0,
5319     OP_VDUP1,
5320     OP_VDUP2,
5321     OP_VDUP3,
5322     OP_VEXT1,
5323     OP_VEXT2,
5324     OP_VEXT3,
5325     OP_VUZPL, // VUZP, left result
5326     OP_VUZPR, // VUZP, right result
5327     OP_VZIPL, // VZIP, left result
5328     OP_VZIPR, // VZIP, right result
5329     OP_VTRNL, // VTRN, left result
5330     OP_VTRNR  // VTRN, right result
5331   };
5332
5333   if (OpNum == OP_COPY) {
5334     if (LHSID == (1*9+2)*9+3) return LHS;
5335     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5336     return RHS;
5337   }
5338
5339   SDValue OpLHS, OpRHS;
5340   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5341   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5342   EVT VT = OpLHS.getValueType();
5343
5344   switch (OpNum) {
5345   default: llvm_unreachable("Unknown shuffle opcode!");
5346   case OP_VREV:
5347     // VREV divides the vector in half and swaps within the half.
5348     if (VT.getVectorElementType() == MVT::i32 ||
5349         VT.getVectorElementType() == MVT::f32)
5350       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5351     // vrev <4 x i16> -> VREV32
5352     if (VT.getVectorElementType() == MVT::i16)
5353       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5354     // vrev <4 x i8> -> VREV16
5355     assert(VT.getVectorElementType() == MVT::i8);
5356     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5357   case OP_VDUP0:
5358   case OP_VDUP1:
5359   case OP_VDUP2:
5360   case OP_VDUP3:
5361     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5362                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5363   case OP_VEXT1:
5364   case OP_VEXT2:
5365   case OP_VEXT3:
5366     return DAG.getNode(ARMISD::VEXT, dl, VT,
5367                        OpLHS, OpRHS,
5368                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5369   case OP_VUZPL:
5370   case OP_VUZPR:
5371     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5372                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5373   case OP_VZIPL:
5374   case OP_VZIPR:
5375     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5376                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5377   case OP_VTRNL:
5378   case OP_VTRNR:
5379     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5380                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5381   }
5382 }
5383
5384 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5385                                        ArrayRef<int> ShuffleMask,
5386                                        SelectionDAG &DAG) {
5387   // Check to see if we can use the VTBL instruction.
5388   SDValue V1 = Op.getOperand(0);
5389   SDValue V2 = Op.getOperand(1);
5390   SDLoc DL(Op);
5391
5392   SmallVector<SDValue, 8> VTBLMask;
5393   for (ArrayRef<int>::iterator
5394          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5395     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5396
5397   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5398     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5399                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5400
5401   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5402                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5403 }
5404
5405 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5406                                                       SelectionDAG &DAG) {
5407   SDLoc DL(Op);
5408   SDValue OpLHS = Op.getOperand(0);
5409   EVT VT = OpLHS.getValueType();
5410
5411   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5412          "Expect an v8i16/v16i8 type");
5413   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5414   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5415   // extract the first 8 bytes into the top double word and the last 8 bytes
5416   // into the bottom double word. The v8i16 case is similar.
5417   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5418   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5419                      DAG.getConstant(ExtractNum, MVT::i32));
5420 }
5421
5422 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5423   SDValue V1 = Op.getOperand(0);
5424   SDValue V2 = Op.getOperand(1);
5425   SDLoc dl(Op);
5426   EVT VT = Op.getValueType();
5427   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5428
5429   // Convert shuffles that are directly supported on NEON to target-specific
5430   // DAG nodes, instead of keeping them as shuffles and matching them again
5431   // during code selection.  This is more efficient and avoids the possibility
5432   // of inconsistencies between legalization and selection.
5433   // FIXME: floating-point vectors should be canonicalized to integer vectors
5434   // of the same time so that they get CSEd properly.
5435   ArrayRef<int> ShuffleMask = SVN->getMask();
5436
5437   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5438   if (EltSize <= 32) {
5439     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5440       int Lane = SVN->getSplatIndex();
5441       // If this is undef splat, generate it via "just" vdup, if possible.
5442       if (Lane == -1) Lane = 0;
5443
5444       // Test if V1 is a SCALAR_TO_VECTOR.
5445       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5446         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5447       }
5448       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5449       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5450       // reaches it).
5451       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5452           !isa<ConstantSDNode>(V1.getOperand(0))) {
5453         bool IsScalarToVector = true;
5454         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5455           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5456             IsScalarToVector = false;
5457             break;
5458           }
5459         if (IsScalarToVector)
5460           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5461       }
5462       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5463                          DAG.getConstant(Lane, MVT::i32));
5464     }
5465
5466     bool ReverseVEXT;
5467     unsigned Imm;
5468     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5469       if (ReverseVEXT)
5470         std::swap(V1, V2);
5471       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5472                          DAG.getConstant(Imm, MVT::i32));
5473     }
5474
5475     if (isVREVMask(ShuffleMask, VT, 64))
5476       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5477     if (isVREVMask(ShuffleMask, VT, 32))
5478       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5479     if (isVREVMask(ShuffleMask, VT, 16))
5480       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5481
5482     if (V2->getOpcode() == ISD::UNDEF &&
5483         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5484       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5485                          DAG.getConstant(Imm, MVT::i32));
5486     }
5487
5488     // Check for Neon shuffles that modify both input vectors in place.
5489     // If both results are used, i.e., if there are two shuffles with the same
5490     // source operands and with masks corresponding to both results of one of
5491     // these operations, DAG memoization will ensure that a single node is
5492     // used for both shuffles.
5493     unsigned WhichResult;
5494     if (isVTRNMask(ShuffleMask, VT, WhichResult))
5495       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5496                          V1, V2).getValue(WhichResult);
5497     if (isVUZPMask(ShuffleMask, VT, WhichResult))
5498       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5499                          V1, V2).getValue(WhichResult);
5500     if (isVZIPMask(ShuffleMask, VT, WhichResult))
5501       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5502                          V1, V2).getValue(WhichResult);
5503
5504     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5505       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5506                          V1, V1).getValue(WhichResult);
5507     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5508       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5509                          V1, V1).getValue(WhichResult);
5510     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5511       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5512                          V1, V1).getValue(WhichResult);
5513   }
5514
5515   // If the shuffle is not directly supported and it has 4 elements, use
5516   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5517   unsigned NumElts = VT.getVectorNumElements();
5518   if (NumElts == 4) {
5519     unsigned PFIndexes[4];
5520     for (unsigned i = 0; i != 4; ++i) {
5521       if (ShuffleMask[i] < 0)
5522         PFIndexes[i] = 8;
5523       else
5524         PFIndexes[i] = ShuffleMask[i];
5525     }
5526
5527     // Compute the index in the perfect shuffle table.
5528     unsigned PFTableIndex =
5529       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5530     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5531     unsigned Cost = (PFEntry >> 30);
5532
5533     if (Cost <= 4)
5534       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5535   }
5536
5537   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5538   if (EltSize >= 32) {
5539     // Do the expansion with floating-point types, since that is what the VFP
5540     // registers are defined to use, and since i64 is not legal.
5541     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5542     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5543     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5544     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5545     SmallVector<SDValue, 8> Ops;
5546     for (unsigned i = 0; i < NumElts; ++i) {
5547       if (ShuffleMask[i] < 0)
5548         Ops.push_back(DAG.getUNDEF(EltVT));
5549       else
5550         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5551                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
5552                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5553                                                   MVT::i32)));
5554     }
5555     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5556     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5557   }
5558
5559   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5560     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5561
5562   if (VT == MVT::v8i8) {
5563     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5564     if (NewOp.getNode())
5565       return NewOp;
5566   }
5567
5568   return SDValue();
5569 }
5570
5571 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5572   // INSERT_VECTOR_ELT is legal only for immediate indexes.
5573   SDValue Lane = Op.getOperand(2);
5574   if (!isa<ConstantSDNode>(Lane))
5575     return SDValue();
5576
5577   return Op;
5578 }
5579
5580 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5581   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5582   SDValue Lane = Op.getOperand(1);
5583   if (!isa<ConstantSDNode>(Lane))
5584     return SDValue();
5585
5586   SDValue Vec = Op.getOperand(0);
5587   if (Op.getValueType() == MVT::i32 &&
5588       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5589     SDLoc dl(Op);
5590     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5591   }
5592
5593   return Op;
5594 }
5595
5596 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5597   // The only time a CONCAT_VECTORS operation can have legal types is when
5598   // two 64-bit vectors are concatenated to a 128-bit vector.
5599   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5600          "unexpected CONCAT_VECTORS");
5601   SDLoc dl(Op);
5602   SDValue Val = DAG.getUNDEF(MVT::v2f64);
5603   SDValue Op0 = Op.getOperand(0);
5604   SDValue Op1 = Op.getOperand(1);
5605   if (Op0.getOpcode() != ISD::UNDEF)
5606     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5607                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5608                       DAG.getIntPtrConstant(0));
5609   if (Op1.getOpcode() != ISD::UNDEF)
5610     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5611                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5612                       DAG.getIntPtrConstant(1));
5613   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5614 }
5615
5616 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5617 /// element has been zero/sign-extended, depending on the isSigned parameter,
5618 /// from an integer type half its size.
5619 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5620                                    bool isSigned) {
5621   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5622   EVT VT = N->getValueType(0);
5623   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5624     SDNode *BVN = N->getOperand(0).getNode();
5625     if (BVN->getValueType(0) != MVT::v4i32 ||
5626         BVN->getOpcode() != ISD::BUILD_VECTOR)
5627       return false;
5628     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5629     unsigned HiElt = 1 - LoElt;
5630     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5631     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5632     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5633     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5634     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5635       return false;
5636     if (isSigned) {
5637       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5638           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5639         return true;
5640     } else {
5641       if (Hi0->isNullValue() && Hi1->isNullValue())
5642         return true;
5643     }
5644     return false;
5645   }
5646
5647   if (N->getOpcode() != ISD::BUILD_VECTOR)
5648     return false;
5649
5650   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5651     SDNode *Elt = N->getOperand(i).getNode();
5652     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5653       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5654       unsigned HalfSize = EltSize / 2;
5655       if (isSigned) {
5656         if (!isIntN(HalfSize, C->getSExtValue()))
5657           return false;
5658       } else {
5659         if (!isUIntN(HalfSize, C->getZExtValue()))
5660           return false;
5661       }
5662       continue;
5663     }
5664     return false;
5665   }
5666
5667   return true;
5668 }
5669
5670 /// isSignExtended - Check if a node is a vector value that is sign-extended
5671 /// or a constant BUILD_VECTOR with sign-extended elements.
5672 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5673   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5674     return true;
5675   if (isExtendedBUILD_VECTOR(N, DAG, true))
5676     return true;
5677   return false;
5678 }
5679
5680 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5681 /// or a constant BUILD_VECTOR with zero-extended elements.
5682 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5683   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5684     return true;
5685   if (isExtendedBUILD_VECTOR(N, DAG, false))
5686     return true;
5687   return false;
5688 }
5689
5690 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5691   if (OrigVT.getSizeInBits() >= 64)
5692     return OrigVT;
5693
5694   assert(OrigVT.isSimple() && "Expecting a simple value type");
5695
5696   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5697   switch (OrigSimpleTy) {
5698   default: llvm_unreachable("Unexpected Vector Type");
5699   case MVT::v2i8:
5700   case MVT::v2i16:
5701      return MVT::v2i32;
5702   case MVT::v4i8:
5703     return  MVT::v4i16;
5704   }
5705 }
5706
5707 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5708 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5709 /// We insert the required extension here to get the vector to fill a D register.
5710 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5711                                             const EVT &OrigTy,
5712                                             const EVT &ExtTy,
5713                                             unsigned ExtOpcode) {
5714   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5715   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5716   // 64-bits we need to insert a new extension so that it will be 64-bits.
5717   assert(ExtTy.is128BitVector() && "Unexpected extension size");
5718   if (OrigTy.getSizeInBits() >= 64)
5719     return N;
5720
5721   // Must extend size to at least 64 bits to be used as an operand for VMULL.
5722   EVT NewVT = getExtensionTo64Bits(OrigTy);
5723
5724   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5725 }
5726
5727 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5728 /// does not do any sign/zero extension. If the original vector is less
5729 /// than 64 bits, an appropriate extension will be added after the load to
5730 /// reach a total size of 64 bits. We have to add the extension separately
5731 /// because ARM does not have a sign/zero extending load for vectors.
5732 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5733   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5734
5735   // The load already has the right type.
5736   if (ExtendedTy == LD->getMemoryVT())
5737     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5738                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5739                 LD->isNonTemporal(), LD->isInvariant(),
5740                 LD->getAlignment());
5741
5742   // We need to create a zextload/sextload. We cannot just create a load
5743   // followed by a zext/zext node because LowerMUL is also run during normal
5744   // operation legalization where we can't create illegal types.
5745   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5746                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5747                         LD->getMemoryVT(), LD->isVolatile(),
5748                         LD->isNonTemporal(), LD->getAlignment());
5749 }
5750
5751 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5752 /// extending load, or BUILD_VECTOR with extended elements, return the
5753 /// unextended value. The unextended vector should be 64 bits so that it can
5754 /// be used as an operand to a VMULL instruction. If the original vector size
5755 /// before extension is less than 64 bits we add a an extension to resize
5756 /// the vector to 64 bits.
5757 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5758   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5759     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5760                                         N->getOperand(0)->getValueType(0),
5761                                         N->getValueType(0),
5762                                         N->getOpcode());
5763
5764   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5765     return SkipLoadExtensionForVMULL(LD, DAG);
5766
5767   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
5768   // have been legalized as a BITCAST from v4i32.
5769   if (N->getOpcode() == ISD::BITCAST) {
5770     SDNode *BVN = N->getOperand(0).getNode();
5771     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5772            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5773     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5774     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5775                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5776   }
5777   // Construct a new BUILD_VECTOR with elements truncated to half the size.
5778   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5779   EVT VT = N->getValueType(0);
5780   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5781   unsigned NumElts = VT.getVectorNumElements();
5782   MVT TruncVT = MVT::getIntegerVT(EltSize);
5783   SmallVector<SDValue, 8> Ops;
5784   for (unsigned i = 0; i != NumElts; ++i) {
5785     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5786     const APInt &CInt = C->getAPIntValue();
5787     // Element types smaller than 32 bits are not legal, so use i32 elements.
5788     // The values are implicitly truncated so sext vs. zext doesn't matter.
5789     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5790   }
5791   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5792                      MVT::getVectorVT(TruncVT, NumElts), Ops);
5793 }
5794
5795 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5796   unsigned Opcode = N->getOpcode();
5797   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5798     SDNode *N0 = N->getOperand(0).getNode();
5799     SDNode *N1 = N->getOperand(1).getNode();
5800     return N0->hasOneUse() && N1->hasOneUse() &&
5801       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5802   }
5803   return false;
5804 }
5805
5806 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5807   unsigned Opcode = N->getOpcode();
5808   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5809     SDNode *N0 = N->getOperand(0).getNode();
5810     SDNode *N1 = N->getOperand(1).getNode();
5811     return N0->hasOneUse() && N1->hasOneUse() &&
5812       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5813   }
5814   return false;
5815 }
5816
5817 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5818   // Multiplications are only custom-lowered for 128-bit vectors so that
5819   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
5820   EVT VT = Op.getValueType();
5821   assert(VT.is128BitVector() && VT.isInteger() &&
5822          "unexpected type for custom-lowering ISD::MUL");
5823   SDNode *N0 = Op.getOperand(0).getNode();
5824   SDNode *N1 = Op.getOperand(1).getNode();
5825   unsigned NewOpc = 0;
5826   bool isMLA = false;
5827   bool isN0SExt = isSignExtended(N0, DAG);
5828   bool isN1SExt = isSignExtended(N1, DAG);
5829   if (isN0SExt && isN1SExt)
5830     NewOpc = ARMISD::VMULLs;
5831   else {
5832     bool isN0ZExt = isZeroExtended(N0, DAG);
5833     bool isN1ZExt = isZeroExtended(N1, DAG);
5834     if (isN0ZExt && isN1ZExt)
5835       NewOpc = ARMISD::VMULLu;
5836     else if (isN1SExt || isN1ZExt) {
5837       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5838       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5839       if (isN1SExt && isAddSubSExt(N0, DAG)) {
5840         NewOpc = ARMISD::VMULLs;
5841         isMLA = true;
5842       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5843         NewOpc = ARMISD::VMULLu;
5844         isMLA = true;
5845       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5846         std::swap(N0, N1);
5847         NewOpc = ARMISD::VMULLu;
5848         isMLA = true;
5849       }
5850     }
5851
5852     if (!NewOpc) {
5853       if (VT == MVT::v2i64)
5854         // Fall through to expand this.  It is not legal.
5855         return SDValue();
5856       else
5857         // Other vector multiplications are legal.
5858         return Op;
5859     }
5860   }
5861
5862   // Legalize to a VMULL instruction.
5863   SDLoc DL(Op);
5864   SDValue Op0;
5865   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5866   if (!isMLA) {
5867     Op0 = SkipExtensionForVMULL(N0, DAG);
5868     assert(Op0.getValueType().is64BitVector() &&
5869            Op1.getValueType().is64BitVector() &&
5870            "unexpected types for extended operands to VMULL");
5871     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5872   }
5873
5874   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5875   // isel lowering to take advantage of no-stall back to back vmul + vmla.
5876   //   vmull q0, d4, d6
5877   //   vmlal q0, d5, d6
5878   // is faster than
5879   //   vaddl q0, d4, d5
5880   //   vmovl q1, d6
5881   //   vmul  q0, q0, q1
5882   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5883   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5884   EVT Op1VT = Op1.getValueType();
5885   return DAG.getNode(N0->getOpcode(), DL, VT,
5886                      DAG.getNode(NewOpc, DL, VT,
5887                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5888                      DAG.getNode(NewOpc, DL, VT,
5889                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5890 }
5891
5892 static SDValue
5893 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
5894   // Convert to float
5895   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5896   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5897   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5898   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5899   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5900   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5901   // Get reciprocal estimate.
5902   // float4 recip = vrecpeq_f32(yf);
5903   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5904                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5905   // Because char has a smaller range than uchar, we can actually get away
5906   // without any newton steps.  This requires that we use a weird bias
5907   // of 0xb000, however (again, this has been exhaustively tested).
5908   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5909   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5910   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5911   Y = DAG.getConstant(0xb000, MVT::i32);
5912   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5913   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5914   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5915   // Convert back to short.
5916   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5917   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5918   return X;
5919 }
5920
5921 static SDValue
5922 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
5923   SDValue N2;
5924   // Convert to float.
5925   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5926   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5927   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5928   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5929   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5930   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5931
5932   // Use reciprocal estimate and one refinement step.
5933   // float4 recip = vrecpeq_f32(yf);
5934   // recip *= vrecpsq_f32(yf, recip);
5935   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5936                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5937   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5938                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5939                    N1, N2);
5940   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5941   // Because short has a smaller range than ushort, we can actually get away
5942   // with only a single newton step.  This requires that we use a weird bias
5943   // of 89, however (again, this has been exhaustively tested).
5944   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5945   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5946   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5947   N1 = DAG.getConstant(0x89, MVT::i32);
5948   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5949   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5950   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5951   // Convert back to integer and return.
5952   // return vmovn_s32(vcvt_s32_f32(result));
5953   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5954   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5955   return N0;
5956 }
5957
5958 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5959   EVT VT = Op.getValueType();
5960   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5961          "unexpected type for custom-lowering ISD::SDIV");
5962
5963   SDLoc dl(Op);
5964   SDValue N0 = Op.getOperand(0);
5965   SDValue N1 = Op.getOperand(1);
5966   SDValue N2, N3;
5967
5968   if (VT == MVT::v8i8) {
5969     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5970     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5971
5972     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5973                      DAG.getIntPtrConstant(4));
5974     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5975                      DAG.getIntPtrConstant(4));
5976     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5977                      DAG.getIntPtrConstant(0));
5978     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5979                      DAG.getIntPtrConstant(0));
5980
5981     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5982     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5983
5984     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5985     N0 = LowerCONCAT_VECTORS(N0, DAG);
5986
5987     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5988     return N0;
5989   }
5990   return LowerSDIV_v4i16(N0, N1, dl, DAG);
5991 }
5992
5993 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5994   EVT VT = Op.getValueType();
5995   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5996          "unexpected type for custom-lowering ISD::UDIV");
5997
5998   SDLoc dl(Op);
5999   SDValue N0 = Op.getOperand(0);
6000   SDValue N1 = Op.getOperand(1);
6001   SDValue N2, N3;
6002
6003   if (VT == MVT::v8i8) {
6004     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6005     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6006
6007     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6008                      DAG.getIntPtrConstant(4));
6009     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6010                      DAG.getIntPtrConstant(4));
6011     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6012                      DAG.getIntPtrConstant(0));
6013     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6014                      DAG.getIntPtrConstant(0));
6015
6016     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6017     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6018
6019     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6020     N0 = LowerCONCAT_VECTORS(N0, DAG);
6021
6022     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6023                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
6024                      N0);
6025     return N0;
6026   }
6027
6028   // v4i16 sdiv ... Convert to float.
6029   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6030   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6031   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6032   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6033   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6034   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6035
6036   // Use reciprocal estimate and two refinement steps.
6037   // float4 recip = vrecpeq_f32(yf);
6038   // recip *= vrecpsq_f32(yf, recip);
6039   // recip *= vrecpsq_f32(yf, recip);
6040   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6041                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
6042   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6043                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6044                    BN1, N2);
6045   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6046   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6047                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6048                    BN1, N2);
6049   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6050   // Simply multiplying by the reciprocal estimate can leave us a few ulps
6051   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6052   // and that it will never cause us to return an answer too large).
6053   // float4 result = as_float4(as_int4(xf*recip) + 2);
6054   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6055   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6056   N1 = DAG.getConstant(2, MVT::i32);
6057   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6058   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6059   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6060   // Convert back to integer and return.
6061   // return vmovn_u32(vcvt_s32_f32(result));
6062   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6063   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6064   return N0;
6065 }
6066
6067 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6068   EVT VT = Op.getNode()->getValueType(0);
6069   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6070
6071   unsigned Opc;
6072   bool ExtraOp = false;
6073   switch (Op.getOpcode()) {
6074   default: llvm_unreachable("Invalid code");
6075   case ISD::ADDC: Opc = ARMISD::ADDC; break;
6076   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6077   case ISD::SUBC: Opc = ARMISD::SUBC; break;
6078   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6079   }
6080
6081   if (!ExtraOp)
6082     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6083                        Op.getOperand(1));
6084   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6085                      Op.getOperand(1), Op.getOperand(2));
6086 }
6087
6088 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6089   assert(Subtarget->isTargetDarwin());
6090
6091   // For iOS, we want to call an alternative entry point: __sincos_stret,
6092   // return values are passed via sret.
6093   SDLoc dl(Op);
6094   SDValue Arg = Op.getOperand(0);
6095   EVT ArgVT = Arg.getValueType();
6096   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6097
6098   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6099   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6100
6101   // Pair of floats / doubles used to pass the result.
6102   StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL);
6103
6104   // Create stack object for sret.
6105   const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
6106   const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
6107   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6108   SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
6109
6110   ArgListTy Args;
6111   ArgListEntry Entry;
6112
6113   Entry.Node = SRet;
6114   Entry.Ty = RetTy->getPointerTo();
6115   Entry.isSExt = false;
6116   Entry.isZExt = false;
6117   Entry.isSRet = true;
6118   Args.push_back(Entry);
6119
6120   Entry.Node = Arg;
6121   Entry.Ty = ArgTy;
6122   Entry.isSExt = false;
6123   Entry.isZExt = false;
6124   Args.push_back(Entry);
6125
6126   const char *LibcallName  = (ArgVT == MVT::f64)
6127   ? "__sincos_stret" : "__sincosf_stret";
6128   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
6129
6130   TargetLowering::CallLoweringInfo CLI(DAG);
6131   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6132     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6133                std::move(Args), 0)
6134     .setDiscardResult();
6135
6136   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6137
6138   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6139                                 MachinePointerInfo(), false, false, false, 0);
6140
6141   // Address of cos field.
6142   SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
6143                             DAG.getIntPtrConstant(ArgVT.getStoreSize()));
6144   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6145                                 MachinePointerInfo(), false, false, false, 0);
6146
6147   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6148   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6149                      LoadSin.getValue(0), LoadCos.getValue(0));
6150 }
6151
6152 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6153   // Monotonic load/store is legal for all targets
6154   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6155     return Op;
6156
6157   // Acquire/Release load/store is not legal for targets without a
6158   // dmb or equivalent available.
6159   return SDValue();
6160 }
6161
6162 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6163                                     SmallVectorImpl<SDValue> &Results,
6164                                     SelectionDAG &DAG,
6165                                     const ARMSubtarget *Subtarget) {
6166   SDLoc DL(N);
6167   SDValue Cycles32, OutChain;
6168
6169   if (Subtarget->hasPerfMon()) {
6170     // Under Power Management extensions, the cycle-count is:
6171     //    mrc p15, #0, <Rt>, c9, c13, #0
6172     SDValue Ops[] = { N->getOperand(0), // Chain
6173                       DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
6174                       DAG.getConstant(15, MVT::i32),
6175                       DAG.getConstant(0, MVT::i32),
6176                       DAG.getConstant(9, MVT::i32),
6177                       DAG.getConstant(13, MVT::i32),
6178                       DAG.getConstant(0, MVT::i32)
6179     };
6180
6181     Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6182                            DAG.getVTList(MVT::i32, MVT::Other), Ops);
6183     OutChain = Cycles32.getValue(1);
6184   } else {
6185     // Intrinsic is defined to return 0 on unsupported platforms. Technically
6186     // there are older ARM CPUs that have implementation-specific ways of
6187     // obtaining this information (FIXME!).
6188     Cycles32 = DAG.getConstant(0, MVT::i32);
6189     OutChain = DAG.getEntryNode();
6190   }
6191
6192
6193   SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6194                                  Cycles32, DAG.getConstant(0, MVT::i32));
6195   Results.push_back(Cycles64);
6196   Results.push_back(OutChain);
6197 }
6198
6199 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6200   switch (Op.getOpcode()) {
6201   default: llvm_unreachable("Don't know how to custom lower this!");
6202   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6203   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6204   case ISD::GlobalAddress:
6205     switch (Subtarget->getTargetTriple().getObjectFormat()) {
6206     default: llvm_unreachable("unknown object format");
6207     case Triple::COFF:
6208       return LowerGlobalAddressWindows(Op, DAG);
6209     case Triple::ELF:
6210       return LowerGlobalAddressELF(Op, DAG);
6211     case Triple::MachO:
6212       return LowerGlobalAddressDarwin(Op, DAG);
6213     }
6214   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6215   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6216   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6217   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6218   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6219   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6220   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6221   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6222   case ISD::SINT_TO_FP:
6223   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6224   case ISD::FP_TO_SINT:
6225   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6226   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6227   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6228   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6229   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6230   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6231   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6232   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6233                                                                Subtarget);
6234   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6235   case ISD::SHL:
6236   case ISD::SRL:
6237   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6238   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6239   case ISD::SRL_PARTS:
6240   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6241   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6242   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6243   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6244   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6245   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6246   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6247   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6248   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6249   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6250   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6251   case ISD::MUL:           return LowerMUL(Op, DAG);
6252   case ISD::SDIV:          return LowerSDIV(Op, DAG);
6253   case ISD::UDIV:          return LowerUDIV(Op, DAG);
6254   case ISD::ADDC:
6255   case ISD::ADDE:
6256   case ISD::SUBC:
6257   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6258   case ISD::SADDO:
6259   case ISD::UADDO:
6260   case ISD::SSUBO:
6261   case ISD::USUBO:
6262     return LowerXALUO(Op, DAG);
6263   case ISD::ATOMIC_LOAD:
6264   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6265   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6266   case ISD::SDIVREM:
6267   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6268   case ISD::DYNAMIC_STACKALLOC:
6269     if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6270       return LowerDYNAMIC_STACKALLOC(Op, DAG);
6271     llvm_unreachable("Don't know how to custom lower this!");
6272   }
6273 }
6274
6275 /// ReplaceNodeResults - Replace the results of node with an illegal result
6276 /// type with new values built out of custom code.
6277 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6278                                            SmallVectorImpl<SDValue>&Results,
6279                                            SelectionDAG &DAG) const {
6280   SDValue Res;
6281   switch (N->getOpcode()) {
6282   default:
6283     llvm_unreachable("Don't know how to custom expand this!");
6284   case ISD::BITCAST:
6285     Res = ExpandBITCAST(N, DAG);
6286     break;
6287   case ISD::SRL:
6288   case ISD::SRA:
6289     Res = Expand64BitShift(N, DAG, Subtarget);
6290     break;
6291   case ISD::READCYCLECOUNTER:
6292     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6293     return;
6294   }
6295   if (Res.getNode())
6296     Results.push_back(Res);
6297 }
6298
6299 //===----------------------------------------------------------------------===//
6300 //                           ARM Scheduler Hooks
6301 //===----------------------------------------------------------------------===//
6302
6303 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6304 /// registers the function context.
6305 void ARMTargetLowering::
6306 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6307                        MachineBasicBlock *DispatchBB, int FI) const {
6308   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6309   DebugLoc dl = MI->getDebugLoc();
6310   MachineFunction *MF = MBB->getParent();
6311   MachineRegisterInfo *MRI = &MF->getRegInfo();
6312   MachineConstantPool *MCP = MF->getConstantPool();
6313   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6314   const Function *F = MF->getFunction();
6315
6316   bool isThumb = Subtarget->isThumb();
6317   bool isThumb2 = Subtarget->isThumb2();
6318
6319   unsigned PCLabelId = AFI->createPICLabelUId();
6320   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6321   ARMConstantPoolValue *CPV =
6322     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6323   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6324
6325   const TargetRegisterClass *TRC = isThumb ?
6326     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6327     (const TargetRegisterClass*)&ARM::GPRRegClass;
6328
6329   // Grab constant pool and fixed stack memory operands.
6330   MachineMemOperand *CPMMO =
6331     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6332                              MachineMemOperand::MOLoad, 4, 4);
6333
6334   MachineMemOperand *FIMMOSt =
6335     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6336                              MachineMemOperand::MOStore, 4, 4);
6337
6338   // Load the address of the dispatch MBB into the jump buffer.
6339   if (isThumb2) {
6340     // Incoming value: jbuf
6341     //   ldr.n  r5, LCPI1_1
6342     //   orr    r5, r5, #1
6343     //   add    r5, pc
6344     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6345     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6346     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6347                    .addConstantPoolIndex(CPI)
6348                    .addMemOperand(CPMMO));
6349     // Set the low bit because of thumb mode.
6350     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6351     AddDefaultCC(
6352       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6353                      .addReg(NewVReg1, RegState::Kill)
6354                      .addImm(0x01)));
6355     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6356     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6357       .addReg(NewVReg2, RegState::Kill)
6358       .addImm(PCLabelId);
6359     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6360                    .addReg(NewVReg3, RegState::Kill)
6361                    .addFrameIndex(FI)
6362                    .addImm(36)  // &jbuf[1] :: pc
6363                    .addMemOperand(FIMMOSt));
6364   } else if (isThumb) {
6365     // Incoming value: jbuf
6366     //   ldr.n  r1, LCPI1_4
6367     //   add    r1, pc
6368     //   mov    r2, #1
6369     //   orrs   r1, r2
6370     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6371     //   str    r1, [r2]
6372     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6373     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6374                    .addConstantPoolIndex(CPI)
6375                    .addMemOperand(CPMMO));
6376     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6377     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6378       .addReg(NewVReg1, RegState::Kill)
6379       .addImm(PCLabelId);
6380     // Set the low bit because of thumb mode.
6381     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6382     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6383                    .addReg(ARM::CPSR, RegState::Define)
6384                    .addImm(1));
6385     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6386     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6387                    .addReg(ARM::CPSR, RegState::Define)
6388                    .addReg(NewVReg2, RegState::Kill)
6389                    .addReg(NewVReg3, RegState::Kill));
6390     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6391     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6392                    .addFrameIndex(FI)
6393                    .addImm(36)); // &jbuf[1] :: pc
6394     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6395                    .addReg(NewVReg4, RegState::Kill)
6396                    .addReg(NewVReg5, RegState::Kill)
6397                    .addImm(0)
6398                    .addMemOperand(FIMMOSt));
6399   } else {
6400     // Incoming value: jbuf
6401     //   ldr  r1, LCPI1_1
6402     //   add  r1, pc, r1
6403     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6404     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6405     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6406                    .addConstantPoolIndex(CPI)
6407                    .addImm(0)
6408                    .addMemOperand(CPMMO));
6409     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6410     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6411                    .addReg(NewVReg1, RegState::Kill)
6412                    .addImm(PCLabelId));
6413     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6414                    .addReg(NewVReg2, RegState::Kill)
6415                    .addFrameIndex(FI)
6416                    .addImm(36)  // &jbuf[1] :: pc
6417                    .addMemOperand(FIMMOSt));
6418   }
6419 }
6420
6421 MachineBasicBlock *ARMTargetLowering::
6422 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6423   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6424   DebugLoc dl = MI->getDebugLoc();
6425   MachineFunction *MF = MBB->getParent();
6426   MachineRegisterInfo *MRI = &MF->getRegInfo();
6427   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6428   MachineFrameInfo *MFI = MF->getFrameInfo();
6429   int FI = MFI->getFunctionContextIndex();
6430
6431   const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6432     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6433     (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6434
6435   // Get a mapping of the call site numbers to all of the landing pads they're
6436   // associated with.
6437   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6438   unsigned MaxCSNum = 0;
6439   MachineModuleInfo &MMI = MF->getMMI();
6440   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6441        ++BB) {
6442     if (!BB->isLandingPad()) continue;
6443
6444     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6445     // pad.
6446     for (MachineBasicBlock::iterator
6447            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6448       if (!II->isEHLabel()) continue;
6449
6450       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6451       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6452
6453       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6454       for (SmallVectorImpl<unsigned>::iterator
6455              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6456            CSI != CSE; ++CSI) {
6457         CallSiteNumToLPad[*CSI].push_back(BB);
6458         MaxCSNum = std::max(MaxCSNum, *CSI);
6459       }
6460       break;
6461     }
6462   }
6463
6464   // Get an ordered list of the machine basic blocks for the jump table.
6465   std::vector<MachineBasicBlock*> LPadList;
6466   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6467   LPadList.reserve(CallSiteNumToLPad.size());
6468   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6469     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6470     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6471            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6472       LPadList.push_back(*II);
6473       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6474     }
6475   }
6476
6477   assert(!LPadList.empty() &&
6478          "No landing pad destinations for the dispatch jump table!");
6479
6480   // Create the jump table and associated information.
6481   MachineJumpTableInfo *JTI =
6482     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6483   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6484   unsigned UId = AFI->createJumpTableUId();
6485   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6486
6487   // Create the MBBs for the dispatch code.
6488
6489   // Shove the dispatch's address into the return slot in the function context.
6490   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6491   DispatchBB->setIsLandingPad();
6492
6493   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6494   unsigned trap_opcode;
6495   if (Subtarget->isThumb())
6496     trap_opcode = ARM::tTRAP;
6497   else
6498     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6499
6500   BuildMI(TrapBB, dl, TII->get(trap_opcode));
6501   DispatchBB->addSuccessor(TrapBB);
6502
6503   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6504   DispatchBB->addSuccessor(DispContBB);
6505
6506   // Insert and MBBs.
6507   MF->insert(MF->end(), DispatchBB);
6508   MF->insert(MF->end(), DispContBB);
6509   MF->insert(MF->end(), TrapBB);
6510
6511   // Insert code into the entry block that creates and registers the function
6512   // context.
6513   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6514
6515   MachineMemOperand *FIMMOLd =
6516     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6517                              MachineMemOperand::MOLoad |
6518                              MachineMemOperand::MOVolatile, 4, 4);
6519
6520   MachineInstrBuilder MIB;
6521   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6522
6523   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6524   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6525
6526   // Add a register mask with no preserved registers.  This results in all
6527   // registers being marked as clobbered.
6528   MIB.addRegMask(RI.getNoPreservedMask());
6529
6530   unsigned NumLPads = LPadList.size();
6531   if (Subtarget->isThumb2()) {
6532     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6533     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6534                    .addFrameIndex(FI)
6535                    .addImm(4)
6536                    .addMemOperand(FIMMOLd));
6537
6538     if (NumLPads < 256) {
6539       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6540                      .addReg(NewVReg1)
6541                      .addImm(LPadList.size()));
6542     } else {
6543       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6544       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6545                      .addImm(NumLPads & 0xFFFF));
6546
6547       unsigned VReg2 = VReg1;
6548       if ((NumLPads & 0xFFFF0000) != 0) {
6549         VReg2 = MRI->createVirtualRegister(TRC);
6550         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6551                        .addReg(VReg1)
6552                        .addImm(NumLPads >> 16));
6553       }
6554
6555       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6556                      .addReg(NewVReg1)
6557                      .addReg(VReg2));
6558     }
6559
6560     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6561       .addMBB(TrapBB)
6562       .addImm(ARMCC::HI)
6563       .addReg(ARM::CPSR);
6564
6565     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6566     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6567                    .addJumpTableIndex(MJTI)
6568                    .addImm(UId));
6569
6570     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6571     AddDefaultCC(
6572       AddDefaultPred(
6573         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6574         .addReg(NewVReg3, RegState::Kill)
6575         .addReg(NewVReg1)
6576         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6577
6578     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6579       .addReg(NewVReg4, RegState::Kill)
6580       .addReg(NewVReg1)
6581       .addJumpTableIndex(MJTI)
6582       .addImm(UId);
6583   } else if (Subtarget->isThumb()) {
6584     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6585     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6586                    .addFrameIndex(FI)
6587                    .addImm(1)
6588                    .addMemOperand(FIMMOLd));
6589
6590     if (NumLPads < 256) {
6591       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6592                      .addReg(NewVReg1)
6593                      .addImm(NumLPads));
6594     } else {
6595       MachineConstantPool *ConstantPool = MF->getConstantPool();
6596       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6597       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6598
6599       // MachineConstantPool wants an explicit alignment.
6600       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6601       if (Align == 0)
6602         Align = getDataLayout()->getTypeAllocSize(C->getType());
6603       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6604
6605       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6606       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6607                      .addReg(VReg1, RegState::Define)
6608                      .addConstantPoolIndex(Idx));
6609       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6610                      .addReg(NewVReg1)
6611                      .addReg(VReg1));
6612     }
6613
6614     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6615       .addMBB(TrapBB)
6616       .addImm(ARMCC::HI)
6617       .addReg(ARM::CPSR);
6618
6619     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6620     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6621                    .addReg(ARM::CPSR, RegState::Define)
6622                    .addReg(NewVReg1)
6623                    .addImm(2));
6624
6625     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6626     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6627                    .addJumpTableIndex(MJTI)
6628                    .addImm(UId));
6629
6630     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6631     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6632                    .addReg(ARM::CPSR, RegState::Define)
6633                    .addReg(NewVReg2, RegState::Kill)
6634                    .addReg(NewVReg3));
6635
6636     MachineMemOperand *JTMMOLd =
6637       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6638                                MachineMemOperand::MOLoad, 4, 4);
6639
6640     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6641     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6642                    .addReg(NewVReg4, RegState::Kill)
6643                    .addImm(0)
6644                    .addMemOperand(JTMMOLd));
6645
6646     unsigned NewVReg6 = NewVReg5;
6647     if (RelocM == Reloc::PIC_) {
6648       NewVReg6 = MRI->createVirtualRegister(TRC);
6649       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6650                      .addReg(ARM::CPSR, RegState::Define)
6651                      .addReg(NewVReg5, RegState::Kill)
6652                      .addReg(NewVReg3));
6653     }
6654
6655     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6656       .addReg(NewVReg6, RegState::Kill)
6657       .addJumpTableIndex(MJTI)
6658       .addImm(UId);
6659   } else {
6660     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6661     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6662                    .addFrameIndex(FI)
6663                    .addImm(4)
6664                    .addMemOperand(FIMMOLd));
6665
6666     if (NumLPads < 256) {
6667       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6668                      .addReg(NewVReg1)
6669                      .addImm(NumLPads));
6670     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6671       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6672       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6673                      .addImm(NumLPads & 0xFFFF));
6674
6675       unsigned VReg2 = VReg1;
6676       if ((NumLPads & 0xFFFF0000) != 0) {
6677         VReg2 = MRI->createVirtualRegister(TRC);
6678         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6679                        .addReg(VReg1)
6680                        .addImm(NumLPads >> 16));
6681       }
6682
6683       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6684                      .addReg(NewVReg1)
6685                      .addReg(VReg2));
6686     } else {
6687       MachineConstantPool *ConstantPool = MF->getConstantPool();
6688       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6689       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6690
6691       // MachineConstantPool wants an explicit alignment.
6692       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6693       if (Align == 0)
6694         Align = getDataLayout()->getTypeAllocSize(C->getType());
6695       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6696
6697       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6698       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6699                      .addReg(VReg1, RegState::Define)
6700                      .addConstantPoolIndex(Idx)
6701                      .addImm(0));
6702       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6703                      .addReg(NewVReg1)
6704                      .addReg(VReg1, RegState::Kill));
6705     }
6706
6707     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6708       .addMBB(TrapBB)
6709       .addImm(ARMCC::HI)
6710       .addReg(ARM::CPSR);
6711
6712     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6713     AddDefaultCC(
6714       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6715                      .addReg(NewVReg1)
6716                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6717     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6718     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6719                    .addJumpTableIndex(MJTI)
6720                    .addImm(UId));
6721
6722     MachineMemOperand *JTMMOLd =
6723       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6724                                MachineMemOperand::MOLoad, 4, 4);
6725     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6726     AddDefaultPred(
6727       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6728       .addReg(NewVReg3, RegState::Kill)
6729       .addReg(NewVReg4)
6730       .addImm(0)
6731       .addMemOperand(JTMMOLd));
6732
6733     if (RelocM == Reloc::PIC_) {
6734       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6735         .addReg(NewVReg5, RegState::Kill)
6736         .addReg(NewVReg4)
6737         .addJumpTableIndex(MJTI)
6738         .addImm(UId);
6739     } else {
6740       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6741         .addReg(NewVReg5, RegState::Kill)
6742         .addJumpTableIndex(MJTI)
6743         .addImm(UId);
6744     }
6745   }
6746
6747   // Add the jump table entries as successors to the MBB.
6748   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6749   for (std::vector<MachineBasicBlock*>::iterator
6750          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6751     MachineBasicBlock *CurMBB = *I;
6752     if (SeenMBBs.insert(CurMBB))
6753       DispContBB->addSuccessor(CurMBB);
6754   }
6755
6756   // N.B. the order the invoke BBs are processed in doesn't matter here.
6757   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
6758   SmallVector<MachineBasicBlock*, 64> MBBLPads;
6759   for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6760          I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6761     MachineBasicBlock *BB = *I;
6762
6763     // Remove the landing pad successor from the invoke block and replace it
6764     // with the new dispatch block.
6765     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6766                                                   BB->succ_end());
6767     while (!Successors.empty()) {
6768       MachineBasicBlock *SMBB = Successors.pop_back_val();
6769       if (SMBB->isLandingPad()) {
6770         BB->removeSuccessor(SMBB);
6771         MBBLPads.push_back(SMBB);
6772       }
6773     }
6774
6775     BB->addSuccessor(DispatchBB);
6776
6777     // Find the invoke call and mark all of the callee-saved registers as
6778     // 'implicit defined' so that they're spilled. This prevents code from
6779     // moving instructions to before the EH block, where they will never be
6780     // executed.
6781     for (MachineBasicBlock::reverse_iterator
6782            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6783       if (!II->isCall()) continue;
6784
6785       DenseMap<unsigned, bool> DefRegs;
6786       for (MachineInstr::mop_iterator
6787              OI = II->operands_begin(), OE = II->operands_end();
6788            OI != OE; ++OI) {
6789         if (!OI->isReg()) continue;
6790         DefRegs[OI->getReg()] = true;
6791       }
6792
6793       MachineInstrBuilder MIB(*MF, &*II);
6794
6795       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6796         unsigned Reg = SavedRegs[i];
6797         if (Subtarget->isThumb2() &&
6798             !ARM::tGPRRegClass.contains(Reg) &&
6799             !ARM::hGPRRegClass.contains(Reg))
6800           continue;
6801         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6802           continue;
6803         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6804           continue;
6805         if (!DefRegs[Reg])
6806           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6807       }
6808
6809       break;
6810     }
6811   }
6812
6813   // Mark all former landing pads as non-landing pads. The dispatch is the only
6814   // landing pad now.
6815   for (SmallVectorImpl<MachineBasicBlock*>::iterator
6816          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6817     (*I)->setIsLandingPad(false);
6818
6819   // The instruction is gone now.
6820   MI->eraseFromParent();
6821
6822   return MBB;
6823 }
6824
6825 static
6826 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6827   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6828        E = MBB->succ_end(); I != E; ++I)
6829     if (*I != Succ)
6830       return *I;
6831   llvm_unreachable("Expecting a BB with two successors!");
6832 }
6833
6834 /// Return the load opcode for a given load size. If load size >= 8,
6835 /// neon opcode will be returned.
6836 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
6837   if (LdSize >= 8)
6838     return LdSize == 16 ? ARM::VLD1q32wb_fixed
6839                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
6840   if (IsThumb1)
6841     return LdSize == 4 ? ARM::tLDRi
6842                        : LdSize == 2 ? ARM::tLDRHi
6843                                      : LdSize == 1 ? ARM::tLDRBi : 0;
6844   if (IsThumb2)
6845     return LdSize == 4 ? ARM::t2LDR_POST
6846                        : LdSize == 2 ? ARM::t2LDRH_POST
6847                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
6848   return LdSize == 4 ? ARM::LDR_POST_IMM
6849                      : LdSize == 2 ? ARM::LDRH_POST
6850                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
6851 }
6852
6853 /// Return the store opcode for a given store size. If store size >= 8,
6854 /// neon opcode will be returned.
6855 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
6856   if (StSize >= 8)
6857     return StSize == 16 ? ARM::VST1q32wb_fixed
6858                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
6859   if (IsThumb1)
6860     return StSize == 4 ? ARM::tSTRi
6861                        : StSize == 2 ? ARM::tSTRHi
6862                                      : StSize == 1 ? ARM::tSTRBi : 0;
6863   if (IsThumb2)
6864     return StSize == 4 ? ARM::t2STR_POST
6865                        : StSize == 2 ? ARM::t2STRH_POST
6866                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
6867   return StSize == 4 ? ARM::STR_POST_IMM
6868                      : StSize == 2 ? ARM::STRH_POST
6869                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
6870 }
6871
6872 /// Emit a post-increment load operation with given size. The instructions
6873 /// will be added to BB at Pos.
6874 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
6875                        const TargetInstrInfo *TII, DebugLoc dl,
6876                        unsigned LdSize, unsigned Data, unsigned AddrIn,
6877                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6878   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
6879   assert(LdOpc != 0 && "Should have a load opcode");
6880   if (LdSize >= 8) {
6881     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6882                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6883                        .addImm(0));
6884   } else if (IsThumb1) {
6885     // load + update AddrIn
6886     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6887                        .addReg(AddrIn).addImm(0));
6888     MachineInstrBuilder MIB =
6889         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6890     MIB = AddDefaultT1CC(MIB);
6891     MIB.addReg(AddrIn).addImm(LdSize);
6892     AddDefaultPred(MIB);
6893   } else if (IsThumb2) {
6894     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6895                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6896                        .addImm(LdSize));
6897   } else { // arm
6898     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6899                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6900                        .addReg(0).addImm(LdSize));
6901   }
6902 }
6903
6904 /// Emit a post-increment store operation with given size. The instructions
6905 /// will be added to BB at Pos.
6906 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
6907                        const TargetInstrInfo *TII, DebugLoc dl,
6908                        unsigned StSize, unsigned Data, unsigned AddrIn,
6909                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6910   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
6911   assert(StOpc != 0 && "Should have a store opcode");
6912   if (StSize >= 8) {
6913     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6914                        .addReg(AddrIn).addImm(0).addReg(Data));
6915   } else if (IsThumb1) {
6916     // store + update AddrIn
6917     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
6918                        .addReg(AddrIn).addImm(0));
6919     MachineInstrBuilder MIB =
6920         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6921     MIB = AddDefaultT1CC(MIB);
6922     MIB.addReg(AddrIn).addImm(StSize);
6923     AddDefaultPred(MIB);
6924   } else if (IsThumb2) {
6925     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6926                        .addReg(Data).addReg(AddrIn).addImm(StSize));
6927   } else { // arm
6928     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6929                        .addReg(Data).addReg(AddrIn).addReg(0)
6930                        .addImm(StSize));
6931   }
6932 }
6933
6934 MachineBasicBlock *
6935 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
6936                                    MachineBasicBlock *BB) const {
6937   // This pseudo instruction has 3 operands: dst, src, size
6938   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
6939   // Otherwise, we will generate unrolled scalar copies.
6940   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6941   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6942   MachineFunction::iterator It = BB;
6943   ++It;
6944
6945   unsigned dest = MI->getOperand(0).getReg();
6946   unsigned src = MI->getOperand(1).getReg();
6947   unsigned SizeVal = MI->getOperand(2).getImm();
6948   unsigned Align = MI->getOperand(3).getImm();
6949   DebugLoc dl = MI->getDebugLoc();
6950
6951   MachineFunction *MF = BB->getParent();
6952   MachineRegisterInfo &MRI = MF->getRegInfo();
6953   unsigned UnitSize = 0;
6954   const TargetRegisterClass *TRC = nullptr;
6955   const TargetRegisterClass *VecTRC = nullptr;
6956
6957   bool IsThumb1 = Subtarget->isThumb1Only();
6958   bool IsThumb2 = Subtarget->isThumb2();
6959
6960   if (Align & 1) {
6961     UnitSize = 1;
6962   } else if (Align & 2) {
6963     UnitSize = 2;
6964   } else {
6965     // Check whether we can use NEON instructions.
6966     if (!MF->getFunction()->getAttributes().
6967           hasAttribute(AttributeSet::FunctionIndex,
6968                        Attribute::NoImplicitFloat) &&
6969         Subtarget->hasNEON()) {
6970       if ((Align % 16 == 0) && SizeVal >= 16)
6971         UnitSize = 16;
6972       else if ((Align % 8 == 0) && SizeVal >= 8)
6973         UnitSize = 8;
6974     }
6975     // Can't use NEON instructions.
6976     if (UnitSize == 0)
6977       UnitSize = 4;
6978   }
6979
6980   // Select the correct opcode and register class for unit size load/store
6981   bool IsNeon = UnitSize >= 8;
6982   TRC = (IsThumb1 || IsThumb2) ? (const TargetRegisterClass *)&ARM::tGPRRegClass
6983                                : (const TargetRegisterClass *)&ARM::GPRRegClass;
6984   if (IsNeon)
6985     VecTRC = UnitSize == 16
6986                  ? (const TargetRegisterClass *)&ARM::DPairRegClass
6987                  : UnitSize == 8
6988                        ? (const TargetRegisterClass *)&ARM::DPRRegClass
6989                        : nullptr;
6990
6991   unsigned BytesLeft = SizeVal % UnitSize;
6992   unsigned LoopSize = SizeVal - BytesLeft;
6993
6994   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
6995     // Use LDR and STR to copy.
6996     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
6997     // [destOut] = STR_POST(scratch, destIn, UnitSize)
6998     unsigned srcIn = src;
6999     unsigned destIn = dest;
7000     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7001       unsigned srcOut = MRI.createVirtualRegister(TRC);
7002       unsigned destOut = MRI.createVirtualRegister(TRC);
7003       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7004       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7005                  IsThumb1, IsThumb2);
7006       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7007                  IsThumb1, IsThumb2);
7008       srcIn = srcOut;
7009       destIn = destOut;
7010     }
7011
7012     // Handle the leftover bytes with LDRB and STRB.
7013     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7014     // [destOut] = STRB_POST(scratch, destIn, 1)
7015     for (unsigned i = 0; i < BytesLeft; i++) {
7016       unsigned srcOut = MRI.createVirtualRegister(TRC);
7017       unsigned destOut = MRI.createVirtualRegister(TRC);
7018       unsigned scratch = MRI.createVirtualRegister(TRC);
7019       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7020                  IsThumb1, IsThumb2);
7021       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7022                  IsThumb1, IsThumb2);
7023       srcIn = srcOut;
7024       destIn = destOut;
7025     }
7026     MI->eraseFromParent();   // The instruction is gone now.
7027     return BB;
7028   }
7029
7030   // Expand the pseudo op to a loop.
7031   // thisMBB:
7032   //   ...
7033   //   movw varEnd, # --> with thumb2
7034   //   movt varEnd, #
7035   //   ldrcp varEnd, idx --> without thumb2
7036   //   fallthrough --> loopMBB
7037   // loopMBB:
7038   //   PHI varPhi, varEnd, varLoop
7039   //   PHI srcPhi, src, srcLoop
7040   //   PHI destPhi, dst, destLoop
7041   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7042   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7043   //   subs varLoop, varPhi, #UnitSize
7044   //   bne loopMBB
7045   //   fallthrough --> exitMBB
7046   // exitMBB:
7047   //   epilogue to handle left-over bytes
7048   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7049   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7050   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7051   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7052   MF->insert(It, loopMBB);
7053   MF->insert(It, exitMBB);
7054
7055   // Transfer the remainder of BB and its successor edges to exitMBB.
7056   exitMBB->splice(exitMBB->begin(), BB,
7057                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7058   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7059
7060   // Load an immediate to varEnd.
7061   unsigned varEnd = MRI.createVirtualRegister(TRC);
7062   if (IsThumb2) {
7063     unsigned Vtmp = varEnd;
7064     if ((LoopSize & 0xFFFF0000) != 0)
7065       Vtmp = MRI.createVirtualRegister(TRC);
7066     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp)
7067                        .addImm(LoopSize & 0xFFFF));
7068
7069     if ((LoopSize & 0xFFFF0000) != 0)
7070       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7071                          .addReg(Vtmp).addImm(LoopSize >> 16));
7072   } else {
7073     MachineConstantPool *ConstantPool = MF->getConstantPool();
7074     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7075     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7076
7077     // MachineConstantPool wants an explicit alignment.
7078     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7079     if (Align == 0)
7080       Align = getDataLayout()->getTypeAllocSize(C->getType());
7081     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7082
7083     if (IsThumb1)
7084       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7085           varEnd, RegState::Define).addConstantPoolIndex(Idx));
7086     else
7087       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7088           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7089   }
7090   BB->addSuccessor(loopMBB);
7091
7092   // Generate the loop body:
7093   //   varPhi = PHI(varLoop, varEnd)
7094   //   srcPhi = PHI(srcLoop, src)
7095   //   destPhi = PHI(destLoop, dst)
7096   MachineBasicBlock *entryBB = BB;
7097   BB = loopMBB;
7098   unsigned varLoop = MRI.createVirtualRegister(TRC);
7099   unsigned varPhi = MRI.createVirtualRegister(TRC);
7100   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7101   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7102   unsigned destLoop = MRI.createVirtualRegister(TRC);
7103   unsigned destPhi = MRI.createVirtualRegister(TRC);
7104
7105   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7106     .addReg(varLoop).addMBB(loopMBB)
7107     .addReg(varEnd).addMBB(entryBB);
7108   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7109     .addReg(srcLoop).addMBB(loopMBB)
7110     .addReg(src).addMBB(entryBB);
7111   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7112     .addReg(destLoop).addMBB(loopMBB)
7113     .addReg(dest).addMBB(entryBB);
7114
7115   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7116   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7117   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7118   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7119              IsThumb1, IsThumb2);
7120   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7121              IsThumb1, IsThumb2);
7122
7123   // Decrement loop variable by UnitSize.
7124   if (IsThumb1) {
7125     MachineInstrBuilder MIB =
7126         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7127     MIB = AddDefaultT1CC(MIB);
7128     MIB.addReg(varPhi).addImm(UnitSize);
7129     AddDefaultPred(MIB);
7130   } else {
7131     MachineInstrBuilder MIB =
7132         BuildMI(*BB, BB->end(), dl,
7133                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7134     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7135     MIB->getOperand(5).setReg(ARM::CPSR);
7136     MIB->getOperand(5).setIsDef(true);
7137   }
7138   BuildMI(*BB, BB->end(), dl,
7139           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7140       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7141
7142   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7143   BB->addSuccessor(loopMBB);
7144   BB->addSuccessor(exitMBB);
7145
7146   // Add epilogue to handle BytesLeft.
7147   BB = exitMBB;
7148   MachineInstr *StartOfExit = exitMBB->begin();
7149
7150   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7151   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7152   unsigned srcIn = srcLoop;
7153   unsigned destIn = destLoop;
7154   for (unsigned i = 0; i < BytesLeft; i++) {
7155     unsigned srcOut = MRI.createVirtualRegister(TRC);
7156     unsigned destOut = MRI.createVirtualRegister(TRC);
7157     unsigned scratch = MRI.createVirtualRegister(TRC);
7158     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7159                IsThumb1, IsThumb2);
7160     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7161                IsThumb1, IsThumb2);
7162     srcIn = srcOut;
7163     destIn = destOut;
7164   }
7165
7166   MI->eraseFromParent();   // The instruction is gone now.
7167   return BB;
7168 }
7169
7170 MachineBasicBlock *
7171 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7172                                        MachineBasicBlock *MBB) const {
7173   const TargetMachine &TM = getTargetMachine();
7174   const TargetInstrInfo &TII = *TM.getInstrInfo();
7175   DebugLoc DL = MI->getDebugLoc();
7176
7177   assert(Subtarget->isTargetWindows() &&
7178          "__chkstk is only supported on Windows");
7179   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7180
7181   // __chkstk takes the number of words to allocate on the stack in R4, and
7182   // returns the stack adjustment in number of bytes in R4.  This will not
7183   // clober any other registers (other than the obvious lr).
7184   //
7185   // Although, technically, IP should be considered a register which may be
7186   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
7187   // thumb-2 environment, so there is no interworking required.  As a result, we
7188   // do not expect a veneer to be emitted by the linker, clobbering IP.
7189   //
7190   // Each module receives its own copy of __chkstk, so no import thunk is
7191   // required, again, ensuring that IP is not clobbered.
7192   //
7193   // Finally, although some linkers may theoretically provide a trampoline for
7194   // out of range calls (which is quite common due to a 32M range limitation of
7195   // branches for Thumb), we can generate the long-call version via
7196   // -mcmodel=large, alleviating the need for the trampoline which may clobber
7197   // IP.
7198
7199   switch (TM.getCodeModel()) {
7200   case CodeModel::Small:
7201   case CodeModel::Medium:
7202   case CodeModel::Default:
7203   case CodeModel::Kernel:
7204     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7205       .addImm((unsigned)ARMCC::AL).addReg(0)
7206       .addExternalSymbol("__chkstk")
7207       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7208       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7209       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7210     break;
7211   case CodeModel::Large:
7212   case CodeModel::JITDefault: {
7213     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7214     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7215
7216     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7217       .addExternalSymbol("__chkstk");
7218     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7219       .addImm((unsigned)ARMCC::AL).addReg(0)
7220       .addReg(Reg, RegState::Kill)
7221       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7222       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7223       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7224     break;
7225   }
7226   }
7227
7228   AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7229                                       ARM::SP)
7230                               .addReg(ARM::SP, RegState::Define)
7231                               .addReg(ARM::R4, RegState::Kill)));
7232
7233   MI->eraseFromParent();
7234   return MBB;
7235 }
7236
7237 MachineBasicBlock *
7238 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7239                                                MachineBasicBlock *BB) const {
7240   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7241   DebugLoc dl = MI->getDebugLoc();
7242   bool isThumb2 = Subtarget->isThumb2();
7243   switch (MI->getOpcode()) {
7244   default: {
7245     MI->dump();
7246     llvm_unreachable("Unexpected instr type to insert");
7247   }
7248   // The Thumb2 pre-indexed stores have the same MI operands, they just
7249   // define them differently in the .td files from the isel patterns, so
7250   // they need pseudos.
7251   case ARM::t2STR_preidx:
7252     MI->setDesc(TII->get(ARM::t2STR_PRE));
7253     return BB;
7254   case ARM::t2STRB_preidx:
7255     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7256     return BB;
7257   case ARM::t2STRH_preidx:
7258     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7259     return BB;
7260
7261   case ARM::STRi_preidx:
7262   case ARM::STRBi_preidx: {
7263     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7264       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7265     // Decode the offset.
7266     unsigned Offset = MI->getOperand(4).getImm();
7267     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7268     Offset = ARM_AM::getAM2Offset(Offset);
7269     if (isSub)
7270       Offset = -Offset;
7271
7272     MachineMemOperand *MMO = *MI->memoperands_begin();
7273     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7274       .addOperand(MI->getOperand(0))  // Rn_wb
7275       .addOperand(MI->getOperand(1))  // Rt
7276       .addOperand(MI->getOperand(2))  // Rn
7277       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7278       .addOperand(MI->getOperand(5))  // pred
7279       .addOperand(MI->getOperand(6))
7280       .addMemOperand(MMO);
7281     MI->eraseFromParent();
7282     return BB;
7283   }
7284   case ARM::STRr_preidx:
7285   case ARM::STRBr_preidx:
7286   case ARM::STRH_preidx: {
7287     unsigned NewOpc;
7288     switch (MI->getOpcode()) {
7289     default: llvm_unreachable("unexpected opcode!");
7290     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7291     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7292     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7293     }
7294     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7295     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7296       MIB.addOperand(MI->getOperand(i));
7297     MI->eraseFromParent();
7298     return BB;
7299   }
7300
7301   case ARM::tMOVCCr_pseudo: {
7302     // To "insert" a SELECT_CC instruction, we actually have to insert the
7303     // diamond control-flow pattern.  The incoming instruction knows the
7304     // destination vreg to set, the condition code register to branch on, the
7305     // true/false values to select between, and a branch opcode to use.
7306     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7307     MachineFunction::iterator It = BB;
7308     ++It;
7309
7310     //  thisMBB:
7311     //  ...
7312     //   TrueVal = ...
7313     //   cmpTY ccX, r1, r2
7314     //   bCC copy1MBB
7315     //   fallthrough --> copy0MBB
7316     MachineBasicBlock *thisMBB  = BB;
7317     MachineFunction *F = BB->getParent();
7318     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7319     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7320     F->insert(It, copy0MBB);
7321     F->insert(It, sinkMBB);
7322
7323     // Transfer the remainder of BB and its successor edges to sinkMBB.
7324     sinkMBB->splice(sinkMBB->begin(), BB,
7325                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7326     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7327
7328     BB->addSuccessor(copy0MBB);
7329     BB->addSuccessor(sinkMBB);
7330
7331     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7332       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7333
7334     //  copy0MBB:
7335     //   %FalseValue = ...
7336     //   # fallthrough to sinkMBB
7337     BB = copy0MBB;
7338
7339     // Update machine-CFG edges
7340     BB->addSuccessor(sinkMBB);
7341
7342     //  sinkMBB:
7343     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7344     //  ...
7345     BB = sinkMBB;
7346     BuildMI(*BB, BB->begin(), dl,
7347             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7348       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7349       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7350
7351     MI->eraseFromParent();   // The pseudo instruction is gone now.
7352     return BB;
7353   }
7354
7355   case ARM::BCCi64:
7356   case ARM::BCCZi64: {
7357     // If there is an unconditional branch to the other successor, remove it.
7358     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7359
7360     // Compare both parts that make up the double comparison separately for
7361     // equality.
7362     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7363
7364     unsigned LHS1 = MI->getOperand(1).getReg();
7365     unsigned LHS2 = MI->getOperand(2).getReg();
7366     if (RHSisZero) {
7367       AddDefaultPred(BuildMI(BB, dl,
7368                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7369                      .addReg(LHS1).addImm(0));
7370       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7371         .addReg(LHS2).addImm(0)
7372         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7373     } else {
7374       unsigned RHS1 = MI->getOperand(3).getReg();
7375       unsigned RHS2 = MI->getOperand(4).getReg();
7376       AddDefaultPred(BuildMI(BB, dl,
7377                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7378                      .addReg(LHS1).addReg(RHS1));
7379       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7380         .addReg(LHS2).addReg(RHS2)
7381         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7382     }
7383
7384     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7385     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7386     if (MI->getOperand(0).getImm() == ARMCC::NE)
7387       std::swap(destMBB, exitMBB);
7388
7389     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7390       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7391     if (isThumb2)
7392       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7393     else
7394       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7395
7396     MI->eraseFromParent();   // The pseudo instruction is gone now.
7397     return BB;
7398   }
7399
7400   case ARM::Int_eh_sjlj_setjmp:
7401   case ARM::Int_eh_sjlj_setjmp_nofp:
7402   case ARM::tInt_eh_sjlj_setjmp:
7403   case ARM::t2Int_eh_sjlj_setjmp:
7404   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7405     EmitSjLjDispatchBlock(MI, BB);
7406     return BB;
7407
7408   case ARM::ABS:
7409   case ARM::t2ABS: {
7410     // To insert an ABS instruction, we have to insert the
7411     // diamond control-flow pattern.  The incoming instruction knows the
7412     // source vreg to test against 0, the destination vreg to set,
7413     // the condition code register to branch on, the
7414     // true/false values to select between, and a branch opcode to use.
7415     // It transforms
7416     //     V1 = ABS V0
7417     // into
7418     //     V2 = MOVS V0
7419     //     BCC                      (branch to SinkBB if V0 >= 0)
7420     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7421     //     SinkBB: V1 = PHI(V2, V3)
7422     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7423     MachineFunction::iterator BBI = BB;
7424     ++BBI;
7425     MachineFunction *Fn = BB->getParent();
7426     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7427     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7428     Fn->insert(BBI, RSBBB);
7429     Fn->insert(BBI, SinkBB);
7430
7431     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7432     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7433     bool isThumb2 = Subtarget->isThumb2();
7434     MachineRegisterInfo &MRI = Fn->getRegInfo();
7435     // In Thumb mode S must not be specified if source register is the SP or
7436     // PC and if destination register is the SP, so restrict register class
7437     unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7438       (const TargetRegisterClass*)&ARM::rGPRRegClass :
7439       (const TargetRegisterClass*)&ARM::GPRRegClass);
7440
7441     // Transfer the remainder of BB and its successor edges to sinkMBB.
7442     SinkBB->splice(SinkBB->begin(), BB,
7443                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
7444     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7445
7446     BB->addSuccessor(RSBBB);
7447     BB->addSuccessor(SinkBB);
7448
7449     // fall through to SinkMBB
7450     RSBBB->addSuccessor(SinkBB);
7451
7452     // insert a cmp at the end of BB
7453     AddDefaultPred(BuildMI(BB, dl,
7454                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7455                    .addReg(ABSSrcReg).addImm(0));
7456
7457     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7458     BuildMI(BB, dl,
7459       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7460       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7461
7462     // insert rsbri in RSBBB
7463     // Note: BCC and rsbri will be converted into predicated rsbmi
7464     // by if-conversion pass
7465     BuildMI(*RSBBB, RSBBB->begin(), dl,
7466       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7467       .addReg(ABSSrcReg, RegState::Kill)
7468       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7469
7470     // insert PHI in SinkBB,
7471     // reuse ABSDstReg to not change uses of ABS instruction
7472     BuildMI(*SinkBB, SinkBB->begin(), dl,
7473       TII->get(ARM::PHI), ABSDstReg)
7474       .addReg(NewRsbDstReg).addMBB(RSBBB)
7475       .addReg(ABSSrcReg).addMBB(BB);
7476
7477     // remove ABS instruction
7478     MI->eraseFromParent();
7479
7480     // return last added BB
7481     return SinkBB;
7482   }
7483   case ARM::COPY_STRUCT_BYVAL_I32:
7484     ++NumLoopByVals;
7485     return EmitStructByval(MI, BB);
7486   case ARM::WIN__CHKSTK:
7487     return EmitLowered__chkstk(MI, BB);
7488   }
7489 }
7490
7491 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7492                                                       SDNode *Node) const {
7493   if (!MI->hasPostISelHook()) {
7494     assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7495            "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7496     return;
7497   }
7498
7499   const MCInstrDesc *MCID = &MI->getDesc();
7500   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7501   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7502   // operand is still set to noreg. If needed, set the optional operand's
7503   // register to CPSR, and remove the redundant implicit def.
7504   //
7505   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7506
7507   // Rename pseudo opcodes.
7508   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7509   if (NewOpc) {
7510     const ARMBaseInstrInfo *TII =
7511       static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
7512     MCID = &TII->get(NewOpc);
7513
7514     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7515            "converted opcode should be the same except for cc_out");
7516
7517     MI->setDesc(*MCID);
7518
7519     // Add the optional cc_out operand
7520     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7521   }
7522   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7523
7524   // Any ARM instruction that sets the 's' bit should specify an optional
7525   // "cc_out" operand in the last operand position.
7526   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7527     assert(!NewOpc && "Optional cc_out operand required");
7528     return;
7529   }
7530   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7531   // since we already have an optional CPSR def.
7532   bool definesCPSR = false;
7533   bool deadCPSR = false;
7534   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7535        i != e; ++i) {
7536     const MachineOperand &MO = MI->getOperand(i);
7537     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7538       definesCPSR = true;
7539       if (MO.isDead())
7540         deadCPSR = true;
7541       MI->RemoveOperand(i);
7542       break;
7543     }
7544   }
7545   if (!definesCPSR) {
7546     assert(!NewOpc && "Optional cc_out operand required");
7547     return;
7548   }
7549   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7550   if (deadCPSR) {
7551     assert(!MI->getOperand(ccOutIdx).getReg() &&
7552            "expect uninitialized optional cc_out operand");
7553     return;
7554   }
7555
7556   // If this instruction was defined with an optional CPSR def and its dag node
7557   // had a live implicit CPSR def, then activate the optional CPSR def.
7558   MachineOperand &MO = MI->getOperand(ccOutIdx);
7559   MO.setReg(ARM::CPSR);
7560   MO.setIsDef(true);
7561 }
7562
7563 //===----------------------------------------------------------------------===//
7564 //                           ARM Optimization Hooks
7565 //===----------------------------------------------------------------------===//
7566
7567 // Helper function that checks if N is a null or all ones constant.
7568 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7569   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7570   if (!C)
7571     return false;
7572   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7573 }
7574
7575 // Return true if N is conditionally 0 or all ones.
7576 // Detects these expressions where cc is an i1 value:
7577 //
7578 //   (select cc 0, y)   [AllOnes=0]
7579 //   (select cc y, 0)   [AllOnes=0]
7580 //   (zext cc)          [AllOnes=0]
7581 //   (sext cc)          [AllOnes=0/1]
7582 //   (select cc -1, y)  [AllOnes=1]
7583 //   (select cc y, -1)  [AllOnes=1]
7584 //
7585 // Invert is set when N is the null/all ones constant when CC is false.
7586 // OtherOp is set to the alternative value of N.
7587 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7588                                        SDValue &CC, bool &Invert,
7589                                        SDValue &OtherOp,
7590                                        SelectionDAG &DAG) {
7591   switch (N->getOpcode()) {
7592   default: return false;
7593   case ISD::SELECT: {
7594     CC = N->getOperand(0);
7595     SDValue N1 = N->getOperand(1);
7596     SDValue N2 = N->getOperand(2);
7597     if (isZeroOrAllOnes(N1, AllOnes)) {
7598       Invert = false;
7599       OtherOp = N2;
7600       return true;
7601     }
7602     if (isZeroOrAllOnes(N2, AllOnes)) {
7603       Invert = true;
7604       OtherOp = N1;
7605       return true;
7606     }
7607     return false;
7608   }
7609   case ISD::ZERO_EXTEND:
7610     // (zext cc) can never be the all ones value.
7611     if (AllOnes)
7612       return false;
7613     // Fall through.
7614   case ISD::SIGN_EXTEND: {
7615     EVT VT = N->getValueType(0);
7616     CC = N->getOperand(0);
7617     if (CC.getValueType() != MVT::i1)
7618       return false;
7619     Invert = !AllOnes;
7620     if (AllOnes)
7621       // When looking for an AllOnes constant, N is an sext, and the 'other'
7622       // value is 0.
7623       OtherOp = DAG.getConstant(0, VT);
7624     else if (N->getOpcode() == ISD::ZERO_EXTEND)
7625       // When looking for a 0 constant, N can be zext or sext.
7626       OtherOp = DAG.getConstant(1, VT);
7627     else
7628       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7629     return true;
7630   }
7631   }
7632 }
7633
7634 // Combine a constant select operand into its use:
7635 //
7636 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
7637 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
7638 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
7639 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
7640 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
7641 //
7642 // The transform is rejected if the select doesn't have a constant operand that
7643 // is null, or all ones when AllOnes is set.
7644 //
7645 // Also recognize sext/zext from i1:
7646 //
7647 //   (add (zext cc), x) -> (select cc (add x, 1), x)
7648 //   (add (sext cc), x) -> (select cc (add x, -1), x)
7649 //
7650 // These transformations eventually create predicated instructions.
7651 //
7652 // @param N       The node to transform.
7653 // @param Slct    The N operand that is a select.
7654 // @param OtherOp The other N operand (x above).
7655 // @param DCI     Context.
7656 // @param AllOnes Require the select constant to be all ones instead of null.
7657 // @returns The new node, or SDValue() on failure.
7658 static
7659 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7660                             TargetLowering::DAGCombinerInfo &DCI,
7661                             bool AllOnes = false) {
7662   SelectionDAG &DAG = DCI.DAG;
7663   EVT VT = N->getValueType(0);
7664   SDValue NonConstantVal;
7665   SDValue CCOp;
7666   bool SwapSelectOps;
7667   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7668                                   NonConstantVal, DAG))
7669     return SDValue();
7670
7671   // Slct is now know to be the desired identity constant when CC is true.
7672   SDValue TrueVal = OtherOp;
7673   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7674                                  OtherOp, NonConstantVal);
7675   // Unless SwapSelectOps says CC should be false.
7676   if (SwapSelectOps)
7677     std::swap(TrueVal, FalseVal);
7678
7679   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7680                      CCOp, TrueVal, FalseVal);
7681 }
7682
7683 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7684 static
7685 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7686                                        TargetLowering::DAGCombinerInfo &DCI) {
7687   SDValue N0 = N->getOperand(0);
7688   SDValue N1 = N->getOperand(1);
7689   if (N0.getNode()->hasOneUse()) {
7690     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7691     if (Result.getNode())
7692       return Result;
7693   }
7694   if (N1.getNode()->hasOneUse()) {
7695     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7696     if (Result.getNode())
7697       return Result;
7698   }
7699   return SDValue();
7700 }
7701
7702 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7703 // (only after legalization).
7704 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7705                                  TargetLowering::DAGCombinerInfo &DCI,
7706                                  const ARMSubtarget *Subtarget) {
7707
7708   // Only perform optimization if after legalize, and if NEON is available. We
7709   // also expected both operands to be BUILD_VECTORs.
7710   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7711       || N0.getOpcode() != ISD::BUILD_VECTOR
7712       || N1.getOpcode() != ISD::BUILD_VECTOR)
7713     return SDValue();
7714
7715   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7716   EVT VT = N->getValueType(0);
7717   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7718     return SDValue();
7719
7720   // Check that the vector operands are of the right form.
7721   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7722   // operands, where N is the size of the formed vector.
7723   // Each EXTRACT_VECTOR should have the same input vector and odd or even
7724   // index such that we have a pair wise add pattern.
7725
7726   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7727   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7728     return SDValue();
7729   SDValue Vec = N0->getOperand(0)->getOperand(0);
7730   SDNode *V = Vec.getNode();
7731   unsigned nextIndex = 0;
7732
7733   // For each operands to the ADD which are BUILD_VECTORs,
7734   // check to see if each of their operands are an EXTRACT_VECTOR with
7735   // the same vector and appropriate index.
7736   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7737     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7738         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7739
7740       SDValue ExtVec0 = N0->getOperand(i);
7741       SDValue ExtVec1 = N1->getOperand(i);
7742
7743       // First operand is the vector, verify its the same.
7744       if (V != ExtVec0->getOperand(0).getNode() ||
7745           V != ExtVec1->getOperand(0).getNode())
7746         return SDValue();
7747
7748       // Second is the constant, verify its correct.
7749       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7750       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7751
7752       // For the constant, we want to see all the even or all the odd.
7753       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7754           || C1->getZExtValue() != nextIndex+1)
7755         return SDValue();
7756
7757       // Increment index.
7758       nextIndex+=2;
7759     } else
7760       return SDValue();
7761   }
7762
7763   // Create VPADDL node.
7764   SelectionDAG &DAG = DCI.DAG;
7765   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7766
7767   // Build operand list.
7768   SmallVector<SDValue, 8> Ops;
7769   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7770                                 TLI.getPointerTy()));
7771
7772   // Input is the vector.
7773   Ops.push_back(Vec);
7774
7775   // Get widened type and narrowed type.
7776   MVT widenType;
7777   unsigned numElem = VT.getVectorNumElements();
7778   
7779   EVT inputLaneType = Vec.getValueType().getVectorElementType();
7780   switch (inputLaneType.getSimpleVT().SimpleTy) {
7781     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7782     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7783     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7784     default:
7785       llvm_unreachable("Invalid vector element type for padd optimization.");
7786   }
7787
7788   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), widenType, Ops);
7789   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
7790   return DAG.getNode(ExtOp, SDLoc(N), VT, tmp);
7791 }
7792
7793 static SDValue findMUL_LOHI(SDValue V) {
7794   if (V->getOpcode() == ISD::UMUL_LOHI ||
7795       V->getOpcode() == ISD::SMUL_LOHI)
7796     return V;
7797   return SDValue();
7798 }
7799
7800 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7801                                      TargetLowering::DAGCombinerInfo &DCI,
7802                                      const ARMSubtarget *Subtarget) {
7803
7804   if (Subtarget->isThumb1Only()) return SDValue();
7805
7806   // Only perform the checks after legalize when the pattern is available.
7807   if (DCI.isBeforeLegalize()) return SDValue();
7808
7809   // Look for multiply add opportunities.
7810   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7811   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7812   // a glue link from the first add to the second add.
7813   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7814   // a S/UMLAL instruction.
7815   //          loAdd   UMUL_LOHI
7816   //            \    / :lo    \ :hi
7817   //             \  /          \          [no multiline comment]
7818   //              ADDC         |  hiAdd
7819   //                 \ :glue  /  /
7820   //                  \      /  /
7821   //                    ADDE
7822   //
7823   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7824   SDValue AddcOp0 = AddcNode->getOperand(0);
7825   SDValue AddcOp1 = AddcNode->getOperand(1);
7826
7827   // Check if the two operands are from the same mul_lohi node.
7828   if (AddcOp0.getNode() == AddcOp1.getNode())
7829     return SDValue();
7830
7831   assert(AddcNode->getNumValues() == 2 &&
7832          AddcNode->getValueType(0) == MVT::i32 &&
7833          "Expect ADDC with two result values. First: i32");
7834
7835   // Check that we have a glued ADDC node.
7836   if (AddcNode->getValueType(1) != MVT::Glue)
7837     return SDValue();
7838
7839   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7840   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7841       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7842       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7843       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7844     return SDValue();
7845
7846   // Look for the glued ADDE.
7847   SDNode* AddeNode = AddcNode->getGluedUser();
7848   if (!AddeNode)
7849     return SDValue();
7850
7851   // Make sure it is really an ADDE.
7852   if (AddeNode->getOpcode() != ISD::ADDE)
7853     return SDValue();
7854
7855   assert(AddeNode->getNumOperands() == 3 &&
7856          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
7857          "ADDE node has the wrong inputs");
7858
7859   // Check for the triangle shape.
7860   SDValue AddeOp0 = AddeNode->getOperand(0);
7861   SDValue AddeOp1 = AddeNode->getOperand(1);
7862
7863   // Make sure that the ADDE operands are not coming from the same node.
7864   if (AddeOp0.getNode() == AddeOp1.getNode())
7865     return SDValue();
7866
7867   // Find the MUL_LOHI node walking up ADDE's operands.
7868   bool IsLeftOperandMUL = false;
7869   SDValue MULOp = findMUL_LOHI(AddeOp0);
7870   if (MULOp == SDValue())
7871    MULOp = findMUL_LOHI(AddeOp1);
7872   else
7873     IsLeftOperandMUL = true;
7874   if (MULOp == SDValue())
7875      return SDValue();
7876
7877   // Figure out the right opcode.
7878   unsigned Opc = MULOp->getOpcode();
7879   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
7880
7881   // Figure out the high and low input values to the MLAL node.
7882   SDValue* HiMul = &MULOp;
7883   SDValue* HiAdd = nullptr;
7884   SDValue* LoMul = nullptr;
7885   SDValue* LowAdd = nullptr;
7886
7887   if (IsLeftOperandMUL)
7888     HiAdd = &AddeOp1;
7889   else
7890     HiAdd = &AddeOp0;
7891
7892
7893   if (AddcOp0->getOpcode() == Opc) {
7894     LoMul = &AddcOp0;
7895     LowAdd = &AddcOp1;
7896   }
7897   if (AddcOp1->getOpcode() == Opc) {
7898     LoMul = &AddcOp1;
7899     LowAdd = &AddcOp0;
7900   }
7901
7902   if (!LoMul)
7903     return SDValue();
7904
7905   if (LoMul->getNode() != HiMul->getNode())
7906     return SDValue();
7907
7908   // Create the merged node.
7909   SelectionDAG &DAG = DCI.DAG;
7910
7911   // Build operand list.
7912   SmallVector<SDValue, 8> Ops;
7913   Ops.push_back(LoMul->getOperand(0));
7914   Ops.push_back(LoMul->getOperand(1));
7915   Ops.push_back(*LowAdd);
7916   Ops.push_back(*HiAdd);
7917
7918   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
7919                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
7920
7921   // Replace the ADDs' nodes uses by the MLA node's values.
7922   SDValue HiMLALResult(MLALNode.getNode(), 1);
7923   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
7924
7925   SDValue LoMLALResult(MLALNode.getNode(), 0);
7926   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
7927
7928   // Return original node to notify the driver to stop replacing.
7929   SDValue resNode(AddcNode, 0);
7930   return resNode;
7931 }
7932
7933 /// PerformADDCCombine - Target-specific dag combine transform from
7934 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
7935 static SDValue PerformADDCCombine(SDNode *N,
7936                                  TargetLowering::DAGCombinerInfo &DCI,
7937                                  const ARMSubtarget *Subtarget) {
7938
7939   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
7940
7941 }
7942
7943 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
7944 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
7945 /// called with the default operands, and if that fails, with commuted
7946 /// operands.
7947 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
7948                                           TargetLowering::DAGCombinerInfo &DCI,
7949                                           const ARMSubtarget *Subtarget){
7950
7951   // Attempt to create vpaddl for this add.
7952   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
7953   if (Result.getNode())
7954     return Result;
7955
7956   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7957   if (N0.getNode()->hasOneUse()) {
7958     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
7959     if (Result.getNode()) return Result;
7960   }
7961   return SDValue();
7962 }
7963
7964 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
7965 ///
7966 static SDValue PerformADDCombine(SDNode *N,
7967                                  TargetLowering::DAGCombinerInfo &DCI,
7968                                  const ARMSubtarget *Subtarget) {
7969   SDValue N0 = N->getOperand(0);
7970   SDValue N1 = N->getOperand(1);
7971
7972   // First try with the default operand order.
7973   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
7974   if (Result.getNode())
7975     return Result;
7976
7977   // If that didn't work, try again with the operands commuted.
7978   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
7979 }
7980
7981 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
7982 ///
7983 static SDValue PerformSUBCombine(SDNode *N,
7984                                  TargetLowering::DAGCombinerInfo &DCI) {
7985   SDValue N0 = N->getOperand(0);
7986   SDValue N1 = N->getOperand(1);
7987
7988   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7989   if (N1.getNode()->hasOneUse()) {
7990     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
7991     if (Result.getNode()) return Result;
7992   }
7993
7994   return SDValue();
7995 }
7996
7997 /// PerformVMULCombine
7998 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
7999 /// special multiplier accumulator forwarding.
8000 ///   vmul d3, d0, d2
8001 ///   vmla d3, d1, d2
8002 /// is faster than
8003 ///   vadd d3, d0, d1
8004 ///   vmul d3, d3, d2
8005 //  However, for (A + B) * (A + B),
8006 //    vadd d2, d0, d1
8007 //    vmul d3, d0, d2
8008 //    vmla d3, d1, d2
8009 //  is slower than
8010 //    vadd d2, d0, d1
8011 //    vmul d3, d2, d2
8012 static SDValue PerformVMULCombine(SDNode *N,
8013                                   TargetLowering::DAGCombinerInfo &DCI,
8014                                   const ARMSubtarget *Subtarget) {
8015   if (!Subtarget->hasVMLxForwarding())
8016     return SDValue();
8017
8018   SelectionDAG &DAG = DCI.DAG;
8019   SDValue N0 = N->getOperand(0);
8020   SDValue N1 = N->getOperand(1);
8021   unsigned Opcode = N0.getOpcode();
8022   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8023       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8024     Opcode = N1.getOpcode();
8025     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8026         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8027       return SDValue();
8028     std::swap(N0, N1);
8029   }
8030
8031   if (N0 == N1)
8032     return SDValue();
8033
8034   EVT VT = N->getValueType(0);
8035   SDLoc DL(N);
8036   SDValue N00 = N0->getOperand(0);
8037   SDValue N01 = N0->getOperand(1);
8038   return DAG.getNode(Opcode, DL, VT,
8039                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8040                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8041 }
8042
8043 static SDValue PerformMULCombine(SDNode *N,
8044                                  TargetLowering::DAGCombinerInfo &DCI,
8045                                  const ARMSubtarget *Subtarget) {
8046   SelectionDAG &DAG = DCI.DAG;
8047
8048   if (Subtarget->isThumb1Only())
8049     return SDValue();
8050
8051   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8052     return SDValue();
8053
8054   EVT VT = N->getValueType(0);
8055   if (VT.is64BitVector() || VT.is128BitVector())
8056     return PerformVMULCombine(N, DCI, Subtarget);
8057   if (VT != MVT::i32)
8058     return SDValue();
8059
8060   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8061   if (!C)
8062     return SDValue();
8063
8064   int64_t MulAmt = C->getSExtValue();
8065   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8066
8067   ShiftAmt = ShiftAmt & (32 - 1);
8068   SDValue V = N->getOperand(0);
8069   SDLoc DL(N);
8070
8071   SDValue Res;
8072   MulAmt >>= ShiftAmt;
8073
8074   if (MulAmt >= 0) {
8075     if (isPowerOf2_32(MulAmt - 1)) {
8076       // (mul x, 2^N + 1) => (add (shl x, N), x)
8077       Res = DAG.getNode(ISD::ADD, DL, VT,
8078                         V,
8079                         DAG.getNode(ISD::SHL, DL, VT,
8080                                     V,
8081                                     DAG.getConstant(Log2_32(MulAmt - 1),
8082                                                     MVT::i32)));
8083     } else if (isPowerOf2_32(MulAmt + 1)) {
8084       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8085       Res = DAG.getNode(ISD::SUB, DL, VT,
8086                         DAG.getNode(ISD::SHL, DL, VT,
8087                                     V,
8088                                     DAG.getConstant(Log2_32(MulAmt + 1),
8089                                                     MVT::i32)),
8090                         V);
8091     } else
8092       return SDValue();
8093   } else {
8094     uint64_t MulAmtAbs = -MulAmt;
8095     if (isPowerOf2_32(MulAmtAbs + 1)) {
8096       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8097       Res = DAG.getNode(ISD::SUB, DL, VT,
8098                         V,
8099                         DAG.getNode(ISD::SHL, DL, VT,
8100                                     V,
8101                                     DAG.getConstant(Log2_32(MulAmtAbs + 1),
8102                                                     MVT::i32)));
8103     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8104       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8105       Res = DAG.getNode(ISD::ADD, DL, VT,
8106                         V,
8107                         DAG.getNode(ISD::SHL, DL, VT,
8108                                     V,
8109                                     DAG.getConstant(Log2_32(MulAmtAbs-1),
8110                                                     MVT::i32)));
8111       Res = DAG.getNode(ISD::SUB, DL, VT,
8112                         DAG.getConstant(0, MVT::i32),Res);
8113
8114     } else
8115       return SDValue();
8116   }
8117
8118   if (ShiftAmt != 0)
8119     Res = DAG.getNode(ISD::SHL, DL, VT,
8120                       Res, DAG.getConstant(ShiftAmt, MVT::i32));
8121
8122   // Do not add new nodes to DAG combiner worklist.
8123   DCI.CombineTo(N, Res, false);
8124   return SDValue();
8125 }
8126
8127 static SDValue PerformANDCombine(SDNode *N,
8128                                  TargetLowering::DAGCombinerInfo &DCI,
8129                                  const ARMSubtarget *Subtarget) {
8130
8131   // Attempt to use immediate-form VBIC
8132   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8133   SDLoc dl(N);
8134   EVT VT = N->getValueType(0);
8135   SelectionDAG &DAG = DCI.DAG;
8136
8137   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8138     return SDValue();
8139
8140   APInt SplatBits, SplatUndef;
8141   unsigned SplatBitSize;
8142   bool HasAnyUndefs;
8143   if (BVN &&
8144       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8145     if (SplatBitSize <= 64) {
8146       EVT VbicVT;
8147       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8148                                       SplatUndef.getZExtValue(), SplatBitSize,
8149                                       DAG, VbicVT, VT.is128BitVector(),
8150                                       OtherModImm);
8151       if (Val.getNode()) {
8152         SDValue Input =
8153           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8154         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8155         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8156       }
8157     }
8158   }
8159
8160   if (!Subtarget->isThumb1Only()) {
8161     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8162     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8163     if (Result.getNode())
8164       return Result;
8165   }
8166
8167   return SDValue();
8168 }
8169
8170 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8171 static SDValue PerformORCombine(SDNode *N,
8172                                 TargetLowering::DAGCombinerInfo &DCI,
8173                                 const ARMSubtarget *Subtarget) {
8174   // Attempt to use immediate-form VORR
8175   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8176   SDLoc dl(N);
8177   EVT VT = N->getValueType(0);
8178   SelectionDAG &DAG = DCI.DAG;
8179
8180   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8181     return SDValue();
8182
8183   APInt SplatBits, SplatUndef;
8184   unsigned SplatBitSize;
8185   bool HasAnyUndefs;
8186   if (BVN && Subtarget->hasNEON() &&
8187       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8188     if (SplatBitSize <= 64) {
8189       EVT VorrVT;
8190       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8191                                       SplatUndef.getZExtValue(), SplatBitSize,
8192                                       DAG, VorrVT, VT.is128BitVector(),
8193                                       OtherModImm);
8194       if (Val.getNode()) {
8195         SDValue Input =
8196           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8197         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8198         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8199       }
8200     }
8201   }
8202
8203   if (!Subtarget->isThumb1Only()) {
8204     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8205     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8206     if (Result.getNode())
8207       return Result;
8208   }
8209
8210   // The code below optimizes (or (and X, Y), Z).
8211   // The AND operand needs to have a single user to make these optimizations
8212   // profitable.
8213   SDValue N0 = N->getOperand(0);
8214   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8215     return SDValue();
8216   SDValue N1 = N->getOperand(1);
8217
8218   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8219   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8220       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8221     APInt SplatUndef;
8222     unsigned SplatBitSize;
8223     bool HasAnyUndefs;
8224
8225     APInt SplatBits0, SplatBits1;
8226     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8227     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8228     // Ensure that the second operand of both ands are constants
8229     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8230                                       HasAnyUndefs) && !HasAnyUndefs) {
8231         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8232                                           HasAnyUndefs) && !HasAnyUndefs) {
8233             // Ensure that the bit width of the constants are the same and that
8234             // the splat arguments are logical inverses as per the pattern we
8235             // are trying to simplify.
8236             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8237                 SplatBits0 == ~SplatBits1) {
8238                 // Canonicalize the vector type to make instruction selection
8239                 // simpler.
8240                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8241                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8242                                              N0->getOperand(1),
8243                                              N0->getOperand(0),
8244                                              N1->getOperand(0));
8245                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8246             }
8247         }
8248     }
8249   }
8250
8251   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8252   // reasonable.
8253
8254   // BFI is only available on V6T2+
8255   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8256     return SDValue();
8257
8258   SDLoc DL(N);
8259   // 1) or (and A, mask), val => ARMbfi A, val, mask
8260   //      iff (val & mask) == val
8261   //
8262   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8263   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8264   //          && mask == ~mask2
8265   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8266   //          && ~mask == mask2
8267   //  (i.e., copy a bitfield value into another bitfield of the same width)
8268
8269   if (VT != MVT::i32)
8270     return SDValue();
8271
8272   SDValue N00 = N0.getOperand(0);
8273
8274   // The value and the mask need to be constants so we can verify this is
8275   // actually a bitfield set. If the mask is 0xffff, we can do better
8276   // via a movt instruction, so don't use BFI in that case.
8277   SDValue MaskOp = N0.getOperand(1);
8278   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8279   if (!MaskC)
8280     return SDValue();
8281   unsigned Mask = MaskC->getZExtValue();
8282   if (Mask == 0xffff)
8283     return SDValue();
8284   SDValue Res;
8285   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8286   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8287   if (N1C) {
8288     unsigned Val = N1C->getZExtValue();
8289     if ((Val & ~Mask) != Val)
8290       return SDValue();
8291
8292     if (ARM::isBitFieldInvertedMask(Mask)) {
8293       Val >>= countTrailingZeros(~Mask);
8294
8295       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8296                         DAG.getConstant(Val, MVT::i32),
8297                         DAG.getConstant(Mask, MVT::i32));
8298
8299       // Do not add new nodes to DAG combiner worklist.
8300       DCI.CombineTo(N, Res, false);
8301       return SDValue();
8302     }
8303   } else if (N1.getOpcode() == ISD::AND) {
8304     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8305     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8306     if (!N11C)
8307       return SDValue();
8308     unsigned Mask2 = N11C->getZExtValue();
8309
8310     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8311     // as is to match.
8312     if (ARM::isBitFieldInvertedMask(Mask) &&
8313         (Mask == ~Mask2)) {
8314       // The pack halfword instruction works better for masks that fit it,
8315       // so use that when it's available.
8316       if (Subtarget->hasT2ExtractPack() &&
8317           (Mask == 0xffff || Mask == 0xffff0000))
8318         return SDValue();
8319       // 2a
8320       unsigned amt = countTrailingZeros(Mask2);
8321       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8322                         DAG.getConstant(amt, MVT::i32));
8323       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8324                         DAG.getConstant(Mask, MVT::i32));
8325       // Do not add new nodes to DAG combiner worklist.
8326       DCI.CombineTo(N, Res, false);
8327       return SDValue();
8328     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8329                (~Mask == Mask2)) {
8330       // The pack halfword instruction works better for masks that fit it,
8331       // so use that when it's available.
8332       if (Subtarget->hasT2ExtractPack() &&
8333           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8334         return SDValue();
8335       // 2b
8336       unsigned lsb = countTrailingZeros(Mask);
8337       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8338                         DAG.getConstant(lsb, MVT::i32));
8339       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8340                         DAG.getConstant(Mask2, MVT::i32));
8341       // Do not add new nodes to DAG combiner worklist.
8342       DCI.CombineTo(N, Res, false);
8343       return SDValue();
8344     }
8345   }
8346
8347   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8348       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8349       ARM::isBitFieldInvertedMask(~Mask)) {
8350     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8351     // where lsb(mask) == #shamt and masked bits of B are known zero.
8352     SDValue ShAmt = N00.getOperand(1);
8353     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8354     unsigned LSB = countTrailingZeros(Mask);
8355     if (ShAmtC != LSB)
8356       return SDValue();
8357
8358     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8359                       DAG.getConstant(~Mask, MVT::i32));
8360
8361     // Do not add new nodes to DAG combiner worklist.
8362     DCI.CombineTo(N, Res, false);
8363   }
8364
8365   return SDValue();
8366 }
8367
8368 static SDValue PerformXORCombine(SDNode *N,
8369                                  TargetLowering::DAGCombinerInfo &DCI,
8370                                  const ARMSubtarget *Subtarget) {
8371   EVT VT = N->getValueType(0);
8372   SelectionDAG &DAG = DCI.DAG;
8373
8374   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8375     return SDValue();
8376
8377   if (!Subtarget->isThumb1Only()) {
8378     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8379     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8380     if (Result.getNode())
8381       return Result;
8382   }
8383
8384   return SDValue();
8385 }
8386
8387 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8388 /// the bits being cleared by the AND are not demanded by the BFI.
8389 static SDValue PerformBFICombine(SDNode *N,
8390                                  TargetLowering::DAGCombinerInfo &DCI) {
8391   SDValue N1 = N->getOperand(1);
8392   if (N1.getOpcode() == ISD::AND) {
8393     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8394     if (!N11C)
8395       return SDValue();
8396     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8397     unsigned LSB = countTrailingZeros(~InvMask);
8398     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8399     unsigned Mask = (1 << Width)-1;
8400     unsigned Mask2 = N11C->getZExtValue();
8401     if ((Mask & (~Mask2)) == 0)
8402       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8403                              N->getOperand(0), N1.getOperand(0),
8404                              N->getOperand(2));
8405   }
8406   return SDValue();
8407 }
8408
8409 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8410 /// ARMISD::VMOVRRD.
8411 static SDValue PerformVMOVRRDCombine(SDNode *N,
8412                                      TargetLowering::DAGCombinerInfo &DCI) {
8413   // vmovrrd(vmovdrr x, y) -> x,y
8414   SDValue InDouble = N->getOperand(0);
8415   if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8416     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8417
8418   // vmovrrd(load f64) -> (load i32), (load i32)
8419   SDNode *InNode = InDouble.getNode();
8420   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8421       InNode->getValueType(0) == MVT::f64 &&
8422       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8423       !cast<LoadSDNode>(InNode)->isVolatile()) {
8424     // TODO: Should this be done for non-FrameIndex operands?
8425     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8426
8427     SelectionDAG &DAG = DCI.DAG;
8428     SDLoc DL(LD);
8429     SDValue BasePtr = LD->getBasePtr();
8430     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8431                                  LD->getPointerInfo(), LD->isVolatile(),
8432                                  LD->isNonTemporal(), LD->isInvariant(),
8433                                  LD->getAlignment());
8434
8435     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8436                                     DAG.getConstant(4, MVT::i32));
8437     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8438                                  LD->getPointerInfo(), LD->isVolatile(),
8439                                  LD->isNonTemporal(), LD->isInvariant(),
8440                                  std::min(4U, LD->getAlignment() / 2));
8441
8442     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8443     if (DCI.DAG.getTargetLoweringInfo().isBigEndian())
8444       std::swap (NewLD1, NewLD2);
8445     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8446     DCI.RemoveFromWorklist(LD);
8447     DAG.DeleteNode(LD);
8448     return Result;
8449   }
8450
8451   return SDValue();
8452 }
8453
8454 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8455 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8456 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8457   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8458   SDValue Op0 = N->getOperand(0);
8459   SDValue Op1 = N->getOperand(1);
8460   if (Op0.getOpcode() == ISD::BITCAST)
8461     Op0 = Op0.getOperand(0);
8462   if (Op1.getOpcode() == ISD::BITCAST)
8463     Op1 = Op1.getOperand(0);
8464   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8465       Op0.getNode() == Op1.getNode() &&
8466       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8467     return DAG.getNode(ISD::BITCAST, SDLoc(N),
8468                        N->getValueType(0), Op0.getOperand(0));
8469   return SDValue();
8470 }
8471
8472 /// PerformSTORECombine - Target-specific dag combine xforms for
8473 /// ISD::STORE.
8474 static SDValue PerformSTORECombine(SDNode *N,
8475                                    TargetLowering::DAGCombinerInfo &DCI) {
8476   StoreSDNode *St = cast<StoreSDNode>(N);
8477   if (St->isVolatile())
8478     return SDValue();
8479
8480   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
8481   // pack all of the elements in one place.  Next, store to memory in fewer
8482   // chunks.
8483   SDValue StVal = St->getValue();
8484   EVT VT = StVal.getValueType();
8485   if (St->isTruncatingStore() && VT.isVector()) {
8486     SelectionDAG &DAG = DCI.DAG;
8487     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8488     EVT StVT = St->getMemoryVT();
8489     unsigned NumElems = VT.getVectorNumElements();
8490     assert(StVT != VT && "Cannot truncate to the same type");
8491     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8492     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8493
8494     // From, To sizes and ElemCount must be pow of two
8495     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8496
8497     // We are going to use the original vector elt for storing.
8498     // Accumulated smaller vector elements must be a multiple of the store size.
8499     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8500
8501     unsigned SizeRatio  = FromEltSz / ToEltSz;
8502     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8503
8504     // Create a type on which we perform the shuffle.
8505     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8506                                      NumElems*SizeRatio);
8507     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8508
8509     SDLoc DL(St);
8510     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8511     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8512     for (unsigned i = 0; i < NumElems; ++i)
8513       ShuffleVec[i] = TLI.isBigEndian() ? (i+1) * SizeRatio - 1 : i * SizeRatio;
8514
8515     // Can't shuffle using an illegal type.
8516     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8517
8518     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8519                                 DAG.getUNDEF(WideVec.getValueType()),
8520                                 ShuffleVec.data());
8521     // At this point all of the data is stored at the bottom of the
8522     // register. We now need to save it to mem.
8523
8524     // Find the largest store unit
8525     MVT StoreType = MVT::i8;
8526     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8527          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8528       MVT Tp = (MVT::SimpleValueType)tp;
8529       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8530         StoreType = Tp;
8531     }
8532     // Didn't find a legal store type.
8533     if (!TLI.isTypeLegal(StoreType))
8534       return SDValue();
8535
8536     // Bitcast the original vector into a vector of store-size units
8537     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8538             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8539     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8540     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8541     SmallVector<SDValue, 8> Chains;
8542     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8543                                         TLI.getPointerTy());
8544     SDValue BasePtr = St->getBasePtr();
8545
8546     // Perform one or more big stores into memory.
8547     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8548     for (unsigned I = 0; I < E; I++) {
8549       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8550                                    StoreType, ShuffWide,
8551                                    DAG.getIntPtrConstant(I));
8552       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8553                                 St->getPointerInfo(), St->isVolatile(),
8554                                 St->isNonTemporal(), St->getAlignment());
8555       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8556                             Increment);
8557       Chains.push_back(Ch);
8558     }
8559     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
8560   }
8561
8562   if (!ISD::isNormalStore(St))
8563     return SDValue();
8564
8565   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8566   // ARM stores of arguments in the same cache line.
8567   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8568       StVal.getNode()->hasOneUse()) {
8569     SelectionDAG  &DAG = DCI.DAG;
8570     bool isBigEndian = DAG.getTargetLoweringInfo().isBigEndian();
8571     SDLoc DL(St);
8572     SDValue BasePtr = St->getBasePtr();
8573     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8574                                   StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
8575                                   BasePtr, St->getPointerInfo(), St->isVolatile(),
8576                                   St->isNonTemporal(), St->getAlignment());
8577
8578     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8579                                     DAG.getConstant(4, MVT::i32));
8580     return DAG.getStore(NewST1.getValue(0), DL,
8581                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
8582                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8583                         St->isNonTemporal(),
8584                         std::min(4U, St->getAlignment() / 2));
8585   }
8586
8587   if (StVal.getValueType() != MVT::i64 ||
8588       StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8589     return SDValue();
8590
8591   // Bitcast an i64 store extracted from a vector to f64.
8592   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8593   SelectionDAG &DAG = DCI.DAG;
8594   SDLoc dl(StVal);
8595   SDValue IntVec = StVal.getOperand(0);
8596   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8597                                  IntVec.getValueType().getVectorNumElements());
8598   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8599   SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8600                                Vec, StVal.getOperand(1));
8601   dl = SDLoc(N);
8602   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8603   // Make the DAGCombiner fold the bitcasts.
8604   DCI.AddToWorklist(Vec.getNode());
8605   DCI.AddToWorklist(ExtElt.getNode());
8606   DCI.AddToWorklist(V.getNode());
8607   return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8608                       St->getPointerInfo(), St->isVolatile(),
8609                       St->isNonTemporal(), St->getAlignment(),
8610                       St->getTBAAInfo());
8611 }
8612
8613 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8614 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8615 /// i64 vector to have f64 elements, since the value can then be loaded
8616 /// directly into a VFP register.
8617 static bool hasNormalLoadOperand(SDNode *N) {
8618   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8619   for (unsigned i = 0; i < NumElts; ++i) {
8620     SDNode *Elt = N->getOperand(i).getNode();
8621     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8622       return true;
8623   }
8624   return false;
8625 }
8626
8627 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8628 /// ISD::BUILD_VECTOR.
8629 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8630                                           TargetLowering::DAGCombinerInfo &DCI){
8631   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8632   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
8633   // into a pair of GPRs, which is fine when the value is used as a scalar,
8634   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8635   SelectionDAG &DAG = DCI.DAG;
8636   if (N->getNumOperands() == 2) {
8637     SDValue RV = PerformVMOVDRRCombine(N, DAG);
8638     if (RV.getNode())
8639       return RV;
8640   }
8641
8642   // Load i64 elements as f64 values so that type legalization does not split
8643   // them up into i32 values.
8644   EVT VT = N->getValueType(0);
8645   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8646     return SDValue();
8647   SDLoc dl(N);
8648   SmallVector<SDValue, 8> Ops;
8649   unsigned NumElts = VT.getVectorNumElements();
8650   for (unsigned i = 0; i < NumElts; ++i) {
8651     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8652     Ops.push_back(V);
8653     // Make the DAGCombiner fold the bitcast.
8654     DCI.AddToWorklist(V.getNode());
8655   }
8656   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8657   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8658   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8659 }
8660
8661 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8662 static SDValue
8663 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8664   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8665   // At that time, we may have inserted bitcasts from integer to float.
8666   // If these bitcasts have survived DAGCombine, change the lowering of this
8667   // BUILD_VECTOR in something more vector friendly, i.e., that does not
8668   // force to use floating point types.
8669
8670   // Make sure we can change the type of the vector.
8671   // This is possible iff:
8672   // 1. The vector is only used in a bitcast to a integer type. I.e.,
8673   //    1.1. Vector is used only once.
8674   //    1.2. Use is a bit convert to an integer type.
8675   // 2. The size of its operands are 32-bits (64-bits are not legal).
8676   EVT VT = N->getValueType(0);
8677   EVT EltVT = VT.getVectorElementType();
8678
8679   // Check 1.1. and 2.
8680   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8681     return SDValue();
8682
8683   // By construction, the input type must be float.
8684   assert(EltVT == MVT::f32 && "Unexpected type!");
8685
8686   // Check 1.2.
8687   SDNode *Use = *N->use_begin();
8688   if (Use->getOpcode() != ISD::BITCAST ||
8689       Use->getValueType(0).isFloatingPoint())
8690     return SDValue();
8691
8692   // Check profitability.
8693   // Model is, if more than half of the relevant operands are bitcast from
8694   // i32, turn the build_vector into a sequence of insert_vector_elt.
8695   // Relevant operands are everything that is not statically
8696   // (i.e., at compile time) bitcasted.
8697   unsigned NumOfBitCastedElts = 0;
8698   unsigned NumElts = VT.getVectorNumElements();
8699   unsigned NumOfRelevantElts = NumElts;
8700   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8701     SDValue Elt = N->getOperand(Idx);
8702     if (Elt->getOpcode() == ISD::BITCAST) {
8703       // Assume only bit cast to i32 will go away.
8704       if (Elt->getOperand(0).getValueType() == MVT::i32)
8705         ++NumOfBitCastedElts;
8706     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8707       // Constants are statically casted, thus do not count them as
8708       // relevant operands.
8709       --NumOfRelevantElts;
8710   }
8711
8712   // Check if more than half of the elements require a non-free bitcast.
8713   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8714     return SDValue();
8715
8716   SelectionDAG &DAG = DCI.DAG;
8717   // Create the new vector type.
8718   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8719   // Check if the type is legal.
8720   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8721   if (!TLI.isTypeLegal(VecVT))
8722     return SDValue();
8723
8724   // Combine:
8725   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8726   // => BITCAST INSERT_VECTOR_ELT
8727   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8728   //                      (BITCAST EN), N.
8729   SDValue Vec = DAG.getUNDEF(VecVT);
8730   SDLoc dl(N);
8731   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8732     SDValue V = N->getOperand(Idx);
8733     if (V.getOpcode() == ISD::UNDEF)
8734       continue;
8735     if (V.getOpcode() == ISD::BITCAST &&
8736         V->getOperand(0).getValueType() == MVT::i32)
8737       // Fold obvious case.
8738       V = V.getOperand(0);
8739     else {
8740       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
8741       // Make the DAGCombiner fold the bitcasts.
8742       DCI.AddToWorklist(V.getNode());
8743     }
8744     SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
8745     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8746   }
8747   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8748   // Make the DAGCombiner fold the bitcasts.
8749   DCI.AddToWorklist(Vec.getNode());
8750   return Vec;
8751 }
8752
8753 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8754 /// ISD::INSERT_VECTOR_ELT.
8755 static SDValue PerformInsertEltCombine(SDNode *N,
8756                                        TargetLowering::DAGCombinerInfo &DCI) {
8757   // Bitcast an i64 load inserted into a vector to f64.
8758   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8759   EVT VT = N->getValueType(0);
8760   SDNode *Elt = N->getOperand(1).getNode();
8761   if (VT.getVectorElementType() != MVT::i64 ||
8762       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8763     return SDValue();
8764
8765   SelectionDAG &DAG = DCI.DAG;
8766   SDLoc dl(N);
8767   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8768                                  VT.getVectorNumElements());
8769   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8770   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8771   // Make the DAGCombiner fold the bitcasts.
8772   DCI.AddToWorklist(Vec.getNode());
8773   DCI.AddToWorklist(V.getNode());
8774   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8775                                Vec, V, N->getOperand(2));
8776   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8777 }
8778
8779 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8780 /// ISD::VECTOR_SHUFFLE.
8781 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8782   // The LLVM shufflevector instruction does not require the shuffle mask
8783   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8784   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
8785   // operands do not match the mask length, they are extended by concatenating
8786   // them with undef vectors.  That is probably the right thing for other
8787   // targets, but for NEON it is better to concatenate two double-register
8788   // size vector operands into a single quad-register size vector.  Do that
8789   // transformation here:
8790   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
8791   //   shuffle(concat(v1, v2), undef)
8792   SDValue Op0 = N->getOperand(0);
8793   SDValue Op1 = N->getOperand(1);
8794   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8795       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8796       Op0.getNumOperands() != 2 ||
8797       Op1.getNumOperands() != 2)
8798     return SDValue();
8799   SDValue Concat0Op1 = Op0.getOperand(1);
8800   SDValue Concat1Op1 = Op1.getOperand(1);
8801   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8802       Concat1Op1.getOpcode() != ISD::UNDEF)
8803     return SDValue();
8804   // Skip the transformation if any of the types are illegal.
8805   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8806   EVT VT = N->getValueType(0);
8807   if (!TLI.isTypeLegal(VT) ||
8808       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8809       !TLI.isTypeLegal(Concat1Op1.getValueType()))
8810     return SDValue();
8811
8812   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
8813                                   Op0.getOperand(0), Op1.getOperand(0));
8814   // Translate the shuffle mask.
8815   SmallVector<int, 16> NewMask;
8816   unsigned NumElts = VT.getVectorNumElements();
8817   unsigned HalfElts = NumElts/2;
8818   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8819   for (unsigned n = 0; n < NumElts; ++n) {
8820     int MaskElt = SVN->getMaskElt(n);
8821     int NewElt = -1;
8822     if (MaskElt < (int)HalfElts)
8823       NewElt = MaskElt;
8824     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8825       NewElt = HalfElts + MaskElt - NumElts;
8826     NewMask.push_back(NewElt);
8827   }
8828   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
8829                               DAG.getUNDEF(VT), NewMask.data());
8830 }
8831
8832 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
8833 /// NEON load/store intrinsics to merge base address updates.
8834 static SDValue CombineBaseUpdate(SDNode *N,
8835                                  TargetLowering::DAGCombinerInfo &DCI) {
8836   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8837     return SDValue();
8838
8839   SelectionDAG &DAG = DCI.DAG;
8840   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8841                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8842   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
8843   SDValue Addr = N->getOperand(AddrOpIdx);
8844
8845   // Search for a use of the address operand that is an increment.
8846   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8847          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8848     SDNode *User = *UI;
8849     if (User->getOpcode() != ISD::ADD ||
8850         UI.getUse().getResNo() != Addr.getResNo())
8851       continue;
8852
8853     // Check that the add is independent of the load/store.  Otherwise, folding
8854     // it would create a cycle.
8855     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8856       continue;
8857
8858     // Find the new opcode for the updating load/store.
8859     bool isLoad = true;
8860     bool isLaneOp = false;
8861     unsigned NewOpc = 0;
8862     unsigned NumVecs = 0;
8863     if (isIntrinsic) {
8864       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8865       switch (IntNo) {
8866       default: llvm_unreachable("unexpected intrinsic for Neon base update");
8867       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
8868         NumVecs = 1; break;
8869       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
8870         NumVecs = 2; break;
8871       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
8872         NumVecs = 3; break;
8873       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
8874         NumVecs = 4; break;
8875       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8876         NumVecs = 2; isLaneOp = true; break;
8877       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8878         NumVecs = 3; isLaneOp = true; break;
8879       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8880         NumVecs = 4; isLaneOp = true; break;
8881       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
8882         NumVecs = 1; isLoad = false; break;
8883       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
8884         NumVecs = 2; isLoad = false; break;
8885       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
8886         NumVecs = 3; isLoad = false; break;
8887       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
8888         NumVecs = 4; isLoad = false; break;
8889       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8890         NumVecs = 2; isLoad = false; isLaneOp = true; break;
8891       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8892         NumVecs = 3; isLoad = false; isLaneOp = true; break;
8893       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8894         NumVecs = 4; isLoad = false; isLaneOp = true; break;
8895       }
8896     } else {
8897       isLaneOp = true;
8898       switch (N->getOpcode()) {
8899       default: llvm_unreachable("unexpected opcode for Neon base update");
8900       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8901       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8902       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8903       }
8904     }
8905
8906     // Find the size of memory referenced by the load/store.
8907     EVT VecTy;
8908     if (isLoad)
8909       VecTy = N->getValueType(0);
8910     else
8911       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8912     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8913     if (isLaneOp)
8914       NumBytes /= VecTy.getVectorNumElements();
8915
8916     // If the increment is a constant, it must match the memory ref size.
8917     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8918     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8919       uint64_t IncVal = CInc->getZExtValue();
8920       if (IncVal != NumBytes)
8921         continue;
8922     } else if (NumBytes >= 3 * 16) {
8923       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8924       // separate instructions that make it harder to use a non-constant update.
8925       continue;
8926     }
8927
8928     // Create the new updating load/store node.
8929     EVT Tys[6];
8930     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
8931     unsigned n;
8932     for (n = 0; n < NumResultVecs; ++n)
8933       Tys[n] = VecTy;
8934     Tys[n++] = MVT::i32;
8935     Tys[n] = MVT::Other;
8936     SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumResultVecs+2));
8937     SmallVector<SDValue, 8> Ops;
8938     Ops.push_back(N->getOperand(0)); // incoming chain
8939     Ops.push_back(N->getOperand(AddrOpIdx));
8940     Ops.push_back(Inc);
8941     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
8942       Ops.push_back(N->getOperand(i));
8943     }
8944     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8945     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
8946                                            Ops, MemInt->getMemoryVT(),
8947                                            MemInt->getMemOperand());
8948
8949     // Update the uses.
8950     std::vector<SDValue> NewResults;
8951     for (unsigned i = 0; i < NumResultVecs; ++i) {
8952       NewResults.push_back(SDValue(UpdN.getNode(), i));
8953     }
8954     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8955     DCI.CombineTo(N, NewResults);
8956     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8957
8958     break;
8959   }
8960   return SDValue();
8961 }
8962
8963 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
8964 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
8965 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
8966 /// return true.
8967 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8968   SelectionDAG &DAG = DCI.DAG;
8969   EVT VT = N->getValueType(0);
8970   // vldN-dup instructions only support 64-bit vectors for N > 1.
8971   if (!VT.is64BitVector())
8972     return false;
8973
8974   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
8975   SDNode *VLD = N->getOperand(0).getNode();
8976   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
8977     return false;
8978   unsigned NumVecs = 0;
8979   unsigned NewOpc = 0;
8980   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
8981   if (IntNo == Intrinsic::arm_neon_vld2lane) {
8982     NumVecs = 2;
8983     NewOpc = ARMISD::VLD2DUP;
8984   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
8985     NumVecs = 3;
8986     NewOpc = ARMISD::VLD3DUP;
8987   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
8988     NumVecs = 4;
8989     NewOpc = ARMISD::VLD4DUP;
8990   } else {
8991     return false;
8992   }
8993
8994   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
8995   // numbers match the load.
8996   unsigned VLDLaneNo =
8997     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
8998   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8999        UI != UE; ++UI) {
9000     // Ignore uses of the chain result.
9001     if (UI.getUse().getResNo() == NumVecs)
9002       continue;
9003     SDNode *User = *UI;
9004     if (User->getOpcode() != ARMISD::VDUPLANE ||
9005         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9006       return false;
9007   }
9008
9009   // Create the vldN-dup node.
9010   EVT Tys[5];
9011   unsigned n;
9012   for (n = 0; n < NumVecs; ++n)
9013     Tys[n] = VT;
9014   Tys[n] = MVT::Other;
9015   SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumVecs+1));
9016   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9017   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9018   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9019                                            Ops, VLDMemInt->getMemoryVT(),
9020                                            VLDMemInt->getMemOperand());
9021
9022   // Update the uses.
9023   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9024        UI != UE; ++UI) {
9025     unsigned ResNo = UI.getUse().getResNo();
9026     // Ignore uses of the chain result.
9027     if (ResNo == NumVecs)
9028       continue;
9029     SDNode *User = *UI;
9030     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9031   }
9032
9033   // Now the vldN-lane intrinsic is dead except for its chain result.
9034   // Update uses of the chain.
9035   std::vector<SDValue> VLDDupResults;
9036   for (unsigned n = 0; n < NumVecs; ++n)
9037     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9038   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9039   DCI.CombineTo(VLD, VLDDupResults);
9040
9041   return true;
9042 }
9043
9044 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9045 /// ARMISD::VDUPLANE.
9046 static SDValue PerformVDUPLANECombine(SDNode *N,
9047                                       TargetLowering::DAGCombinerInfo &DCI) {
9048   SDValue Op = N->getOperand(0);
9049
9050   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9051   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9052   if (CombineVLDDUP(N, DCI))
9053     return SDValue(N, 0);
9054
9055   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9056   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9057   while (Op.getOpcode() == ISD::BITCAST)
9058     Op = Op.getOperand(0);
9059   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9060     return SDValue();
9061
9062   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9063   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9064   // The canonical VMOV for a zero vector uses a 32-bit element size.
9065   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9066   unsigned EltBits;
9067   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9068     EltSize = 8;
9069   EVT VT = N->getValueType(0);
9070   if (EltSize > VT.getVectorElementType().getSizeInBits())
9071     return SDValue();
9072
9073   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9074 }
9075
9076 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9077 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9078 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9079 {
9080   integerPart cN;
9081   integerPart c0 = 0;
9082   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9083        I != E; I++) {
9084     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9085     if (!C)
9086       return false;
9087
9088     bool isExact;
9089     APFloat APF = C->getValueAPF();
9090     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9091         != APFloat::opOK || !isExact)
9092       return false;
9093
9094     c0 = (I == 0) ? cN : c0;
9095     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9096       return false;
9097   }
9098   C = c0;
9099   return true;
9100 }
9101
9102 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9103 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9104 /// when the VMUL has a constant operand that is a power of 2.
9105 ///
9106 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9107 ///  vmul.f32        d16, d17, d16
9108 ///  vcvt.s32.f32    d16, d16
9109 /// becomes:
9110 ///  vcvt.s32.f32    d16, d16, #3
9111 static SDValue PerformVCVTCombine(SDNode *N,
9112                                   TargetLowering::DAGCombinerInfo &DCI,
9113                                   const ARMSubtarget *Subtarget) {
9114   SelectionDAG &DAG = DCI.DAG;
9115   SDValue Op = N->getOperand(0);
9116
9117   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9118       Op.getOpcode() != ISD::FMUL)
9119     return SDValue();
9120
9121   uint64_t C;
9122   SDValue N0 = Op->getOperand(0);
9123   SDValue ConstVec = Op->getOperand(1);
9124   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9125
9126   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9127       !isConstVecPow2(ConstVec, isSigned, C))
9128     return SDValue();
9129
9130   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9131   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9132   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9133     // These instructions only exist converting from f32 to i32. We can handle
9134     // smaller integers by generating an extra truncate, but larger ones would
9135     // be lossy.
9136     return SDValue();
9137   }
9138
9139   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9140     Intrinsic::arm_neon_vcvtfp2fxu;
9141   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9142   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9143                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9144                                  DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9145                                  DAG.getConstant(Log2_64(C), MVT::i32));
9146
9147   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9148     FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9149
9150   return FixConv;
9151 }
9152
9153 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9154 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9155 /// when the VDIV has a constant operand that is a power of 2.
9156 ///
9157 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9158 ///  vcvt.f32.s32    d16, d16
9159 ///  vdiv.f32        d16, d17, d16
9160 /// becomes:
9161 ///  vcvt.f32.s32    d16, d16, #3
9162 static SDValue PerformVDIVCombine(SDNode *N,
9163                                   TargetLowering::DAGCombinerInfo &DCI,
9164                                   const ARMSubtarget *Subtarget) {
9165   SelectionDAG &DAG = DCI.DAG;
9166   SDValue Op = N->getOperand(0);
9167   unsigned OpOpcode = Op.getNode()->getOpcode();
9168
9169   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9170       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9171     return SDValue();
9172
9173   uint64_t C;
9174   SDValue ConstVec = N->getOperand(1);
9175   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9176
9177   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9178       !isConstVecPow2(ConstVec, isSigned, C))
9179     return SDValue();
9180
9181   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9182   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9183   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9184     // These instructions only exist converting from i32 to f32. We can handle
9185     // smaller integers by generating an extra extend, but larger ones would
9186     // be lossy.
9187     return SDValue();
9188   }
9189
9190   SDValue ConvInput = Op.getOperand(0);
9191   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9192   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9193     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9194                             SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9195                             ConvInput);
9196
9197   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9198     Intrinsic::arm_neon_vcvtfxu2fp;
9199   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9200                      Op.getValueType(),
9201                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
9202                      ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9203 }
9204
9205 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9206 /// operand of a vector shift operation, where all the elements of the
9207 /// build_vector must have the same constant integer value.
9208 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9209   // Ignore bit_converts.
9210   while (Op.getOpcode() == ISD::BITCAST)
9211     Op = Op.getOperand(0);
9212   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9213   APInt SplatBits, SplatUndef;
9214   unsigned SplatBitSize;
9215   bool HasAnyUndefs;
9216   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9217                                       HasAnyUndefs, ElementBits) ||
9218       SplatBitSize > ElementBits)
9219     return false;
9220   Cnt = SplatBits.getSExtValue();
9221   return true;
9222 }
9223
9224 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9225 /// operand of a vector shift left operation.  That value must be in the range:
9226 ///   0 <= Value < ElementBits for a left shift; or
9227 ///   0 <= Value <= ElementBits for a long left shift.
9228 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9229   assert(VT.isVector() && "vector shift count is not a vector type");
9230   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9231   if (! getVShiftImm(Op, ElementBits, Cnt))
9232     return false;
9233   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9234 }
9235
9236 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9237 /// operand of a vector shift right operation.  For a shift opcode, the value
9238 /// is positive, but for an intrinsic the value count must be negative. The
9239 /// absolute value must be in the range:
9240 ///   1 <= |Value| <= ElementBits for a right shift; or
9241 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9242 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9243                          int64_t &Cnt) {
9244   assert(VT.isVector() && "vector shift count is not a vector type");
9245   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9246   if (! getVShiftImm(Op, ElementBits, Cnt))
9247     return false;
9248   if (isIntrinsic)
9249     Cnt = -Cnt;
9250   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9251 }
9252
9253 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9254 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9255   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9256   switch (IntNo) {
9257   default:
9258     // Don't do anything for most intrinsics.
9259     break;
9260
9261   // Vector shifts: check for immediate versions and lower them.
9262   // Note: This is done during DAG combining instead of DAG legalizing because
9263   // the build_vectors for 64-bit vector element shift counts are generally
9264   // not legal, and it is hard to see their values after they get legalized to
9265   // loads from a constant pool.
9266   case Intrinsic::arm_neon_vshifts:
9267   case Intrinsic::arm_neon_vshiftu:
9268   case Intrinsic::arm_neon_vrshifts:
9269   case Intrinsic::arm_neon_vrshiftu:
9270   case Intrinsic::arm_neon_vrshiftn:
9271   case Intrinsic::arm_neon_vqshifts:
9272   case Intrinsic::arm_neon_vqshiftu:
9273   case Intrinsic::arm_neon_vqshiftsu:
9274   case Intrinsic::arm_neon_vqshiftns:
9275   case Intrinsic::arm_neon_vqshiftnu:
9276   case Intrinsic::arm_neon_vqshiftnsu:
9277   case Intrinsic::arm_neon_vqrshiftns:
9278   case Intrinsic::arm_neon_vqrshiftnu:
9279   case Intrinsic::arm_neon_vqrshiftnsu: {
9280     EVT VT = N->getOperand(1).getValueType();
9281     int64_t Cnt;
9282     unsigned VShiftOpc = 0;
9283
9284     switch (IntNo) {
9285     case Intrinsic::arm_neon_vshifts:
9286     case Intrinsic::arm_neon_vshiftu:
9287       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9288         VShiftOpc = ARMISD::VSHL;
9289         break;
9290       }
9291       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9292         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9293                      ARMISD::VSHRs : ARMISD::VSHRu);
9294         break;
9295       }
9296       return SDValue();
9297
9298     case Intrinsic::arm_neon_vrshifts:
9299     case Intrinsic::arm_neon_vrshiftu:
9300       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9301         break;
9302       return SDValue();
9303
9304     case Intrinsic::arm_neon_vqshifts:
9305     case Intrinsic::arm_neon_vqshiftu:
9306       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9307         break;
9308       return SDValue();
9309
9310     case Intrinsic::arm_neon_vqshiftsu:
9311       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9312         break;
9313       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9314
9315     case Intrinsic::arm_neon_vrshiftn:
9316     case Intrinsic::arm_neon_vqshiftns:
9317     case Intrinsic::arm_neon_vqshiftnu:
9318     case Intrinsic::arm_neon_vqshiftnsu:
9319     case Intrinsic::arm_neon_vqrshiftns:
9320     case Intrinsic::arm_neon_vqrshiftnu:
9321     case Intrinsic::arm_neon_vqrshiftnsu:
9322       // Narrowing shifts require an immediate right shift.
9323       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9324         break;
9325       llvm_unreachable("invalid shift count for narrowing vector shift "
9326                        "intrinsic");
9327
9328     default:
9329       llvm_unreachable("unhandled vector shift");
9330     }
9331
9332     switch (IntNo) {
9333     case Intrinsic::arm_neon_vshifts:
9334     case Intrinsic::arm_neon_vshiftu:
9335       // Opcode already set above.
9336       break;
9337     case Intrinsic::arm_neon_vrshifts:
9338       VShiftOpc = ARMISD::VRSHRs; break;
9339     case Intrinsic::arm_neon_vrshiftu:
9340       VShiftOpc = ARMISD::VRSHRu; break;
9341     case Intrinsic::arm_neon_vrshiftn:
9342       VShiftOpc = ARMISD::VRSHRN; break;
9343     case Intrinsic::arm_neon_vqshifts:
9344       VShiftOpc = ARMISD::VQSHLs; break;
9345     case Intrinsic::arm_neon_vqshiftu:
9346       VShiftOpc = ARMISD::VQSHLu; break;
9347     case Intrinsic::arm_neon_vqshiftsu:
9348       VShiftOpc = ARMISD::VQSHLsu; break;
9349     case Intrinsic::arm_neon_vqshiftns:
9350       VShiftOpc = ARMISD::VQSHRNs; break;
9351     case Intrinsic::arm_neon_vqshiftnu:
9352       VShiftOpc = ARMISD::VQSHRNu; break;
9353     case Intrinsic::arm_neon_vqshiftnsu:
9354       VShiftOpc = ARMISD::VQSHRNsu; break;
9355     case Intrinsic::arm_neon_vqrshiftns:
9356       VShiftOpc = ARMISD::VQRSHRNs; break;
9357     case Intrinsic::arm_neon_vqrshiftnu:
9358       VShiftOpc = ARMISD::VQRSHRNu; break;
9359     case Intrinsic::arm_neon_vqrshiftnsu:
9360       VShiftOpc = ARMISD::VQRSHRNsu; break;
9361     }
9362
9363     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9364                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9365   }
9366
9367   case Intrinsic::arm_neon_vshiftins: {
9368     EVT VT = N->getOperand(1).getValueType();
9369     int64_t Cnt;
9370     unsigned VShiftOpc = 0;
9371
9372     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9373       VShiftOpc = ARMISD::VSLI;
9374     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9375       VShiftOpc = ARMISD::VSRI;
9376     else {
9377       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9378     }
9379
9380     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9381                        N->getOperand(1), N->getOperand(2),
9382                        DAG.getConstant(Cnt, MVT::i32));
9383   }
9384
9385   case Intrinsic::arm_neon_vqrshifts:
9386   case Intrinsic::arm_neon_vqrshiftu:
9387     // No immediate versions of these to check for.
9388     break;
9389   }
9390
9391   return SDValue();
9392 }
9393
9394 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9395 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9396 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9397 /// vector element shift counts are generally not legal, and it is hard to see
9398 /// their values after they get legalized to loads from a constant pool.
9399 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9400                                    const ARMSubtarget *ST) {
9401   EVT VT = N->getValueType(0);
9402   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9403     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9404     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9405     SDValue N1 = N->getOperand(1);
9406     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9407       SDValue N0 = N->getOperand(0);
9408       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9409           DAG.MaskedValueIsZero(N0.getOperand(0),
9410                                 APInt::getHighBitsSet(32, 16)))
9411         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9412     }
9413   }
9414
9415   // Nothing to be done for scalar shifts.
9416   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9417   if (!VT.isVector() || !TLI.isTypeLegal(VT))
9418     return SDValue();
9419
9420   assert(ST->hasNEON() && "unexpected vector shift");
9421   int64_t Cnt;
9422
9423   switch (N->getOpcode()) {
9424   default: llvm_unreachable("unexpected shift opcode");
9425
9426   case ISD::SHL:
9427     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9428       return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9429                          DAG.getConstant(Cnt, MVT::i32));
9430     break;
9431
9432   case ISD::SRA:
9433   case ISD::SRL:
9434     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9435       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9436                             ARMISD::VSHRs : ARMISD::VSHRu);
9437       return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9438                          DAG.getConstant(Cnt, MVT::i32));
9439     }
9440   }
9441   return SDValue();
9442 }
9443
9444 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9445 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9446 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9447                                     const ARMSubtarget *ST) {
9448   SDValue N0 = N->getOperand(0);
9449
9450   // Check for sign- and zero-extensions of vector extract operations of 8-
9451   // and 16-bit vector elements.  NEON supports these directly.  They are
9452   // handled during DAG combining because type legalization will promote them
9453   // to 32-bit types and it is messy to recognize the operations after that.
9454   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9455     SDValue Vec = N0.getOperand(0);
9456     SDValue Lane = N0.getOperand(1);
9457     EVT VT = N->getValueType(0);
9458     EVT EltVT = N0.getValueType();
9459     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9460
9461     if (VT == MVT::i32 &&
9462         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9463         TLI.isTypeLegal(Vec.getValueType()) &&
9464         isa<ConstantSDNode>(Lane)) {
9465
9466       unsigned Opc = 0;
9467       switch (N->getOpcode()) {
9468       default: llvm_unreachable("unexpected opcode");
9469       case ISD::SIGN_EXTEND:
9470         Opc = ARMISD::VGETLANEs;
9471         break;
9472       case ISD::ZERO_EXTEND:
9473       case ISD::ANY_EXTEND:
9474         Opc = ARMISD::VGETLANEu;
9475         break;
9476       }
9477       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9478     }
9479   }
9480
9481   return SDValue();
9482 }
9483
9484 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9485 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9486 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9487                                        const ARMSubtarget *ST) {
9488   // If the target supports NEON, try to use vmax/vmin instructions for f32
9489   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
9490   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
9491   // a NaN; only do the transformation when it matches that behavior.
9492
9493   // For now only do this when using NEON for FP operations; if using VFP, it
9494   // is not obvious that the benefit outweighs the cost of switching to the
9495   // NEON pipeline.
9496   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9497       N->getValueType(0) != MVT::f32)
9498     return SDValue();
9499
9500   SDValue CondLHS = N->getOperand(0);
9501   SDValue CondRHS = N->getOperand(1);
9502   SDValue LHS = N->getOperand(2);
9503   SDValue RHS = N->getOperand(3);
9504   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9505
9506   unsigned Opcode = 0;
9507   bool IsReversed;
9508   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9509     IsReversed = false; // x CC y ? x : y
9510   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9511     IsReversed = true ; // x CC y ? y : x
9512   } else {
9513     return SDValue();
9514   }
9515
9516   bool IsUnordered;
9517   switch (CC) {
9518   default: break;
9519   case ISD::SETOLT:
9520   case ISD::SETOLE:
9521   case ISD::SETLT:
9522   case ISD::SETLE:
9523   case ISD::SETULT:
9524   case ISD::SETULE:
9525     // If LHS is NaN, an ordered comparison will be false and the result will
9526     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
9527     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9528     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9529     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9530       break;
9531     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9532     // will return -0, so vmin can only be used for unsafe math or if one of
9533     // the operands is known to be nonzero.
9534     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9535         !DAG.getTarget().Options.UnsafeFPMath &&
9536         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9537       break;
9538     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9539     break;
9540
9541   case ISD::SETOGT:
9542   case ISD::SETOGE:
9543   case ISD::SETGT:
9544   case ISD::SETGE:
9545   case ISD::SETUGT:
9546   case ISD::SETUGE:
9547     // If LHS is NaN, an ordered comparison will be false and the result will
9548     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
9549     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9550     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9551     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9552       break;
9553     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9554     // will return +0, so vmax can only be used for unsafe math or if one of
9555     // the operands is known to be nonzero.
9556     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9557         !DAG.getTarget().Options.UnsafeFPMath &&
9558         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9559       break;
9560     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9561     break;
9562   }
9563
9564   if (!Opcode)
9565     return SDValue();
9566   return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9567 }
9568
9569 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9570 SDValue
9571 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9572   SDValue Cmp = N->getOperand(4);
9573   if (Cmp.getOpcode() != ARMISD::CMPZ)
9574     // Only looking at EQ and NE cases.
9575     return SDValue();
9576
9577   EVT VT = N->getValueType(0);
9578   SDLoc dl(N);
9579   SDValue LHS = Cmp.getOperand(0);
9580   SDValue RHS = Cmp.getOperand(1);
9581   SDValue FalseVal = N->getOperand(0);
9582   SDValue TrueVal = N->getOperand(1);
9583   SDValue ARMcc = N->getOperand(2);
9584   ARMCC::CondCodes CC =
9585     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9586
9587   // Simplify
9588   //   mov     r1, r0
9589   //   cmp     r1, x
9590   //   mov     r0, y
9591   //   moveq   r0, x
9592   // to
9593   //   cmp     r0, x
9594   //   movne   r0, y
9595   //
9596   //   mov     r1, r0
9597   //   cmp     r1, x
9598   //   mov     r0, x
9599   //   movne   r0, y
9600   // to
9601   //   cmp     r0, x
9602   //   movne   r0, y
9603   /// FIXME: Turn this into a target neutral optimization?
9604   SDValue Res;
9605   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9606     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9607                       N->getOperand(3), Cmp);
9608   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9609     SDValue ARMcc;
9610     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9611     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9612                       N->getOperand(3), NewCmp);
9613   }
9614
9615   if (Res.getNode()) {
9616     APInt KnownZero, KnownOne;
9617     DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
9618     // Capture demanded bits information that would be otherwise lost.
9619     if (KnownZero == 0xfffffffe)
9620       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9621                         DAG.getValueType(MVT::i1));
9622     else if (KnownZero == 0xffffff00)
9623       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9624                         DAG.getValueType(MVT::i8));
9625     else if (KnownZero == 0xffff0000)
9626       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9627                         DAG.getValueType(MVT::i16));
9628   }
9629
9630   return Res;
9631 }
9632
9633 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9634                                              DAGCombinerInfo &DCI) const {
9635   switch (N->getOpcode()) {
9636   default: break;
9637   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
9638   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
9639   case ISD::SUB:        return PerformSUBCombine(N, DCI);
9640   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
9641   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
9642   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
9643   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
9644   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
9645   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
9646   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9647   case ISD::STORE:      return PerformSTORECombine(N, DCI);
9648   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
9649   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9650   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9651   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9652   case ISD::FP_TO_SINT:
9653   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9654   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
9655   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9656   case ISD::SHL:
9657   case ISD::SRA:
9658   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
9659   case ISD::SIGN_EXTEND:
9660   case ISD::ZERO_EXTEND:
9661   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9662   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9663   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9664   case ARMISD::VLD2DUP:
9665   case ARMISD::VLD3DUP:
9666   case ARMISD::VLD4DUP:
9667     return CombineBaseUpdate(N, DCI);
9668   case ARMISD::BUILD_VECTOR:
9669     return PerformARMBUILD_VECTORCombine(N, DCI);
9670   case ISD::INTRINSIC_VOID:
9671   case ISD::INTRINSIC_W_CHAIN:
9672     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9673     case Intrinsic::arm_neon_vld1:
9674     case Intrinsic::arm_neon_vld2:
9675     case Intrinsic::arm_neon_vld3:
9676     case Intrinsic::arm_neon_vld4:
9677     case Intrinsic::arm_neon_vld2lane:
9678     case Intrinsic::arm_neon_vld3lane:
9679     case Intrinsic::arm_neon_vld4lane:
9680     case Intrinsic::arm_neon_vst1:
9681     case Intrinsic::arm_neon_vst2:
9682     case Intrinsic::arm_neon_vst3:
9683     case Intrinsic::arm_neon_vst4:
9684     case Intrinsic::arm_neon_vst2lane:
9685     case Intrinsic::arm_neon_vst3lane:
9686     case Intrinsic::arm_neon_vst4lane:
9687       return CombineBaseUpdate(N, DCI);
9688     default: break;
9689     }
9690     break;
9691   }
9692   return SDValue();
9693 }
9694
9695 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9696                                                           EVT VT) const {
9697   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9698 }
9699
9700 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, unsigned,
9701                                                       bool *Fast) const {
9702   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9703   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9704
9705   switch (VT.getSimpleVT().SimpleTy) {
9706   default:
9707     return false;
9708   case MVT::i8:
9709   case MVT::i16:
9710   case MVT::i32: {
9711     // Unaligned access can use (for example) LRDB, LRDH, LDR
9712     if (AllowsUnaligned) {
9713       if (Fast)
9714         *Fast = Subtarget->hasV7Ops();
9715       return true;
9716     }
9717     return false;
9718   }
9719   case MVT::f64:
9720   case MVT::v2f64: {
9721     // For any little-endian targets with neon, we can support unaligned ld/st
9722     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9723     // A big-endian target may also explicitly support unaligned accesses
9724     if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9725       if (Fast)
9726         *Fast = true;
9727       return true;
9728     }
9729     return false;
9730   }
9731   }
9732 }
9733
9734 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9735                        unsigned AlignCheck) {
9736   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9737           (DstAlign == 0 || DstAlign % AlignCheck == 0));
9738 }
9739
9740 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9741                                            unsigned DstAlign, unsigned SrcAlign,
9742                                            bool IsMemset, bool ZeroMemset,
9743                                            bool MemcpyStrSrc,
9744                                            MachineFunction &MF) const {
9745   const Function *F = MF.getFunction();
9746
9747   // See if we can use NEON instructions for this...
9748   if ((!IsMemset || ZeroMemset) &&
9749       Subtarget->hasNEON() &&
9750       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
9751                                        Attribute::NoImplicitFloat)) {
9752     bool Fast;
9753     if (Size >= 16 &&
9754         (memOpAlign(SrcAlign, DstAlign, 16) ||
9755          (allowsUnalignedMemoryAccesses(MVT::v2f64, 0, &Fast) && Fast))) {
9756       return MVT::v2f64;
9757     } else if (Size >= 8 &&
9758                (memOpAlign(SrcAlign, DstAlign, 8) ||
9759                 (allowsUnalignedMemoryAccesses(MVT::f64, 0, &Fast) && Fast))) {
9760       return MVT::f64;
9761     }
9762   }
9763
9764   // Lowering to i32/i16 if the size permits.
9765   if (Size >= 4)
9766     return MVT::i32;
9767   else if (Size >= 2)
9768     return MVT::i16;
9769
9770   // Let the target-independent logic figure it out.
9771   return MVT::Other;
9772 }
9773
9774 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9775   if (Val.getOpcode() != ISD::LOAD)
9776     return false;
9777
9778   EVT VT1 = Val.getValueType();
9779   if (!VT1.isSimple() || !VT1.isInteger() ||
9780       !VT2.isSimple() || !VT2.isInteger())
9781     return false;
9782
9783   switch (VT1.getSimpleVT().SimpleTy) {
9784   default: break;
9785   case MVT::i1:
9786   case MVT::i8:
9787   case MVT::i16:
9788     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
9789     return true;
9790   }
9791
9792   return false;
9793 }
9794
9795 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
9796   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9797     return false;
9798
9799   if (!isTypeLegal(EVT::getEVT(Ty1)))
9800     return false;
9801
9802   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
9803
9804   // Assuming the caller doesn't have a zeroext or signext return parameter,
9805   // truncation all the way down to i1 is valid.
9806   return true;
9807 }
9808
9809
9810 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9811   if (V < 0)
9812     return false;
9813
9814   unsigned Scale = 1;
9815   switch (VT.getSimpleVT().SimpleTy) {
9816   default: return false;
9817   case MVT::i1:
9818   case MVT::i8:
9819     // Scale == 1;
9820     break;
9821   case MVT::i16:
9822     // Scale == 2;
9823     Scale = 2;
9824     break;
9825   case MVT::i32:
9826     // Scale == 4;
9827     Scale = 4;
9828     break;
9829   }
9830
9831   if ((V & (Scale - 1)) != 0)
9832     return false;
9833   V /= Scale;
9834   return V == (V & ((1LL << 5) - 1));
9835 }
9836
9837 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
9838                                       const ARMSubtarget *Subtarget) {
9839   bool isNeg = false;
9840   if (V < 0) {
9841     isNeg = true;
9842     V = - V;
9843   }
9844
9845   switch (VT.getSimpleVT().SimpleTy) {
9846   default: return false;
9847   case MVT::i1:
9848   case MVT::i8:
9849   case MVT::i16:
9850   case MVT::i32:
9851     // + imm12 or - imm8
9852     if (isNeg)
9853       return V == (V & ((1LL << 8) - 1));
9854     return V == (V & ((1LL << 12) - 1));
9855   case MVT::f32:
9856   case MVT::f64:
9857     // Same as ARM mode. FIXME: NEON?
9858     if (!Subtarget->hasVFP2())
9859       return false;
9860     if ((V & 3) != 0)
9861       return false;
9862     V >>= 2;
9863     return V == (V & ((1LL << 8) - 1));
9864   }
9865 }
9866
9867 /// isLegalAddressImmediate - Return true if the integer value can be used
9868 /// as the offset of the target addressing mode for load / store of the
9869 /// given type.
9870 static bool isLegalAddressImmediate(int64_t V, EVT VT,
9871                                     const ARMSubtarget *Subtarget) {
9872   if (V == 0)
9873     return true;
9874
9875   if (!VT.isSimple())
9876     return false;
9877
9878   if (Subtarget->isThumb1Only())
9879     return isLegalT1AddressImmediate(V, VT);
9880   else if (Subtarget->isThumb2())
9881     return isLegalT2AddressImmediate(V, VT, Subtarget);
9882
9883   // ARM mode.
9884   if (V < 0)
9885     V = - V;
9886   switch (VT.getSimpleVT().SimpleTy) {
9887   default: return false;
9888   case MVT::i1:
9889   case MVT::i8:
9890   case MVT::i32:
9891     // +- imm12
9892     return V == (V & ((1LL << 12) - 1));
9893   case MVT::i16:
9894     // +- imm8
9895     return V == (V & ((1LL << 8) - 1));
9896   case MVT::f32:
9897   case MVT::f64:
9898     if (!Subtarget->hasVFP2()) // FIXME: NEON?
9899       return false;
9900     if ((V & 3) != 0)
9901       return false;
9902     V >>= 2;
9903     return V == (V & ((1LL << 8) - 1));
9904   }
9905 }
9906
9907 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
9908                                                       EVT VT) const {
9909   int Scale = AM.Scale;
9910   if (Scale < 0)
9911     return false;
9912
9913   switch (VT.getSimpleVT().SimpleTy) {
9914   default: return false;
9915   case MVT::i1:
9916   case MVT::i8:
9917   case MVT::i16:
9918   case MVT::i32:
9919     if (Scale == 1)
9920       return true;
9921     // r + r << imm
9922     Scale = Scale & ~1;
9923     return Scale == 2 || Scale == 4 || Scale == 8;
9924   case MVT::i64:
9925     // r + r
9926     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9927       return true;
9928     return false;
9929   case MVT::isVoid:
9930     // Note, we allow "void" uses (basically, uses that aren't loads or
9931     // stores), because arm allows folding a scale into many arithmetic
9932     // operations.  This should be made more precise and revisited later.
9933
9934     // Allow r << imm, but the imm has to be a multiple of two.
9935     if (Scale & 1) return false;
9936     return isPowerOf2_32(Scale);
9937   }
9938 }
9939
9940 /// isLegalAddressingMode - Return true if the addressing mode represented
9941 /// by AM is legal for this target, for a load/store of the specified type.
9942 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9943                                               Type *Ty) const {
9944   EVT VT = getValueType(Ty, true);
9945   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
9946     return false;
9947
9948   // Can never fold addr of global into load/store.
9949   if (AM.BaseGV)
9950     return false;
9951
9952   switch (AM.Scale) {
9953   case 0:  // no scale reg, must be "r+i" or "r", or "i".
9954     break;
9955   case 1:
9956     if (Subtarget->isThumb1Only())
9957       return false;
9958     // FALL THROUGH.
9959   default:
9960     // ARM doesn't support any R+R*scale+imm addr modes.
9961     if (AM.BaseOffs)
9962       return false;
9963
9964     if (!VT.isSimple())
9965       return false;
9966
9967     if (Subtarget->isThumb2())
9968       return isLegalT2ScaledAddressingMode(AM, VT);
9969
9970     int Scale = AM.Scale;
9971     switch (VT.getSimpleVT().SimpleTy) {
9972     default: return false;
9973     case MVT::i1:
9974     case MVT::i8:
9975     case MVT::i32:
9976       if (Scale < 0) Scale = -Scale;
9977       if (Scale == 1)
9978         return true;
9979       // r + r << imm
9980       return isPowerOf2_32(Scale & ~1);
9981     case MVT::i16:
9982     case MVT::i64:
9983       // r + r
9984       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9985         return true;
9986       return false;
9987
9988     case MVT::isVoid:
9989       // Note, we allow "void" uses (basically, uses that aren't loads or
9990       // stores), because arm allows folding a scale into many arithmetic
9991       // operations.  This should be made more precise and revisited later.
9992
9993       // Allow r << imm, but the imm has to be a multiple of two.
9994       if (Scale & 1) return false;
9995       return isPowerOf2_32(Scale);
9996     }
9997   }
9998   return true;
9999 }
10000
10001 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10002 /// icmp immediate, that is the target has icmp instructions which can compare
10003 /// a register against the immediate without having to materialize the
10004 /// immediate into a register.
10005 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10006   // Thumb2 and ARM modes can use cmn for negative immediates.
10007   if (!Subtarget->isThumb())
10008     return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
10009   if (Subtarget->isThumb2())
10010     return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
10011   // Thumb1 doesn't have cmn, and only 8-bit immediates.
10012   return Imm >= 0 && Imm <= 255;
10013 }
10014
10015 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10016 /// *or sub* immediate, that is the target has add or sub instructions which can
10017 /// add a register with the immediate without having to materialize the
10018 /// immediate into a register.
10019 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10020   // Same encoding for add/sub, just flip the sign.
10021   int64_t AbsImm = llvm::abs64(Imm);
10022   if (!Subtarget->isThumb())
10023     return ARM_AM::getSOImmVal(AbsImm) != -1;
10024   if (Subtarget->isThumb2())
10025     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10026   // Thumb1 only has 8-bit unsigned immediate.
10027   return AbsImm >= 0 && AbsImm <= 255;
10028 }
10029
10030 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10031                                       bool isSEXTLoad, SDValue &Base,
10032                                       SDValue &Offset, bool &isInc,
10033                                       SelectionDAG &DAG) {
10034   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10035     return false;
10036
10037   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10038     // AddressingMode 3
10039     Base = Ptr->getOperand(0);
10040     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10041       int RHSC = (int)RHS->getZExtValue();
10042       if (RHSC < 0 && RHSC > -256) {
10043         assert(Ptr->getOpcode() == ISD::ADD);
10044         isInc = false;
10045         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10046         return true;
10047       }
10048     }
10049     isInc = (Ptr->getOpcode() == ISD::ADD);
10050     Offset = Ptr->getOperand(1);
10051     return true;
10052   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10053     // AddressingMode 2
10054     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10055       int RHSC = (int)RHS->getZExtValue();
10056       if (RHSC < 0 && RHSC > -0x1000) {
10057         assert(Ptr->getOpcode() == ISD::ADD);
10058         isInc = false;
10059         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10060         Base = Ptr->getOperand(0);
10061         return true;
10062       }
10063     }
10064
10065     if (Ptr->getOpcode() == ISD::ADD) {
10066       isInc = true;
10067       ARM_AM::ShiftOpc ShOpcVal=
10068         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10069       if (ShOpcVal != ARM_AM::no_shift) {
10070         Base = Ptr->getOperand(1);
10071         Offset = Ptr->getOperand(0);
10072       } else {
10073         Base = Ptr->getOperand(0);
10074         Offset = Ptr->getOperand(1);
10075       }
10076       return true;
10077     }
10078
10079     isInc = (Ptr->getOpcode() == ISD::ADD);
10080     Base = Ptr->getOperand(0);
10081     Offset = Ptr->getOperand(1);
10082     return true;
10083   }
10084
10085   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10086   return false;
10087 }
10088
10089 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10090                                      bool isSEXTLoad, SDValue &Base,
10091                                      SDValue &Offset, bool &isInc,
10092                                      SelectionDAG &DAG) {
10093   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10094     return false;
10095
10096   Base = Ptr->getOperand(0);
10097   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10098     int RHSC = (int)RHS->getZExtValue();
10099     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10100       assert(Ptr->getOpcode() == ISD::ADD);
10101       isInc = false;
10102       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10103       return true;
10104     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10105       isInc = Ptr->getOpcode() == ISD::ADD;
10106       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10107       return true;
10108     }
10109   }
10110
10111   return false;
10112 }
10113
10114 /// getPreIndexedAddressParts - returns true by value, base pointer and
10115 /// offset pointer and addressing mode by reference if the node's address
10116 /// can be legally represented as pre-indexed load / store address.
10117 bool
10118 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10119                                              SDValue &Offset,
10120                                              ISD::MemIndexedMode &AM,
10121                                              SelectionDAG &DAG) const {
10122   if (Subtarget->isThumb1Only())
10123     return false;
10124
10125   EVT VT;
10126   SDValue Ptr;
10127   bool isSEXTLoad = false;
10128   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10129     Ptr = LD->getBasePtr();
10130     VT  = LD->getMemoryVT();
10131     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10132   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10133     Ptr = ST->getBasePtr();
10134     VT  = ST->getMemoryVT();
10135   } else
10136     return false;
10137
10138   bool isInc;
10139   bool isLegal = false;
10140   if (Subtarget->isThumb2())
10141     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10142                                        Offset, isInc, DAG);
10143   else
10144     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10145                                         Offset, isInc, DAG);
10146   if (!isLegal)
10147     return false;
10148
10149   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10150   return true;
10151 }
10152
10153 /// getPostIndexedAddressParts - returns true by value, base pointer and
10154 /// offset pointer and addressing mode by reference if this node can be
10155 /// combined with a load / store to form a post-indexed load / store.
10156 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10157                                                    SDValue &Base,
10158                                                    SDValue &Offset,
10159                                                    ISD::MemIndexedMode &AM,
10160                                                    SelectionDAG &DAG) const {
10161   if (Subtarget->isThumb1Only())
10162     return false;
10163
10164   EVT VT;
10165   SDValue Ptr;
10166   bool isSEXTLoad = false;
10167   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10168     VT  = LD->getMemoryVT();
10169     Ptr = LD->getBasePtr();
10170     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10171   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10172     VT  = ST->getMemoryVT();
10173     Ptr = ST->getBasePtr();
10174   } else
10175     return false;
10176
10177   bool isInc;
10178   bool isLegal = false;
10179   if (Subtarget->isThumb2())
10180     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10181                                        isInc, DAG);
10182   else
10183     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10184                                         isInc, DAG);
10185   if (!isLegal)
10186     return false;
10187
10188   if (Ptr != Base) {
10189     // Swap base ptr and offset to catch more post-index load / store when
10190     // it's legal. In Thumb2 mode, offset must be an immediate.
10191     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10192         !Subtarget->isThumb2())
10193       std::swap(Base, Offset);
10194
10195     // Post-indexed load / store update the base pointer.
10196     if (Ptr != Base)
10197       return false;
10198   }
10199
10200   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10201   return true;
10202 }
10203
10204 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10205                                                       APInt &KnownZero,
10206                                                       APInt &KnownOne,
10207                                                       const SelectionDAG &DAG,
10208                                                       unsigned Depth) const {
10209   unsigned BitWidth = KnownOne.getBitWidth();
10210   KnownZero = KnownOne = APInt(BitWidth, 0);
10211   switch (Op.getOpcode()) {
10212   default: break;
10213   case ARMISD::ADDC:
10214   case ARMISD::ADDE:
10215   case ARMISD::SUBC:
10216   case ARMISD::SUBE:
10217     // These nodes' second result is a boolean
10218     if (Op.getResNo() == 0)
10219       break;
10220     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10221     break;
10222   case ARMISD::CMOV: {
10223     // Bits are known zero/one if known on the LHS and RHS.
10224     DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10225     if (KnownZero == 0 && KnownOne == 0) return;
10226
10227     APInt KnownZeroRHS, KnownOneRHS;
10228     DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10229     KnownZero &= KnownZeroRHS;
10230     KnownOne  &= KnownOneRHS;
10231     return;
10232   }
10233   case ISD::INTRINSIC_W_CHAIN: {
10234     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10235     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10236     switch (IntID) {
10237     default: return;
10238     case Intrinsic::arm_ldaex:
10239     case Intrinsic::arm_ldrex: {
10240       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10241       unsigned MemBits = VT.getScalarType().getSizeInBits();
10242       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10243       return;
10244     }
10245     }
10246   }
10247   }
10248 }
10249
10250 //===----------------------------------------------------------------------===//
10251 //                           ARM Inline Assembly Support
10252 //===----------------------------------------------------------------------===//
10253
10254 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10255   // Looking for "rev" which is V6+.
10256   if (!Subtarget->hasV6Ops())
10257     return false;
10258
10259   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10260   std::string AsmStr = IA->getAsmString();
10261   SmallVector<StringRef, 4> AsmPieces;
10262   SplitString(AsmStr, AsmPieces, ";\n");
10263
10264   switch (AsmPieces.size()) {
10265   default: return false;
10266   case 1:
10267     AsmStr = AsmPieces[0];
10268     AsmPieces.clear();
10269     SplitString(AsmStr, AsmPieces, " \t,");
10270
10271     // rev $0, $1
10272     if (AsmPieces.size() == 3 &&
10273         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10274         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10275       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10276       if (Ty && Ty->getBitWidth() == 32)
10277         return IntrinsicLowering::LowerToByteSwap(CI);
10278     }
10279     break;
10280   }
10281
10282   return false;
10283 }
10284
10285 /// getConstraintType - Given a constraint letter, return the type of
10286 /// constraint it is for this target.
10287 ARMTargetLowering::ConstraintType
10288 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10289   if (Constraint.size() == 1) {
10290     switch (Constraint[0]) {
10291     default:  break;
10292     case 'l': return C_RegisterClass;
10293     case 'w': return C_RegisterClass;
10294     case 'h': return C_RegisterClass;
10295     case 'x': return C_RegisterClass;
10296     case 't': return C_RegisterClass;
10297     case 'j': return C_Other; // Constant for movw.
10298       // An address with a single base register. Due to the way we
10299       // currently handle addresses it is the same as an 'r' memory constraint.
10300     case 'Q': return C_Memory;
10301     }
10302   } else if (Constraint.size() == 2) {
10303     switch (Constraint[0]) {
10304     default: break;
10305     // All 'U+' constraints are addresses.
10306     case 'U': return C_Memory;
10307     }
10308   }
10309   return TargetLowering::getConstraintType(Constraint);
10310 }
10311
10312 /// Examine constraint type and operand type and determine a weight value.
10313 /// This object must already have been set up with the operand type
10314 /// and the current alternative constraint selected.
10315 TargetLowering::ConstraintWeight
10316 ARMTargetLowering::getSingleConstraintMatchWeight(
10317     AsmOperandInfo &info, const char *constraint) const {
10318   ConstraintWeight weight = CW_Invalid;
10319   Value *CallOperandVal = info.CallOperandVal;
10320     // If we don't have a value, we can't do a match,
10321     // but allow it at the lowest weight.
10322   if (!CallOperandVal)
10323     return CW_Default;
10324   Type *type = CallOperandVal->getType();
10325   // Look at the constraint type.
10326   switch (*constraint) {
10327   default:
10328     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10329     break;
10330   case 'l':
10331     if (type->isIntegerTy()) {
10332       if (Subtarget->isThumb())
10333         weight = CW_SpecificReg;
10334       else
10335         weight = CW_Register;
10336     }
10337     break;
10338   case 'w':
10339     if (type->isFloatingPointTy())
10340       weight = CW_Register;
10341     break;
10342   }
10343   return weight;
10344 }
10345
10346 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10347 RCPair
10348 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10349                                                 MVT VT) const {
10350   if (Constraint.size() == 1) {
10351     // GCC ARM Constraint Letters
10352     switch (Constraint[0]) {
10353     case 'l': // Low regs or general regs.
10354       if (Subtarget->isThumb())
10355         return RCPair(0U, &ARM::tGPRRegClass);
10356       return RCPair(0U, &ARM::GPRRegClass);
10357     case 'h': // High regs or no regs.
10358       if (Subtarget->isThumb())
10359         return RCPair(0U, &ARM::hGPRRegClass);
10360       break;
10361     case 'r':
10362       return RCPair(0U, &ARM::GPRRegClass);
10363     case 'w':
10364       if (VT == MVT::Other)
10365         break;
10366       if (VT == MVT::f32)
10367         return RCPair(0U, &ARM::SPRRegClass);
10368       if (VT.getSizeInBits() == 64)
10369         return RCPair(0U, &ARM::DPRRegClass);
10370       if (VT.getSizeInBits() == 128)
10371         return RCPair(0U, &ARM::QPRRegClass);
10372       break;
10373     case 'x':
10374       if (VT == MVT::Other)
10375         break;
10376       if (VT == MVT::f32)
10377         return RCPair(0U, &ARM::SPR_8RegClass);
10378       if (VT.getSizeInBits() == 64)
10379         return RCPair(0U, &ARM::DPR_8RegClass);
10380       if (VT.getSizeInBits() == 128)
10381         return RCPair(0U, &ARM::QPR_8RegClass);
10382       break;
10383     case 't':
10384       if (VT == MVT::f32)
10385         return RCPair(0U, &ARM::SPRRegClass);
10386       break;
10387     }
10388   }
10389   if (StringRef("{cc}").equals_lower(Constraint))
10390     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10391
10392   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10393 }
10394
10395 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10396 /// vector.  If it is invalid, don't add anything to Ops.
10397 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10398                                                      std::string &Constraint,
10399                                                      std::vector<SDValue>&Ops,
10400                                                      SelectionDAG &DAG) const {
10401   SDValue Result;
10402
10403   // Currently only support length 1 constraints.
10404   if (Constraint.length() != 1) return;
10405
10406   char ConstraintLetter = Constraint[0];
10407   switch (ConstraintLetter) {
10408   default: break;
10409   case 'j':
10410   case 'I': case 'J': case 'K': case 'L':
10411   case 'M': case 'N': case 'O':
10412     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10413     if (!C)
10414       return;
10415
10416     int64_t CVal64 = C->getSExtValue();
10417     int CVal = (int) CVal64;
10418     // None of these constraints allow values larger than 32 bits.  Check
10419     // that the value fits in an int.
10420     if (CVal != CVal64)
10421       return;
10422
10423     switch (ConstraintLetter) {
10424       case 'j':
10425         // Constant suitable for movw, must be between 0 and
10426         // 65535.
10427         if (Subtarget->hasV6T2Ops())
10428           if (CVal >= 0 && CVal <= 65535)
10429             break;
10430         return;
10431       case 'I':
10432         if (Subtarget->isThumb1Only()) {
10433           // This must be a constant between 0 and 255, for ADD
10434           // immediates.
10435           if (CVal >= 0 && CVal <= 255)
10436             break;
10437         } else if (Subtarget->isThumb2()) {
10438           // A constant that can be used as an immediate value in a
10439           // data-processing instruction.
10440           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10441             break;
10442         } else {
10443           // A constant that can be used as an immediate value in a
10444           // data-processing instruction.
10445           if (ARM_AM::getSOImmVal(CVal) != -1)
10446             break;
10447         }
10448         return;
10449
10450       case 'J':
10451         if (Subtarget->isThumb()) {  // FIXME thumb2
10452           // This must be a constant between -255 and -1, for negated ADD
10453           // immediates. This can be used in GCC with an "n" modifier that
10454           // prints the negated value, for use with SUB instructions. It is
10455           // not useful otherwise but is implemented for compatibility.
10456           if (CVal >= -255 && CVal <= -1)
10457             break;
10458         } else {
10459           // This must be a constant between -4095 and 4095. It is not clear
10460           // what this constraint is intended for. Implemented for
10461           // compatibility with GCC.
10462           if (CVal >= -4095 && CVal <= 4095)
10463             break;
10464         }
10465         return;
10466
10467       case 'K':
10468         if (Subtarget->isThumb1Only()) {
10469           // A 32-bit value where only one byte has a nonzero value. Exclude
10470           // zero to match GCC. This constraint is used by GCC internally for
10471           // constants that can be loaded with a move/shift combination.
10472           // It is not useful otherwise but is implemented for compatibility.
10473           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10474             break;
10475         } else if (Subtarget->isThumb2()) {
10476           // A constant whose bitwise inverse can be used as an immediate
10477           // value in a data-processing instruction. This can be used in GCC
10478           // with a "B" modifier that prints the inverted value, for use with
10479           // BIC and MVN instructions. It is not useful otherwise but is
10480           // implemented for compatibility.
10481           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10482             break;
10483         } else {
10484           // A constant whose bitwise inverse can be used as an immediate
10485           // value in a data-processing instruction. This can be used in GCC
10486           // with a "B" modifier that prints the inverted value, for use with
10487           // BIC and MVN instructions. It is not useful otherwise but is
10488           // implemented for compatibility.
10489           if (ARM_AM::getSOImmVal(~CVal) != -1)
10490             break;
10491         }
10492         return;
10493
10494       case 'L':
10495         if (Subtarget->isThumb1Only()) {
10496           // This must be a constant between -7 and 7,
10497           // for 3-operand ADD/SUB immediate instructions.
10498           if (CVal >= -7 && CVal < 7)
10499             break;
10500         } else if (Subtarget->isThumb2()) {
10501           // A constant whose negation can be used as an immediate value in a
10502           // data-processing instruction. This can be used in GCC with an "n"
10503           // modifier that prints the negated value, for use with SUB
10504           // instructions. It is not useful otherwise but is implemented for
10505           // compatibility.
10506           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10507             break;
10508         } else {
10509           // A constant whose negation can be used as an immediate value in a
10510           // data-processing instruction. This can be used in GCC with an "n"
10511           // modifier that prints the negated value, for use with SUB
10512           // instructions. It is not useful otherwise but is implemented for
10513           // compatibility.
10514           if (ARM_AM::getSOImmVal(-CVal) != -1)
10515             break;
10516         }
10517         return;
10518
10519       case 'M':
10520         if (Subtarget->isThumb()) { // FIXME thumb2
10521           // This must be a multiple of 4 between 0 and 1020, for
10522           // ADD sp + immediate.
10523           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10524             break;
10525         } else {
10526           // A power of two or a constant between 0 and 32.  This is used in
10527           // GCC for the shift amount on shifted register operands, but it is
10528           // useful in general for any shift amounts.
10529           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10530             break;
10531         }
10532         return;
10533
10534       case 'N':
10535         if (Subtarget->isThumb()) {  // FIXME thumb2
10536           // This must be a constant between 0 and 31, for shift amounts.
10537           if (CVal >= 0 && CVal <= 31)
10538             break;
10539         }
10540         return;
10541
10542       case 'O':
10543         if (Subtarget->isThumb()) {  // FIXME thumb2
10544           // This must be a multiple of 4 between -508 and 508, for
10545           // ADD/SUB sp = sp + immediate.
10546           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10547             break;
10548         }
10549         return;
10550     }
10551     Result = DAG.getTargetConstant(CVal, Op.getValueType());
10552     break;
10553   }
10554
10555   if (Result.getNode()) {
10556     Ops.push_back(Result);
10557     return;
10558   }
10559   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10560 }
10561
10562 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10563   assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10564   unsigned Opcode = Op->getOpcode();
10565   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10566       "Invalid opcode for Div/Rem lowering");
10567   bool isSigned = (Opcode == ISD::SDIVREM);
10568   EVT VT = Op->getValueType(0);
10569   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10570
10571   RTLIB::Libcall LC;
10572   switch (VT.getSimpleVT().SimpleTy) {
10573   default: llvm_unreachable("Unexpected request for libcall!");
10574   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
10575   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10576   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10577   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10578   }
10579
10580   SDValue InChain = DAG.getEntryNode();
10581
10582   TargetLowering::ArgListTy Args;
10583   TargetLowering::ArgListEntry Entry;
10584   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
10585     EVT ArgVT = Op->getOperand(i).getValueType();
10586     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10587     Entry.Node = Op->getOperand(i);
10588     Entry.Ty = ArgTy;
10589     Entry.isSExt = isSigned;
10590     Entry.isZExt = !isSigned;
10591     Args.push_back(Entry);
10592   }
10593
10594   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
10595                                          getPointerTy());
10596
10597   Type *RetTy = (Type*)StructType::get(Ty, Ty, NULL);
10598
10599   SDLoc dl(Op);
10600   TargetLowering::CallLoweringInfo CLI(DAG);
10601   CLI.setDebugLoc(dl).setChain(InChain)
10602     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
10603     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
10604
10605   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
10606   return CallInfo.first;
10607 }
10608
10609 SDValue
10610 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
10611   assert(Subtarget->isTargetWindows() && "unsupported target platform");
10612   SDLoc DL(Op);
10613
10614   // Get the inputs.
10615   SDValue Chain = Op.getOperand(0);
10616   SDValue Size  = Op.getOperand(1);
10617
10618   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
10619                               DAG.getConstant(2, MVT::i32));
10620
10621   SDValue Flag;
10622   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
10623   Flag = Chain.getValue(1);
10624
10625   SDVTList NodeTys = DAG.getVTList(MVT::i32, MVT::Glue);
10626   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
10627
10628   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
10629   Chain = NewSP.getValue(1);
10630
10631   SDValue Ops[2] = { NewSP, Chain };
10632   return DAG.getMergeValues(Ops, DL);
10633 }
10634
10635 bool
10636 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10637   // The ARM target isn't yet aware of offsets.
10638   return false;
10639 }
10640
10641 bool ARM::isBitFieldInvertedMask(unsigned v) {
10642   if (v == 0xffffffff)
10643     return false;
10644
10645   // there can be 1's on either or both "outsides", all the "inside"
10646   // bits must be 0's
10647   unsigned TO = CountTrailingOnes_32(v);
10648   unsigned LO = CountLeadingOnes_32(v);
10649   v = (v >> TO) << TO;
10650   v = (v << LO) >> LO;
10651   return v == 0;
10652 }
10653
10654 /// isFPImmLegal - Returns true if the target can instruction select the
10655 /// specified FP immediate natively. If false, the legalizer will
10656 /// materialize the FP immediate as a load from a constant pool.
10657 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10658   if (!Subtarget->hasVFP3())
10659     return false;
10660   if (VT == MVT::f32)
10661     return ARM_AM::getFP32Imm(Imm) != -1;
10662   if (VT == MVT::f64)
10663     return ARM_AM::getFP64Imm(Imm) != -1;
10664   return false;
10665 }
10666
10667 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10668 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
10669 /// specified in the intrinsic calls.
10670 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10671                                            const CallInst &I,
10672                                            unsigned Intrinsic) const {
10673   switch (Intrinsic) {
10674   case Intrinsic::arm_neon_vld1:
10675   case Intrinsic::arm_neon_vld2:
10676   case Intrinsic::arm_neon_vld3:
10677   case Intrinsic::arm_neon_vld4:
10678   case Intrinsic::arm_neon_vld2lane:
10679   case Intrinsic::arm_neon_vld3lane:
10680   case Intrinsic::arm_neon_vld4lane: {
10681     Info.opc = ISD::INTRINSIC_W_CHAIN;
10682     // Conservatively set memVT to the entire set of vectors loaded.
10683     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10684     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10685     Info.ptrVal = I.getArgOperand(0);
10686     Info.offset = 0;
10687     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10688     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10689     Info.vol = false; // volatile loads with NEON intrinsics not supported
10690     Info.readMem = true;
10691     Info.writeMem = false;
10692     return true;
10693   }
10694   case Intrinsic::arm_neon_vst1:
10695   case Intrinsic::arm_neon_vst2:
10696   case Intrinsic::arm_neon_vst3:
10697   case Intrinsic::arm_neon_vst4:
10698   case Intrinsic::arm_neon_vst2lane:
10699   case Intrinsic::arm_neon_vst3lane:
10700   case Intrinsic::arm_neon_vst4lane: {
10701     Info.opc = ISD::INTRINSIC_VOID;
10702     // Conservatively set memVT to the entire set of vectors stored.
10703     unsigned NumElts = 0;
10704     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10705       Type *ArgTy = I.getArgOperand(ArgI)->getType();
10706       if (!ArgTy->isVectorTy())
10707         break;
10708       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10709     }
10710     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10711     Info.ptrVal = I.getArgOperand(0);
10712     Info.offset = 0;
10713     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10714     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10715     Info.vol = false; // volatile stores with NEON intrinsics not supported
10716     Info.readMem = false;
10717     Info.writeMem = true;
10718     return true;
10719   }
10720   case Intrinsic::arm_ldaex:
10721   case Intrinsic::arm_ldrex: {
10722     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
10723     Info.opc = ISD::INTRINSIC_W_CHAIN;
10724     Info.memVT = MVT::getVT(PtrTy->getElementType());
10725     Info.ptrVal = I.getArgOperand(0);
10726     Info.offset = 0;
10727     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10728     Info.vol = true;
10729     Info.readMem = true;
10730     Info.writeMem = false;
10731     return true;
10732   }
10733   case Intrinsic::arm_stlex:
10734   case Intrinsic::arm_strex: {
10735     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
10736     Info.opc = ISD::INTRINSIC_W_CHAIN;
10737     Info.memVT = MVT::getVT(PtrTy->getElementType());
10738     Info.ptrVal = I.getArgOperand(1);
10739     Info.offset = 0;
10740     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10741     Info.vol = true;
10742     Info.readMem = false;
10743     Info.writeMem = true;
10744     return true;
10745   }
10746   case Intrinsic::arm_stlexd:
10747   case Intrinsic::arm_strexd: {
10748     Info.opc = ISD::INTRINSIC_W_CHAIN;
10749     Info.memVT = MVT::i64;
10750     Info.ptrVal = I.getArgOperand(2);
10751     Info.offset = 0;
10752     Info.align = 8;
10753     Info.vol = true;
10754     Info.readMem = false;
10755     Info.writeMem = true;
10756     return true;
10757   }
10758   case Intrinsic::arm_ldaexd:
10759   case Intrinsic::arm_ldrexd: {
10760     Info.opc = ISD::INTRINSIC_W_CHAIN;
10761     Info.memVT = MVT::i64;
10762     Info.ptrVal = I.getArgOperand(0);
10763     Info.offset = 0;
10764     Info.align = 8;
10765     Info.vol = true;
10766     Info.readMem = true;
10767     Info.writeMem = false;
10768     return true;
10769   }
10770   default:
10771     break;
10772   }
10773
10774   return false;
10775 }
10776
10777 /// \brief Returns true if it is beneficial to convert a load of a constant
10778 /// to just the constant itself.
10779 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
10780                                                           Type *Ty) const {
10781   assert(Ty->isIntegerTy());
10782
10783   unsigned Bits = Ty->getPrimitiveSizeInBits();
10784   if (Bits == 0 || Bits > 32)
10785     return false;
10786   return true;
10787 }
10788
10789 bool ARMTargetLowering::shouldExpandAtomicInIR(Instruction *Inst) const {
10790   // Loads and stores less than 64-bits are already atomic; ones above that
10791   // are doomed anyway, so defer to the default libcall and blame the OS when
10792   // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
10793   // anything for those.
10794   bool IsMClass = Subtarget->isMClass();
10795   if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
10796     unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
10797     return Size == 64 && !IsMClass;
10798   } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
10799     return LI->getType()->getPrimitiveSizeInBits() == 64 && !IsMClass;
10800   }
10801
10802   // For the real atomic operations, we have ldrex/strex up to 32 bits,
10803   // and up to 64 bits on the non-M profiles
10804   unsigned AtomicLimit = IsMClass ? 32 : 64;
10805   return Inst->getType()->getPrimitiveSizeInBits() <= AtomicLimit;
10806 }
10807
10808 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
10809                                          AtomicOrdering Ord) const {
10810   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10811   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
10812   bool IsAcquire =
10813       Ord == Acquire || Ord == AcquireRelease || Ord == SequentiallyConsistent;
10814
10815   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
10816   // intrinsic must return {i32, i32} and we have to recombine them into a
10817   // single i64 here.
10818   if (ValTy->getPrimitiveSizeInBits() == 64) {
10819     Intrinsic::ID Int =
10820         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
10821     Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
10822
10823     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10824     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
10825
10826     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
10827     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
10828     if (!Subtarget->isLittle())
10829       std::swap (Lo, Hi);
10830     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
10831     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
10832     return Builder.CreateOr(
10833         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
10834   }
10835
10836   Type *Tys[] = { Addr->getType() };
10837   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
10838   Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
10839
10840   return Builder.CreateTruncOrBitCast(
10841       Builder.CreateCall(Ldrex, Addr),
10842       cast<PointerType>(Addr->getType())->getElementType());
10843 }
10844
10845 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
10846                                                Value *Addr,
10847                                                AtomicOrdering Ord) const {
10848   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10849   bool IsRelease =
10850       Ord == Release || Ord == AcquireRelease || Ord == SequentiallyConsistent;
10851
10852   // Since the intrinsics must have legal type, the i64 intrinsics take two
10853   // parameters: "i32, i32". We must marshal Val into the appropriate form
10854   // before the call.
10855   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
10856     Intrinsic::ID Int =
10857         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
10858     Function *Strex = Intrinsic::getDeclaration(M, Int);
10859     Type *Int32Ty = Type::getInt32Ty(M->getContext());
10860
10861     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
10862     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
10863     if (!Subtarget->isLittle())
10864       std::swap (Lo, Hi);
10865     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10866     return Builder.CreateCall3(Strex, Lo, Hi, Addr);
10867   }
10868
10869   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
10870   Type *Tys[] = { Addr->getType() };
10871   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
10872
10873   return Builder.CreateCall2(
10874       Strex, Builder.CreateZExtOrBitCast(
10875                  Val, Strex->getFunctionType()->getParamType(0)),
10876       Addr);
10877 }
10878
10879 enum HABaseType {
10880   HA_UNKNOWN = 0,
10881   HA_FLOAT,
10882   HA_DOUBLE,
10883   HA_VECT64,
10884   HA_VECT128
10885 };
10886
10887 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
10888                                    uint64_t &Members) {
10889   if (const StructType *ST = dyn_cast<StructType>(Ty)) {
10890     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
10891       uint64_t SubMembers = 0;
10892       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
10893         return false;
10894       Members += SubMembers;
10895     }
10896   } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
10897     uint64_t SubMembers = 0;
10898     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
10899       return false;
10900     Members += SubMembers * AT->getNumElements();
10901   } else if (Ty->isFloatTy()) {
10902     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
10903       return false;
10904     Members = 1;
10905     Base = HA_FLOAT;
10906   } else if (Ty->isDoubleTy()) {
10907     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
10908       return false;
10909     Members = 1;
10910     Base = HA_DOUBLE;
10911   } else if (const VectorType *VT = dyn_cast<VectorType>(Ty)) {
10912     Members = 1;
10913     switch (Base) {
10914     case HA_FLOAT:
10915     case HA_DOUBLE:
10916       return false;
10917     case HA_VECT64:
10918       return VT->getBitWidth() == 64;
10919     case HA_VECT128:
10920       return VT->getBitWidth() == 128;
10921     case HA_UNKNOWN:
10922       switch (VT->getBitWidth()) {
10923       case 64:
10924         Base = HA_VECT64;
10925         return true;
10926       case 128:
10927         Base = HA_VECT128;
10928         return true;
10929       default:
10930         return false;
10931       }
10932     }
10933   }
10934
10935   return (Members > 0 && Members <= 4);
10936 }
10937
10938 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate.
10939 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
10940     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
10941   if (getEffectiveCallingConv(CallConv, isVarArg) !=
10942       CallingConv::ARM_AAPCS_VFP)
10943     return false;
10944
10945   HABaseType Base = HA_UNKNOWN;
10946   uint64_t Members = 0;
10947   bool result = isHomogeneousAggregate(Ty, Base, Members);
10948   DEBUG(dbgs() << "isHA: " << result << " "; Ty->dump(); dbgs() << "\n");
10949   return result;
10950 }